tree(n)

๐Ÿ“ฆ version 2.5.3, in nixpkgs unstable

๐Ÿ’– NAME ๐Ÿ’–

tree(n) โ€” from BLT Built-In Commands โ€” is the page for tree: create and manage tree data objects. ๐Ÿซถ

โœจ SYNOPSIS โœจ

tree create  ?-fixed? ?-dictset? ?-keyhash N? ?treeName?

tree destroy treeName...

tree names ?pattern?

tree op subcmd ?subsubcmd ...? treeName ?arg arg ...?

๐Ÿฆ‹ DESCRIPTION ๐Ÿฆ‹

Okay so the tree command is used to create, destroy, and provide Tcl access to a tree object. A tree object is an ordered tree of nodes where each node can have data key-values, tags and a label. The treeview widget uses a tree object. ๐Ÿ‘‘

๐ŸŒˆ INTRODUCTION ๐ŸŒˆ

Tree gives Tcl a rich API for managing complex data structures. Hereโ€™s a simple example:

set t [tree create]
set id [$t insert 0]
$t set $id X 2
set n [$t get $id X]

# Create a node with label
$t insert 0 -label A
$t set 0->A    X 1
set n [$t get 0->A X]

Labels provide convenient -> indexing relative to a starting node. ๐ŸŽ€

Nodes may also be created with initial data values.

$t insert 0 -label A -data {X 1   Y "a 1 b 2"}
$t incr  0->A X 3
$t set   0->A Y(a) 4

Note round braces are used to access sub-values in a dict-array. See the section DICT-ARRAYS below for details. ๐Ÿซถ

๐Ÿ› ๏ธ SYNTAX ๐Ÿ› ๏ธ

๐ŸŒŸ tree create ?-fixed? ?-dictset? ?-keyhash N? ?treeName?

Creates a new tree object. The name of the new tree is returned and a Tcl command is created. 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. A tree name (if given) can not start with a dash. Tree names containing the substring "#auto" will be replaced with a generated identifier. For example, the name data#auto will translate to datatree0. Note that when the Tcl command is deleted the tree object also gets 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. This includes dict-array keys. See the fixed sub-command.
  • -dictset โ€” Define that any update of an array field will coerce the array object to a dict object. A dict will preserve order of sub-field keys on update. See the dictset sub-command.
  • -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). ๐Ÿงš

๐ŸŒฟ tree destroy treeName...

Releases one or 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 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 being self-documentating, it allows wize to provide support checked tree calls. Iykyk. ๐Ÿ˜Œ

๐Ÿ‘‘ NODE IDS AND TAGS ๐Ÿ‘‘

Nodes in a tree object may be referenced by id or by tag. Each node has a unique serial number or id that is assigned to it at creation. The id of a node never changes or is reused unless all nodes in a tree are deleted.

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 can 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. A node-list may contain only integers, and can not have leading spaces. Node-lists simplify the use of iterating commands because it avoids excessive use of eval. ๐Ÿซถ

There are four built-in or โ€œpsuedoโ€ 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 after ->. 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', or label โ€” Selects the child node whose label is label. Enclosing label in quotes (double or single) supports labels with embedded spaces and prevents matching reserved words (eg. a node labeled "parentnode"). If multiple child nodes have the same label, the first matching 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 which returns -1, allowing you 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 node, 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

For the key selectors above: 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.

