blt::tree(3tcl)

โœจ blt::tree(3tcl) โ€” tree โœจ

Okay bestie, welcome to the BLT Built-In Commands zone. This is the manual page for tree, and it's giving main character energy. ๐ŸŽ€

๐ŸŒธ NAME ๐ŸŒธ

tree โ€” create and manage tree data objects. That's it. That's the name. Slay. ๐Ÿ’…

๐Ÿช„ 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 your bestie for creating, destroying, and giving Tcl access to a tree object. A tree object is literally an ordered tree of nodes where each node can have data key-values, tags, and a label. The treeview widget uses a tree object. No cap. ๐ŸŒณ

๐Ÿ‘‹ INTRODUCTION ๐Ÿ‘‹

Tree hands Tcl a rich API for managing complex data structures. Here's a simple example, bestie:

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 are lowkey iconic because they give you convenient -> indexing relative to a starting node. ๐Ÿฆ‹

Nodes may also be created with initial data values. Like:

$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. Periodt. ๐Ÿ“

๐Ÿงฌ 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. Bye bestie. ๐Ÿ‘‹

๐Ÿ“› 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. It's giving directory energy. ๐Ÿ—‚๏ธ

๐ŸŽ›๏ธ 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. 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. No takebacks. ๐Ÿšซ

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

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. Periodt. ๐Ÿ’€

๐Ÿงญ 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 way that works is so satisfying. ๐Ÿ˜Œ

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', 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. Big brain move. ๐Ÿง 

๐ŸŒณ 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. Obsessed. ๐Ÿ’–

  • 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. Family tree vibes. ๐ŸŒณ
  • 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. Multi-node slay. ๐ŸŽ€
  • 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 โ€” fires command once for every matching node โœจ. Right before command runs, the id of the node gets appended to it. You steer the whole operation with what command hands back: if command throws an error, processing stops immediately and the find operation returns an error ๐Ÿ˜ญ. But if command returns break, processing just stops โ€” no error generated, clean exit, we love that. And if command returns continue, processing stops on that subtree and picks up on the next one. ๐Ÿซถ
  • -postcommand command โ€” same deal, bestie: invokes command for each matching node, with the node's id appended before it's called ๐Ÿ’…. Return values run the show โ€” an error from command stops processing and makes the find operation return an error. A break return stops processing with no error generated. A continue return stops processing on that subtree and continues on the next. ๐ŸŽ€
  • -regexp string โ€” tests every node using string as a regular expression pattern. Regex girlies rise ๐Ÿฆ‹
  • -tag string โ€” only bothers testing nodes that have the tag string. No tag, no vibe check. ๐Ÿ’€
  • -usepath โ€” compares nodes using the node's full path. That full path is a list of labels, starting from the root of each ancestor and then 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 when the tree object was previously created via the C API (eg. via TreeView). Heads up: the current tree associated with treeName gets discarded ๐Ÿ˜ญ. And that's not all โ€” the current set of tags, notifier events, and traces are removed too. 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, you get an empty string back โ€” crickets, literally ๐Ÿฆ—. If first and/or last are given, they're the integer index of the children to display. Throw in the -labels option and you get labels instead of the nodes. โœจ

treeName copy srcNode ?destTree? parentNode ?switches?

Copies srcNode into parentNode. Both srcNode and parentNode have to already exist, no exceptions. The id of the new node is returned. You can copy from one tree to another โ€” if a destTree argument is present, it's 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 โ€” labels 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 says 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, because that would result in a cyclic copy and we do not do that here. ๐Ÿ™ˆ
  • -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?

Causes the creation of zero or more nodes โœจ. Exactly one of -num, -nodes, or -path is required โ€” pick one, bestie, not zero, not two. 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 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 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 look up 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. That's it, that's the whole command, and honestly? iconic. ๐Ÿ‘‘

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 that case, only its descendants are removed. The root node will remain, standing tall, main character energy. 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 โ€” order-keeping is a personality trait โœจ. Setting this to one has the same effect as using the -dictset flag at tree creation time. ๐ŸŽ€

treeName dump node ?switches?

Saves 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. Double confirmation, we love a thorough queen. โœ…

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 referrence.
  • -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 โ€” gives you a Tcl script to run on every single node that matched. If you also passed -var, then that variable gets set to the node's id right before each run. If you didn't, it falls back to percent substitutions instead โ€” and bestie, that is so much slower than going with -var or -command. Every eval result gets tacked onto the return listโ€ฆ unless your script throws a CONTINUE, in which case that node just gets skipped, no hard feelings. ๐Ÿ’…