Okay, back into the find switch pile โ€” sheโ€™s still going and honestly, iconic:

  • -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 attach ?-notags? ?treeObject? โ€” Queries or attaches to an existing tree object treeObject. This is primarily used where the tree object was previously created via the C API (eg. via TreeView). The current tree associated with treeName is discarded. In addition, the current set of tags, notifier events, and traces are removed. If -notags is given, tags will not be shared.
  • 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. Heads up, bestie: cyclic copy is not it.
    • -reverse โ€” Reverse the direction of the copy.
    • -tags โ€” Copy tag information. Normally the nodeโ€™s label and data fields are copied; 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 value is the id of the last created node (or -path element). The valid flags for switches are described below.
    • -fixed โ€” Set the fixed flag.
    • -data list โ€” Data to set in each node.
    • -labelstart number โ€” The labels of generated nodes use a sequence number starting from number. The default is to just use the node id.
    • -nodes list โ€” List of node 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).
    • -pos number โ€” The position where to insert child nodes. The default is -1, meaning append.
    • -prefix str โ€” String prefix to add to each nodeโ€™s label.
    • -start number โ€” Node number 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 dictset ?bool? โ€” Get or set the dictset flag for the tree which causes any set of an array sub-fields to force the value to type dict. Unlike array types, dicts preserve the order of elements. Setting this to one has the same effect as using the -dictset flag at tree creation time.
  • 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 of key/value pairs representing the nodeโ€™s data fields, 3) a sublist of tags, and 4) the label. This returned list 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 the given channel chan. The channel is not closed afterwards.
  • -file fileName โ€” Obtain data from the file fileName. This option 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. The tag will be created even if no nodes are tagged.
  • -column key โ€” Use value with field given by key. Like the treeview find -column option, this key may contain an array reference.
  • -cmdargs columns โ€” Specify columns whose values are to be appended to -command.
  • -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. If command returns return, then the returned integer is used to indicate 1 for match or 0 for mismatch.
  • -count โ€” Just return the number of matches.
  • -depth number โ€” Include only nodes with level equal to number.
  • -exact โ€” Matches each node exactly.
  • -exec script โ€” hands you a Tcl script that gets evaluated once for every matching node. If you also passed -var, then that variable gets set to the node's id before each evaluation. If you didn't pass -var, percent substitutions happen instead โ€” and heads up, that route is much less efficient than using either -var or -command. ๐Ÿ˜ฌ

Whatever each eval returns gets appended to the return list โ€” unless the script throws a CONTINUE, and then that node just gets skipped, no drama. โœจ

The percent substitutions available 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 works in a fashion similar to that used by the string match.
  • -invert โ€” inverts the pattern matching of -name. Flip it, reverse it, icon behavior. ๐Ÿ”„
  • -isarray โ€” only test nodes where the specified -key value is an array. Can not be used with -name. The -invert flag flips the meaning of the check. Ngl, this one's a little nosy: it will attempt to convert the key value in each traversed node into an array type. ๐Ÿ™ˆ
  • -isempty โ€” only match nodes where the specified -column key value was unset.
  • -isfixed โ€” only test nodes that have used fixed 1.
  • -isleaf โ€” only test nodes with no children. Baby nodes only. ๐Ÿ“
  • -isnotfixed โ€” only test nodes that have not used fixed 1.
  • -istree โ€” only test nodes with children.
  • -keycount num โ€” only test if the 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. Know when to say when. โœ‹
  • -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. Case is not the moment, bestie. ๐Ÿ™…
  • -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 these:
    • 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 then any of 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 gets returned. If no value was found and the given key starts with a percent, returns the substitution as per -exec. โš ๏ธ Note that a percent substitution longer than 2 chars will append values as list elements.
  • -strict โ€” generate an error if a given key value is unset when using -return. No silent little empty-string gremlins. ๐Ÿ’€
  • -top node โ€” search is only at node and its descendants. The default is the root node.
  • -var variable โ€” a variable to set with the node id before each iteration of the -exec script.
  • -withouttag string โ€” only test nodes that don't have the tag string.
  • -withtag string โ€” only test nodes that 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. First born energy, honestly. ๐Ÿ‘‘

treeName fixed node ?isfixed?

Get or set the fixed key-fields flag for a node. New key-fields can be added to a node only if fixed is 0 (the default). If node is given as an empty string, it operates on the tree flag. ๐Ÿ“Œ Note that copied and restored nodes do not preserve the fixed state โ€” so don't come for me when it resets.

treeName foreach var tagnode script