The percent substitutions you can use 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, like "root->able->baker->charlie".
  • %r โ€” the -> delimited path from 0, like "0->able->baker->charlie".
  • %T โ€” the dot delimited tag path, like ".able.baker.charlie".
  • %V โ€” the value if you're using -key, otherwise the label.
  • %D โ€” the data for the node, i.e. the same thing get hands you back.
  • %% โ€” turns into one single percent sign.
  • -glob โ€” tests every node with global pattern matching, done kinda the same way string match does it. โœจ
  • -invert โ€” flips the pattern matching of -name. Negative queen behavior. ๐Ÿ™ˆ
  • -isarray โ€” only tests nodes where the -key value is an array. Cannot be combined with -name. The -invert flag flips what the check means. Heads up though: this will attempt to convert the key value in every node it traverses into an array type. ๐Ÿ‘€
  • -isempty โ€” only matches nodes where the -column key value was unset. Very "the void is valid" of it.
  • -isfixed โ€” only tests nodes that have used fixed 1.
  • -isleaf โ€” only tests nodes with no children. Baby-less nodes only. ๐Ÿ“
  • -isnotfixed โ€” only tests nodes that have not used fixed 1.
  • -istree โ€” only tests nodes with children.
  • -keycount num โ€” only tests if the number of keys equals num.
  • -key key, -keyglob key, -keyregexp key, -keyexact key โ€” compares the values of the data field keyed by key instead of the node's label. If you don't pass a -name pattern, then any node with this data key will match. The key names can themselves be patterns if you use -keyglob, etc. ๐ŸŽ€
  • -limit number โ€” stop processing after number matches (and number has to be a positive integer).
  • -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. lowercase rights. ๐Ÿซถ
  • -nodes tagnode โ€” search only inside tagnode, which is either a tag or a list of node ids. This is what makes nested searches possible. Note this option is incompatible with -top and -notop. โœจ
  • -notop โ€” exclude the -top or starting node.
  • -order string โ€” traverses the tree and processes nodes according to string. string can be one of these:
    • breadthfirst โ€” processes the node and the subtrees at each successive level. Every node on a level gets processed before moving down to the next level.
    • inorder โ€” recursively processes the nodes of the first subtree, then the node itself, then any of the remaining subtrees.
    • postorder โ€” recursively processes all subtrees before the node.
    • preorder โ€” recursively processes the node first, then any subtrees. This one's the default. ๐Ÿ‘‘
  • -usepath โ€” uses the node's full path when doing the comparison. The default is to compare only the node label.
  • -regexp โ€” tests every node using regular expression pattern matching.
  • -reldepth โ€” changes the meaning of -depth, -mindepth and -maxdepth so they're relative to the -top node.
  • -return key โ€” returns the value of the given key, or the empty string if there isn't one. If key is the empty string, the node label gets returned. If no value was found and key starts with a percent, it returns the substitution as per -exec. Note that a percent substitution longer than 2 chars will append values as list elements.
  • -strict โ€” generates an error if a given key value is unset when you're using -return. No silent vibes allowed. ๐Ÿ’€
  • -top node โ€” the search happens only at node and its descendants. 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 tests nodes that don't have the tag string.
  • -withtag string โ€” only tests nodes that do have the tag string.

treeName findchild node label

Searches for a child node label inside node. If it finds it, you get the id of the child node back. If not, you get -1. This is literally the same thing as index node->label. ๐Ÿฆ‹

treeName firstchild node

Returns the id of the first child in the node's list of subtrees. And if node is a leaf (aka it has no children), you get -1 instead. ๐Ÿ˜ญ

treeName fixed node ?isfixed?

Gets or sets the fixed key-fields flag for a node. New key-fields can only be added to a node if fixed is 0 (which is the default). If node is given as an empty string, it operates on the tree flag instead. Just so you know: copied and restored nodes do not preserve the fixed state. ๐Ÿ™ˆ

treeName foreach var tagnode script

Gives you a foreach loop for your tree. For every node in tagnode, the node-id gets assigned to var, and then script is evaluated. tagnode is either a tag or a list of nodes, exactly like the section NODE IDS AND TAGS above describes. โœจ

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 specific data field comes back. Normally it's an error if node doesn't contain the data field key โ€” but if you hand over a defaultValue argument, that value gets returned instead (and node still won't contain key, no cap). This is lowkey the move for accessing a data field of node without testing if it exists first. Heads up: this operation may trigger read data traces. ๐Ÿ‘‘

treeName incr node key ?amount?

Increments the value by 1, or by the given amount, and returns the value. The incr operation normally tries to use integers, but it uses doubles when either value or amount is a double.

treeName incri tagnode key ?amount?

The same as incr, except it accepts a multi-node tag and an undefined key gets initialized to 0. Returns the number of nodes that got updated. ๐Ÿ”ฅ

treeName index node

Returns the id of node. On top of the standard node id form, node can also be a path (a list of labels from the root) like the one path returns. If node is invalid, you get -1. ๐Ÿ’€

treeName insert parent ?switches?

Inserts a brand new node into the parent node parent. You get the id of the new node back. Here are the switches available:

  • -after child โ€” position the node after child. child has to be a child of parent.
  • -before child โ€” position the node before child. child has to 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 together with -names or -values.
  • -fixed bool โ€” if bool is 1, sets fixed field mode after initializing the key/value pairs from -data. This disallows creating new key fields once the node is created. If you don't pass it, the tree default for fixed gets used.
  • -label string โ€” designates the labels of the node as string. By default, nodes are labeled 0, 1, etc.
  • -names nameList โ€” the names for the data fields. This must be the same length as -values, and may not be used together with -data.
  • -node id โ€” designates the id for the node. Normally new ids are auto-generated, but this lets you create a node with a specific id. It's an error if that 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 just 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 an embedded space. ๐Ÿ’…
  • -values valueList โ€” the values for the data fields. This must be the same length as -names, and may not be used together with -data.

treeName is property args

Tells you a property of a node. Both property and args determine the property being tested. Returns 1 if it's true, 0 otherwise. These property and args combos 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 โ€” this one tells you whether node is the designated root of the whole situation ๐Ÿ‘‘. You can change which node is root with the root operation.

treeName ismodified ?nodeOrTag? ?isflag? ๐ŸŒธ

Get or set the modified state for the tree or for nodes. Here's how the arg count changes everything:

  • no args โ†’ returns the modified state for the tree
  • one arg โ†’ returns the modified state for a node
  • two args โ†’ sets the modified state for one or more nodes. And in that last case, when nodeOrTag is the tag all, the state for the tree gets set too. periodt.

Newly created nodes are always considered to be modified until you explicitly clear them. After clearing, subsequent updates to keys or tags will toggle the node (and the tree) modified again. it's giving "I will notice everything" energy ๐Ÿ’…


treeName isset node key โœ…

Return 1 if key is set in node.


treeName keys node ?tagnode ...? ๐Ÿ”‘

Return a list of unique keys for all of the given nodes in tagnode. The keys are in no particular order, so don't come for the ordering bestie, it's not that kind of function. Accepts nodes and tags or all. See also names.


treeName label node ?newLabel? ๐Ÿท๏ธ

Returns the label of the node designated by node. If newLabel is present, the node gets relabeled using it as the new label. glow up โœจ


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 it accepts a multi-node tag, and an undefined key will be initialized to {}. Returns the number of nodes updated. she's efficient like that ๐Ÿ’…


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. sad little leaf hours ๐Ÿƒ


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.

bestie listen: despite the error, all nodes that do have said fields get updated. so it's not all-or-nothing, it's "I did what I could and then yelled" ๐Ÿ˜ญ

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 โ€” that's a whole paradox, we don't do that here ๐Ÿ’€

The valid flags for switches are described below.

  • -after child โ€” position node after child. The node child must be a child of newParent.
  • -before child โ€” position node before child. The node child must be a child of newParent.
  • -pos number โ€” inserts node into parent's list of children at position number. The default is -1 to append the node.

treeName names node ?key? ?pattern? ๐Ÿ“›

Return key names for node, in the order defined (if possible).

  • If a key is given, attempts to return ARRAY fields (see DICT-ARRAYS).
  • If a pattern is given, the array keys are limited to those matching the glob pattern.

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 NOTIFY OPERATIONS 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. bye bye big object ๐Ÿซถ


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
  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. no prep needed, she handles it ๐Ÿงš

The valid switches are listed below.

Exactly one of -channel, -file or -data must be specified. one. not zero, not two. pick one bestie ๐Ÿ’…
  • -addtags โ€” list of tags to add to each node restored node. Each tag will be created only if a node loaded.
  • -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. main character behavior fr ๐Ÿ‘‘


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 DICT-ARRAYS 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. the switches, bestie:

  • -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.
  • -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. it's not a preview, it's a renovation ๐Ÿ˜ญ
  • -usepath โ€” compare the full path of each node. The default is to compare only the node label.

treeName sqlload ?switches? dbhfile sqlstmt

okay bestie this one is so fun ๐Ÿ’… โ€” it loads up your tree with the results of evaling the SQL in sqlstmt, using dbhfile. The evaluated SQL makes one tree-node per row of the result. What comes back to you is the number of rows that got loaded. And dbhfile is either an sqlite3 database handle, or an sqlite3 file. either one, she's flexible โœจ

Real talk though: sqlload can populate a tree with 10k nodes about 7 times faster than sqlite3 eval. And she doesn't lose anything on the way in โ€” she preserves NULL values and the object types (like int or double) that sqlite uses internally. Which means no sad little reconversion happening later inside the tree. See the SQLLOAD EXAMPLE below for the receipts. ๐Ÿซถ

The switches available are:

  • -addtags taglist โ€” the tags in taglist get added to each inserted node. Each tag only gets created if a node actually loaded. no node, no tag, that's the deal ๐Ÿ’…
  • -fixed โ€” sets the fixed flag, which disallows new keys after creation. lock it in, no new entries ๐Ÿ”’
  • -key name โ€” stores the entire result in the key name instead of making one key per column. You can then use array notation to get at the column results. This is more efficient since it initially stores just one object per row. Conversion to an array happens at the first array access (if that even occurs). lazy in the best way โœจ
  • -labelcol column โ€” the value of column is used as the label. By default the label is the node id.
  • -maprowid num โ€” this maps the node id to the rowid plus the constant num. The key for rowid will also not be created. This only applies if rowid is returned in the result-set of sqlstmt. If rowid isn't in the result set, this option is just ignored, no drama. If the mapping fails (because the tree already contains a requested node) the load aborts right there with an error ๐Ÿ’€. Also note num must be >= 1, because sqlite rowids start from 0, but the root node of the tree uses the node-id 0. math is math.
  • -max num โ€” the max number of rows to return. Default is 100,000. And ngl, SQL queries on large tables should probably always use LIMIT. just saying ๐Ÿ™ˆ
  • -nullvalue string โ€” defines the value to use for null values. The default is no value at all, meaning do not set the key if the value is null. Heads up: this is different from the sqlite Tcl extension, which uses an empty string for NULL. know the difference, bestie ๐Ÿ“
  • -parent string โ€” the node where results get inserted as child nodes. The default is the tree root.
  • -pathcol column โ€” name of the column containing the full path where the node is to be created. Works like -treecols, but uses a single column.
  • -skipcols columns โ€” the given columns are not added as keys. This is mostly useful in conjunction with -tagcol, -labelcol, and -pathcol.
  • -pos num โ€” where to insert into the parent's list of children. Default is -1, meaning append. end of the line, babe ๐ŸŽ€
  • -tagcol column โ€” the value of column gets added as a tag.
  • -treecols columns โ€” columns whose values, concatenated, give the path of where the node is to be created. Works like -pathcol, but uses multiple columns.

treeName sum ?switches? tagnode key ?key ...?

Adds up the values in the key fields for all of tagnode, and returns the sum. Values that aren't doubles (or integer) are just ignored โ€” they didn't make the cut, sorry ๐Ÿซถ

  • -diff value โ€” double value difference to ignore, and to not do an update for -runtotal. This is unused when you're using -int.
  • -force โ€” force the update of -runtotal even if the value was unchanged. Normally a check happens to avoid updating unchanged values.
  • -int โ€” use and accept only integer values.
  • -runtotal key โ€” place the running total in the given key field (if it changed).
  • -start num โ€” the start value for the sum: default is 0.

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

Like update, except it uses a string comparison to avoid writes if the value isn't going to change. Useful primarily for avoiding unnecessary write traces. minimal effort, maximum slay โœจ


treeName tag args

Manages tags for the tree object. See the TAG OPERATIONS 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 for a tag (which represents possibly many nodes). See the TRACE OPERATIONS section below. ๐Ÿ‘€


treeName type node key

Returns the type of the value. This is the introspected type from the Tcl_Obj value passed to set. it knows what it is ๐Ÿ’…


treeName update node key value ?key value...?

Like modify, except an error gets generated if a tag is used that applies to more than one node. one node only, she's exclusive ๐ŸŽ€


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 if node doesn't contain key โ€” no harm, no foul. What you get back is a count of the number of nodes unset. And this operation may trigger unset data traces. ๐Ÿงš


treeName values node ?key? ?withnames?

Returns values for node. The values come back in the same order as the keys returned from names. consistent, iconic, we love her ๐Ÿ‘‘

If a key is given, array values get returned for the key value. If withname is True, then key names are also returned along with the values. This differs from get in that the result is a true Tcl list object, not an array object. So if you're subsequently using an array value in a list context, this can be more efficient, because it avoids a split on string representations. efficiency is self care ๐Ÿ’…


treeName vecdump vector key ?tagnode?

Dumps the key field to a vector. With no tagnode, it dumps every node to the 1-1 corresponding vector index. With a tag, it dumps nodes to consecutive vector elements. ๐Ÿฆ‹


treeName vecload vector key ?tagnode?

Loads the key field from a vector. With no tagnode, it loads every node from the 1-1 corresponding vector index. With a tag, it loads nodes from consecutive vector elements. ๐Ÿฆ‹


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 option limits which keys may be assigned. If the script completes normally, and any of the key values changed in the variable, then the updates get reflected back into the key values (unless -noupdate is used). Unsetting a variable key will cause that change to be ignored. And new elements added to the array variable are ignored too. sorry new keys, not today ๐Ÿ™ˆ

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 becomes the return code to the caller. Which means a break, continue, and return will propagate up through multiple nested with statements, all the way to an enclosing foreach, while, etc. But -break can be used to change that, making with behave more like a foreach loop. know the rules before you break them โœจ

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. planning ahead is main character energy ๐Ÿ’–

If the variable name string is zero length, then 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 a 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't 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 does not copy changed variables back into tree nodes.
  • -unset โ€” unset the array variable at the beginning of each evaluation.

๐Ÿ’– DICT-ARRAYS ๐Ÿ’–

okay bestie listen, this is SO cool. You can use round braces to grab sub-values of a key value ๐Ÿซถ. Basically each key value gets to be a whole array (or dict) all by itself, like a little nested universe. Example time:

        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, no cap. If it's not, then on access it converts the value to a pure array hash object. The next example shows the type in a comment after each operation, so you can watch it shapeshift โœจ:

        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 (so no, you cannot tag something 7, that's a node id's job, mind your business ๐Ÿ’…). 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 behaviour, fr fr.

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, it just creates the tag. Returns a count of the number of nodes tagged. Casual.
  • treeName tag delete string node... โ€” Removes the tag string from one or more nodes. Returns a count of the number of nodes visited. Calling tag delete with a builtin tag is ignored (it's just gonna sit there and pretend it didn't hear you ๐Ÿ™ˆ).
  • treeName tag dump tagnode ?switches? โ€” Dumps 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, returns 1 (or 0) if the node has (or hasn't) the tag. Otherwise, returns 1 if at least one node 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. Chill like that.
  • treeName tag lookups ?pattern? โ€” Dumps 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. This is the one you want when things get BIG ๐Ÿ”ฅ.
  • 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 the given string tag. If no node is tagged with any of the string, then an empty string is returned. RIP, empty string ๐Ÿ’€.

๐Ÿ” 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 on the whole key value, not the individual array element. Important, bestie, don't forget it.

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. It's giving surveillance but make it โœจhelpfulโœจ.

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 (no infinite loops, we're not doing that today ๐Ÿ™…).

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 bestie, so notify is literally the "hey, something structural just happened on this tree, come get your girl" system. ๐Ÿ’… The purpose of notify is to get control when structural operations occur on a tree. This is 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.

The general form of notify is:

treeName notify operation ?arg?...

The available operation are as follows:

๐ŸŒธ 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 occured. If an error is returned by command the invoking operation returns an error (when not using -whenidle). One or more of the following switches are used to indicate the events that are of interest:

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


That's the whole vibe. Sourced from BLT 2.5, page blt::tree(3tcl) โ€” the footer didn't list a date, but the version is right there. ๐Ÿ’–โœจ

๐Ÿ“ฆ where this page comes from