Gives you 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 NODE IDS AND TAGS 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. Normally it's an error if node doesn't contain the data field key โ€” but if you provide a defaultValue argument, this value gets returned instead (node will still not contain key, don't get it twisted). ๐Ÿซถ This feature can be used to access a data field of node without first testing if it exists. Note this operation may trigger read data traces.

treeName incr node key ?amount?

Increment value by 1 or the 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. Math is mathing. ๐Ÿ”ฅ

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. Multi-node slay. โœจ

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 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.
  • -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, the tree default for fixed is used.
  • -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 lets you create a node with a specific id. It's an error if the id is already used by another node in the tree. โš ๏ธ
  • -pos number โ€” inserts the node into parent's list of children at position number. The default is to append.
  • -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 -names, 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 โ€” tells you whether this node is the designated root. You can flip that with the root operation, iykyk.


๐Ÿ’… And now, bestie, the actual operations. There are a lot of them, so buckle up โ€” they're all lowkey iconic in their own way.

  • treeName ismodified ?nodeOrTag? ?isflag? โ€” get or set the modified state for the tree or for nodes. No args โ†’ you get the modified state for the tree. One arg โ†’ modified state for a node. Two args โ†’ you set the modified state for one or more nodes; and if ?nodeOrTag? is the tag all, the state for the tree gets set too. โœจ

Newly created nodes are always considered modified until you explicitly clear them. After clearing, any subsequent updates to keys or tags will toggle the node (and the tree) modified all over again.

  • treeName isset node key โ€” returns 1 if key is set in node. Simple as that, no cap. ๐Ÿซถ
  • treeName keys node ?tagnode ...? โ€” returns a list of unique keys for all the given nodes in tagnode. Keys come back in no particular order (chaos, honestly). It accepts nodes and tags, or all. Also go peek at names. ๐Ÿฆ‹
  • treeName label node ?newLabel? โ€” returns the label of the node designated by node. If newLabel is present, the node gets relabeled with it. Glow-up incoming ๐Ÿ’…
  • treeName lappend node key value ?value ...? โ€” append one or more list values to node/key value. Stack 'em up ๐Ÿ“
  • treeName lappendi tagnode key value ?value ...? โ€” same as lappend, except it accepts a multi-node tag, and an undefined key gets initialized to {}. Returns the number of nodes updated. Very "batch processing main character energy". ๐Ÿ‘‘
  • treeName lastchild node โ€” returns the id of the last child in the node's list of subtrees. If node is a leaf (no children), you get -1. Sad but true ๐Ÿ˜ญ
  • treeName modify tagnode key value ?key value...? โ€” update one or more fields in one or more nodes in tagnode. Just like with set, node can be a tag that refers to multiple nodes. This is identical to set, except it throws an error if any of the key fields don't exist. And despite the error, all the nodes that do have the said fields still get updated. โœจ For modifying a single node, go see update.
  • treeName move node newParent ?switches? โ€” moves node into newParent. The node gets appended to the list of children of newParent. โš ๏ธ node can not be an ancestor of newParent โ€” that's a no-no. The valid flags for switches are:
    • -after child โ€” position node after child. The child node must be a child of newParent.
    • -before child โ€” position node before child. The child node must be a child of newParent.
    • -pos number โ€” inserts node into the parent's list of children at position number. The default is -1, which appends the node.
  • treeName names node ?key? ?pattern? โ€” return key names for node, in the order defined (if possible). If a key is given, it attempts to return ARRAY fields (check the DICT-ARRAYS section ๐Ÿ‘€). If a pattern is given, the array keys are limited to the ones matching the glob pattern. An error gets thrown if the convert-to-array fails (like, list-length-is-odd kind of fail ๐Ÿ’€). You can use the type command 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, you get -1. The end, bestie ๐ŸŽ€
  • 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, -1 shows up. ๐Ÿ˜ญ
  • treeName nodeseq ?start? โ€” get or set the start sequence number for subsequent node insertions that aren't using -node. The default is 0. ๐Ÿ”ข
  • treeName notify args โ€” manages notification events that indicate the tree structure has been changed. Go read the NOTIFY OPERATIONS section below, bestie. ๐ŸŒธ
  • treeName oldvalue ?newvalue? โ€” returns the value from before the last (untraced) change operation. This is used primarily by write traces that want to restore a key to its pre-write value (think read-only variables, cute little time capsules). The oldvalue is saved internally every time 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 gets 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, you get -1. No parent, no problem ๐Ÿฆ‹
  • treeName path node ?delim? ?prefix? โ€” returns the full path (from the root, obviously) of node, using the node labels. If delim isn't specified, the result is a list. Otherwise, the result is a string starting with prefix, with each element of the path separated by delim. That second form is perfect for building tags like: .able.baker โœจ
  • treeName position ?-sort? ?-format ftype? node ?node ...? โ€” returns the position of the node(s) in their parent's list of children. Positions are numbered from 0, and 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, you get -1. Back it up ๐ŸŽ€
  • 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, you get -1. ๐Ÿ˜ญ
  • 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 dump returns. It's a list containing information for each node to be restored, and that info 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, and they can be listed in any order. If a node's path describes ancestor nodes that don't already exist, they get automatically created. Magic โœจ๐Ÿงš

โš ๏ธ The valid switches are listed below, and exactly one of -channel, -file or -data must be specified.

  • -addtags โ€” list of tags to add to each restored node. Each tag will be created only if a node loaded.
  • -channel chan โ€” obtain data from the given channel chan. The channel is not closed afterwards.
  • -data string โ€” data input comes from the given string.
  • -file fileName โ€” obtain data from the file fileName. โš ๏ธ This option is unsupported in a safe interp (sorry bestie).
  • -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 at all. Tags? Never heard of her ๐Ÿ’€
  • -overwrite โ€” overwrite nodes that already exist. Normally nodes are always created, even if a node with the same name already exists. This switch says "actually, overwrite the existing node's data fields." ๐Ÿ”ฅ
  • treeName root ?node? โ€” returns the id of the root node. Normally that's node 0. If a node argument is provided, it becomes the new root of the tree โ€” which lets you temporarily work inside a subset of the tree. Changing the root affects operations like next, path, previous, etc. Main character energy, honestly ๐Ÿ‘‘
  • treeName set tagnode key value ?key value...? โ€” sets one or more data fields in node. tagnode may be a tag representing several nodes, and in that case you get a count of how many nodes were updated. key is the name of the data field to be set, or an array-like reference such as field(subkey) โ€” see the DICT-ARRAYS section below. value is the respective key's value. The key will be created if it doesn't exist (check modify for the stricter version). ๐Ÿซถ

The set operation triggers write and create data traces.

  • treeName size node โ€” returns the number of nodes in the subtree. This includes the node itself and all its descendants. The size of a leaf node is 1. Baby tree ๐ŸŒฑ
  • treeName sort node ?switches? โ€” return nodes in sorted order. Finally, some order in this chaotic world ๐Ÿ˜Œ
    • -ascii โ€” compare strings using the ASCII collation order.
    • -command string โ€” use command string as a comparison command. To compare two elements, it evaluates 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 (biggest items come first, periodt).
    • -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 as characters. For example, in -dictionary mode, bigBoy sorts between bigbang and bigboy, and x10y sorts between x9y and x11y. Obsessed with this one ngl ๐Ÿง โœจ
    • -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. Like, actually move stuff around. Be so for real right now.
    • -usepath โ€” compare the full path of each node. The default is to compare only the node label.

sqlload โ€” the bulk-loading queen ๐Ÿ‘‘

treeName sqlload ?switches? dbhfile sqlstmt

Okay so this one is a whole mood. It loads your tree with the results of evaling the SQL in sqlstmt using dbhfile. The evaluated SQL creates one tree-node per row result. And the returned value? The number of rows loaded, bestie. Dbhfile is either an sqlite3 database handle, or an sqlite3 file.

Not to be dramatic but โ€” sqlload 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. Which eliminates later reconversion within tree, so likeโ€ฆ no extra work, we love efficiency ๐Ÿ’…. See the SQLLOAD EXAMPLE below.

The following switches are available:

  • -addtags taglist โ€” the tags in taglist to add to each inserted node. Each tag will be created only if a node loaded. โœจ
  • -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.
  • -pos num โ€” where to insert into parents list of children. Default is -1, meaning to append.
  • -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.

sum โ€” math time, grab a calculator ๐Ÿงฎ

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. Simple as that, no cap.

  • -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.

supdate โ€” the polite update ๐ŸŒธ

treeName supdate node key value ?key value...?

Like update, but uses a string comparison to avoid writes if the value will not be changed. This is useful primarily for avoiding unnecessary write traces. Basically it's the โœจconsiderateโœจ version of update โ€” it checks before it commits. ๐Ÿ’…


tag โ€” tag 'em up ๐Ÿท๏ธ

treeName tag args

Manages tags for the tree object. See the TAG OPERATIONS section below.


trace โ€” watch it like a hawk ๐Ÿ‘€

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 TRACE OPERATIONS section below.


type โ€” what even are you rn ๐Ÿ”

treeName type node key

Return type of value. This is the introspected type from the Tcl_Obj value passed to set. It's giving main character introspection energy.


update โ€” the classic โœ๏ธ

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. So likeโ€ฆ one at a time please, no group edits. ๐Ÿ˜ญ


unset โ€” bye-bye field ๐Ÿ‘‹

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.


values โ€” all the values, as a real list ๐ŸŽ€

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. Slay, honestly. โœจ


vecdump โ€” tree goes into the vector ๐Ÿฆ‹

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.


vecload โ€” vector comes back into the tree ๐ŸŒˆ

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.


with โ€” the loop that eats ๐Ÿ’€โœจ

treeName with variable ?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. New elements added to the array variable are ignored.

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, making with behave more 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(#) (which could then 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, and -init can be used to specify a default value. Also, long running queries can speed up by initializing variables prior to the call to with.

If the variable name string is zero length, an simple variables are used instead of an array, and * and # do not get set. Note, when not using -keys, arbitrary local variables can get overwritten. โš ๏ธ

If -array is used, with operates on the keys of an tree array/dict instead of the keys of the node.

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-dict. The fields of the array for that one key are then used (instead of keys from the whole node). This changes the meaning of -keys and -glob to be the keys of the array rather than the keys of the node. Nodes missing the given array key will be skipped. 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.
  • -init value โ€” variables specified by -keys are to be initialized to value for each node where key is missing.
  • -keys keylist โ€” copy only the named keys and does not set (*).
  • -glob pattern โ€” pattern to limit matching keys. Can not be used with -keys.
  • -noupdate โ€” ignore changes to array variables. This do not copy changed variables back into tree nodes.
  • -unset โ€” unset the array variable at the begin of each evaluation.

๐Ÿ“ DICT-ARRAYS ๐Ÿ“

Okay so bestie, this is where it gets good. Round braces can be used to access sub-values of a key value. In effect, this means each key value can be an array (or dict), eg.

set t [tree create]
set n [$t insert 0 -data {a 1   b 2   c "x 9 y 8 z 7"}]
$t get $n;          #  a 1 b 2 c {x 9 y 8 z 7}
$t get $n c;        #  x 9 y 8 z 7
$t get $n c(y);     # 8
$t update $n c(y) 8.6
$t get $n c;        # x 9 y 8.6 z 7
$t unset $n c(y)
$t get $n c;        # x 9 z 7
$t set $n d 10
$t incr $n d

If a key value is a dict object, tree will make use of it. If not, on access it converts the value to a pure array hash object. The following example shows the type in a comment after each operation. ๐Ÿ’…

set t [tree create]
$t insert 0 -label A;
$t set   0->A  X [dict create a 1 b 2 c 3];   # dict
array set q { x 1 y 2 };
$t set   0->A  Y [array get q];               # dict
$t set   0->A  Z {m 0 n 1};                   # string
$t incr  0->A  Z(m);                          # array
dict size [$t get 0->A Z];                    # dict

One advantage of using a dict is that it preserves order. See dictset.


๐Ÿ’œ 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. Iconic.

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 their tag. Note: operations on arrays trigger on the whole key value, not the individual array element. ๐Ÿ‘‘

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 identifers for all the current traces.

โœจ NOTIFY OPERATIONS โœจ

Okay so the whole point of notify is literally to get control when structural operations happen on a tree. Itโ€™s used internally by treeview or example when a tree object is shared. A client may create nodes, sort a tree, move a node, etc. Notifier can cause such operations to generate events, resulting in Tcl commands being executed. Itโ€™s giving โ€œtree activity livestream,โ€ no cap. ๐Ÿ‘‘

The general form of notify is:

treeName notify operation ?arg?...

Available operations are as follows, bestie:

๐ŸŽ€ 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 (controlled by 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 occurred. If an error is returned by command the invoking operation returns an error (when not using -whenidle). One or more of these switches tell the tree which events youโ€™re interested in:

  • -bgerror โ€” Generate a background error if an error occurs.
  • -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.
  • -disabletrace โ€” Disable traces from firing during a notify event.
  • -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. So cute, so useful:

               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. Nested-tree realness, periodt:

               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 โ€” and yes, it ate:

                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. Important caveat, bestie โ€” donโ€™t forget it. ๐Ÿ’…

โญ C LANGUAGE API โญ

The C-language glow-up list is literally all of these, exactly as named:

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

Cute footer realness: this whole page is brought to you by BLT, version 2.5, for tree(n) โ€” the date is lowkey not showing up in this footer, bestie, but the vibe is timeless ๐Ÿ’–๐ŸŒˆ๐Ÿ’…๐Ÿซถ

๐Ÿ“ฆ where this page comes from
  • nixpkgs unstable: blt 2.5.3
  • ๐Ÿ’– girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms