NAME
textblocks - additional text widget subcommand for Tk distribution.
SYNOPSIS
.widgetName block subcommand ?opt opt ...?
.widgetName mark data markName ?value?
.widgetName tag data tagName index ?value?
.widgetName configure -getFlags integer
What else is in the widget?
The other difference with the stock Text widget is the object oriented dump. It dumps a list of objects which represent the contents of the widget in the given range. The temporary position for this command is
.widget block list from to
An object is a real object in Perl, and a list with a first element being the class id in TCL (the rest being the contests, in what follows the first element of the rest is referenced as the first element of the object).
The particular elements of the list represent:
- String
-
An object with contents being the string. Object class is
Tk::Text::String, class id isS. - Marks
-
The contents is the name of the mark, the classes are
Tk::Text::MarkLeftwith idL, andTk::Text::MarkRightwith idR. A mark that has a value (see Values) is listed as a list of the name and a copy of the value,[name, value], instead of a reference to the name, as for tags. When a list is inserted back (the undo does this with its own lists), a mark element of this form gives the mark that value (the value the mark had is freed when the widget command returns); a reference to a name leaves the value of an existing mark as it is. The marksinsertandcurrentare not set from a list, nor are their values. - Tags
-
The contents is the name of the tag, the classes are
Tk::Text::TagOnwith idT, andTk::Text::TagOffwith idt. The start of a run of a tag that has a value (see Values) is aTk::Text::TagOnholding a list of the name and a copy of the value,[name, value], instead of a reference to the name; code that reads the name should accept both forms:my $name = UNIVERSAL::isa($elt, 'ARRAY') ? $elt->[0] : $$elt; - Window
-
The contents is a list of the name of the window and the script to create the window, followed by the options of the window as option/value pairs:
-window(the path name, if the window exists),-create(if there is a script),-align,-padx,-padyand-stretch; the class isTk::Text::EmbWinwith idW. Undo re-creates the window segment from the options. - Image
-
The contents is a list of the name of the image in the widget, followed by its options as option/value pairs:
-image(if it has one),-align,-padxand-pady; the class isTk::Text::EmbImagewith idI. Undo re-creates the image from the name and the options. - block
-
A block is dumped as a list of
- type
-
The first element is a list of block name, depth and (optionally) instance data and node values. The node values are there when a node of the block has a value (see Values) and the whole block is in the listed range; the third element is then
undefif the block has no instance data. They are written as the tree: a node as a list of its value followed by its children, a leaf as a list of its value, withundeffor a node without a value. For a fraction with valueRon the root andNon the numerator the first element is['Fraction', 0, undef, ['R', ['N'], [undef]]] - contents
-
The rest of the list represents the contents of the block in the same form as the top-level dump, with exception for inter-leaf separators.
The inter-leaf separators are dumped as on object of class
Tk::Text::BlockSeparator, with id|, the contents being the "depth" of the separator. Note that the minimal possible depth is 0, for separators between leaves of the same parent; 1 is a separator between leaves whose parents are siblings, and so on.
The object class in Perl is
Tk::Text::Block, the class id isB. - Empty
-
An empty block is dumped in the same way with the object class being
Tk::Text::Empty, the class id beingE. The contenst is the list of the block name, and (optionally) instance data.
What is a block?
A Block is an additional editable unit of information for inclusion into widget. Block consists of block type, block contents, and, possibly, block instance data. Block contents is a tree whose leaves can contain anything that can be in a row in a text widget (including other blocks). Block instance data can be arbitrary data as in a language variable.
Current implementation allows only trees with the distance from root to leaves being the same for all the leaves.
Examples of blocks
Here we provide several examples on the internal structure of blocks that can implement the following objects. To see how the internal structure (does not) correlate with the visual appearance, see "Display of blocks".
- Button
-
___ Text to show when released / \___ Text to show when pressed - Multilevel sub-super-script
-
__ First superscript / /\__ Second superscript / \ __ First subscript \ / \/___ Second subscript \ \__ Third subscript - Radical
-
___ Text to show inside - Tabulation
-
(Empty)
Indices in blocks
A block occupies the following place in the index space: 1 index unit for the start of the block, then all the leaves separated by 1 index separators, and 1 index for the end of the block. Thus a block with one empty leaf occupies 2 index units.
An empty block (without leaves) occupies 1 unit of the index space.
Note that a block (however complicated) always fits in one line of the index space. In particular, the usual bindings for up and down will move you out of a block. (You should expect it, since leaves of a block may be placed one under another, but may be not.)
String representation of blocks
The commands that convert block contents to string (.t get, selection and search) see the contents of a block as a string of the same size as the size of block in the index space. The start of the block looks like {, end like }, interleaf separators like |.
An empty block looks like ..
Note that a string representation of a block (however complicated) always fits in one line.
Insertion in blocks
Insertion changes contents of the block if the insertion point is inside the block, i.e., after starting index of the block and before the ending position (and not inside some other block contained in the given one). Note that it is impossible to be inside an empty block.
If inserted text contains no newlines, it is added to the leaf of tree the insertion point is in (i.e., at or after the start of, and before the end of). If it contains newlines, then the resulting leaf is split into several at the inserted newlines. All the new leaves have the same parent node as the initial leaf. Registered callback will be called on insertion of newlines (not implemented).
Destruction of blocks
When the block is destructed, it contents is merged into the surrounding environment. Block's head and tail disappear, interleaf separators behave like newlines. I.e., if block was contained in another block, interleaf separators of deceased block became interleaf separators of the parent block, otherwise they became line separators in the text widget.
Deletion of text in blocks
If the deletion range does not include any index unit occupied by the block, the block does not change.
If a range contains a block as a whole, block is deleted. Registered callback will be called (not implemented). Same happens if the range contains all the block except either head or tail index.
Otherwise, if the range includes head or tail of the block, the block is destroyed, and what remains of the contents is merged into enclosing structure as is described in "Destruction of blocks".
If a range is completely contained inside some leaf, the inner structure of the block does not change (but if a leaf becomes empty, registered callback will be called (not implemented)).
If the range contains leaves separators, two survived leaves are merged together. If their parents were different, they are also merged together, and the process continues until the common parent is met. This is exact opposite to the
block split ??subcommand that would create this separator. Registered callbacks are called (not implemented).
Tags and blocks
Characters inside leaves can be tagged in the usual way. Interleaf separators and tail of the block behave like end-of-lines when tagged. tag names at the start of a block reports the tags in effect there; for drawing, a tag that switches off inside the block does not style the block as a whole.
Bounding boxes
If index in the text corresponds to a character in a leaf of a block, it behaves as usual.
If the index corresponds to the interleaf separator or tail of a block, the bounding box of the preceeding leaf is returned.
If the index corresponds to the head of the block, the bounding box for the whole block is returned.
Bounding box for anything invisible is of size 0 and at the upper-left corner of the block.
Display of blocks
The display of blocks is completely customizable. It is based on the current configuration of the type of displayed block.
If no customization is registered for the block, then the tree structure is ignored, all the leaves are drawn on the display one under another, left justified, with wrap enabled, and the resulting object is vertically centered about the middle of the ascent of the default font. In what follows we refer to this behavior as default layout.
If the block registers a layout callback, it will be called when the block is about to be drawn. This procedure takes the information on the size the leaves take on the display, and returns information on what size the block takes on the display and what should be relative offsets of leaves in the resulting rectangle. Details are subject to change. No clipping is performed.
Layout callback can also specify which leaves should not be shown at all, and what additional details to show in the rectangle.
(Not implemented)
Block can also specify that some leaves have some additional tags.
Layout callback
Layout callback is the main component of the block.
Details are subject to change.
A layout procedure takes a variable number of input arguments. The first element is a list containing the block name and widget name, (possibly with an addition, say, if instance data is present in the block, it will be the next element). The second element gives the horizontal offset of the start of the block inside the ambient line (it can be different from the absolute horizontal position if the block is inside some other block). The remaining elements specify the tree structure of the block and the layout details of the leaves. Any child of the root node of the tree provides one argument of the function. All the arguments are lists, and
if the child is a leaf, then the list consists of the repeat count (necessarily 1), current
yoffset inside the block, width, total width, height, baseline, and some additional data on the leaf (last part is not implemented, but it will contain horizontal stretchability of the leaf, vertical one and stretchability of the baseline).If the child is a node, the list elements are themselves lists that are obtained using the same rules recursively: if children are leaves, the elements are lists of numbers, otherwise lists of lists.
If block is configured to lie to the layout procedure about its contents, it can present several lines or a whole subtree of itself in the same form as a single leaf. In this case the repeat count above can be bigger than 1.
Summary:
- Input arguments:
-
{bname wname ...} ho {rc yo w tw h b hs vs bs} ... - Abbreviations:
-
BlockNAME, WidgetNAME, Horizontal Offset, Repeat Count, Y Offset, Width, Total Width, Baseline. hs, vs, bs are currently not used.
The return value of the callback must be a list. The length of the list (counting multiplicities, see below) must be at least the number of leaves plus one. The first element of the list specifies the layout information on the block as a whole, the others specify layout information for the leaves and (possibly) additional elements to show.
There are three possible formats of the elements in this list. All are lists of numbers (and should be of the form {dd ... dd}) of lengths 1, 7, or 13. The first number is either repeat count, or id of additional line to show (i.e., the same data as returned by textWidget block addline index command). Lists of different length have the following meaning:
- 1:
-
the child is not shown at all. This format is prohibited for the layout information of the block as a whole and for additional lines. The only element of the list is the repeat count.
- 7:
-
If the block as a whole is not laid out yet, this is the information about it, and all the elements but what describe width, height and baseline are ignored. If not all the leaves are laid out yet, the first element is the repeat count, what means the number of leaves that are described by this list (it can be 0).
The remaining elements of the list provide x and y offsets of the upper-left corner inside the ambient block, width, total width, height, and baseline of the block as a whole, or of a group of leaves, or a leaf. If it describes a group of leaves, the leaves are laid out as by default layout procedure. Width, height, and baseline information is used for displaying background of the line.
If all the leaves are laid out, then this list describes an additional element to draw if the first element is greater than 0, i.e. it is considered a Block ID of an additional drawing element, and the rest specifies the layout of this element. If it is 0, then this element of the list is ignored exactly as in other cases.
- 13:
-
(not implemented, but accepted by the widget): the first 7 elements have the same meaning as above, the last 6 provide stretchability x and y position of upper-left corner, width, total width, height, and baseline.
The total width above is the width of the leaf including the space reserved for showing the background of the leaf terminator.
Summary:
- Return list elements:
-
{Block Layout} {Leaf0 Layout} ... {Leafn Layout} {Additional Element0 Layout} ... {Additional Elementn Layout} - Layout Styles
-
Block Layout -
{ig ig ig w ig h b}Show one or more leaves -
{rc xo yo w tw h b}Hide one or more leaves -
{rc}Show Additional Elements -
{bi xo yo w tw h b}(
wis not very important), put after leaves.
- Abbreviations:
-
IGnored, Width, Total Width, Height, Baseline, XOffset, YOffset, Repeat Count, Block Id
None of the returned date is used for clipping. However, it is used in directing the mouse events and reporting bounding boxes.
Lying to layout callback
It is possible to configure a block to lie about its structure to the layout callback. This can greatly simplify writing the callback in interpreted languages, if the default layout procedure is satisfactory for parts of a block.
Setting the -layoutdepth and/or -layoutwidths options for a block forces the layout procedure to be called with agruments corresponding to modified tree structure.
If -layoutdepth is set, the depth of the tree is modified to be the given number. If the true depth of the tree is too small, tree is extended from the root side, if it too deep, the subtrees on the maximal allowed depth level are mocked as lines with repeat count.
If -layoutwidths is set, this can restrict the number of branches going out of any node of the modified tree. The value of this option should be a list, elements of this list are either numbers, or lists of the form {min max}. (A single number is equivalent to a pair {number number}). N-th element of the list controls the number of branches going out of nodes on the distance N from the root. If there are too few branches, it adds branches that contain simulated groups of leaves with repeat count 0. If there are too many branches, it groups several last brunches into one with appropriate repeat count. (Current implementation is buggy in interaction of -layoutwidths and -layoutdepth if the depth of the node is less than -layoutdepth.)
Block subcommands
- configure blockName ?option value ... ?
-
Standard procedure for creating and configuring block type. Currently supported configuration options are
- cget
-
Standard configuration get procedure.
- at index
-
Returns information in the block that starts at the given index or "nothing" if there is no such block. Returned information is a list consisting of block start index, block length in index space, block name, block instance data, structure of the block. The latter is a list (possibly of lists) with leaves being lengths of block leaves.
- of index
-
Returns information in the innermost block that contains the given index or empty list if there is no such block. See
atsubcommand for description of return value. - delete blockName ?blockName ...?
-
Deletes the information on block types. Error is returned if the are blocks of the given types in the widget.
- insert blockName index1 ?index2?
-
Inserts block of the given type in the widget. The block contains one node, and all the leaves are immediate children of this node. If index2 is not specified, creates a block with one empty leaf, otherwise moves the contents of the widget between index1 and index2 into the tree.
In the latter case index1 and index2 should be outside of any block, or properly inside the same block. The newlines (or, correspondingly, interleaf separators of enclosing block) are converted into interleaf separators of newly created block. This is prohibited for empty blocks. An index2 before index1 is an error.
More precisely: both indices outside of any block, or both inside the same block (the innermost block around each is the same) are accepted; ends in different blocks are an error. A range inside a block may cross leaves of that block, and nodes of its tree too. The leaves moved (whole, or the part of the first one after index1 and the part of the last one before index2) become immediate children of the single node of the new block, in their order: whatever structure they had in the enclosing block (the nodes above them) is flattened, and the separators between them, whatever their depth, become separators of depth 0 of the new block. Blocks nested in the range move into the new block unchanged. In the enclosing block, the parts of the first and the last leaf left outside the range (with the new block between them) are one leaf, which stays where the first leaf was; nodes left without leaves disappear, but the other nodes are not joined. With
{ab|cd|ef|gh}on line 1, whose root has two nodes, one with the leavesabandcd, the other withefandgh,block insert G 1.2 1.9(overb|cd|ef) gives{a{b|cd|ef}|gh}: the leavesb,cdandefof the new block are children of its single node, and the root of the outer block still has two nodes, one with the leafa{b|cd|ef}, the other withgh. (What happens to the values of the nodes involved is in "Node values and editing".)Recorded for undo; see "Undo and redo of block and tag changes".
- names
-
Returns list of names of currently defined block types.
- split index ?level?
-
If index is outside of blocks, inserts newline.
Otherwise, if level is not specified, or is 0, is equivalent to insertion of newline, i.e., splits the leaf into two with the same parent.
If level is positive, splits the leaf in two and changes the structure of the tree.
If level is less than the distance from the leaf to the root, splits the levelth parent (and all the parents of less order) in two. The beginning of the split leaf goes to one node, the rest (together with the leafs in the same node after the splitted one) goes to another. Example of split 1 follows (the leaf marked X is split into two marked x):
___ ___ / __ / _ / / / / .-------X .-------x \ \__ \ \____x \_____ \ \_ \____If level is too big to proceed with the above procedure, the tree is extended to the left first. The added nodes have one child each.
Returns the number of levels added above the root (-1 outside of blocks). Recorded for undo; see "Undo and redo of block and tag changes". An index on the last (dummy) line is taken as the end of the line before it, as for
insert. - trim index
-
If the block at index has only one edge coming from the root, and this edge does not end in a leaf, deletes the root. The resulting tree will be 1 level more shallow. Returns error if out of block or the above conditions are not met. Recorded for undo; see "Undo and redo of block and tag changes".
- data index ?data?
-
Returns or sets instance data information for the block at
index. - nodedata index level ?value?
-
Returns or sets the value kept with a node of the tree of the block containing index: the leaf index names if level is 0, its parent if it is 1, and so on; the root if level is -1, a child of the root on the way to the leaf if it is -2, and so on. Returns the value (an empty result,
undefin Perl, if the node has none); with value, sets it and returns nothing,undefremoving the value. See Values, which tells which leaf a position names. - addline index
-
"Steals" the displayed structure of the line starting at index. Returns the id of the resulting element. This id can be used in the return value of the layout callback to specify additional elements used in drawing of the block. Beware that the behaviour is undefined if the line contains something more complicated than tagged characters.
- deletelines
-
Deletes all the "stolen" lines.
- list from to
Mark and tag subcommands
The mark and tag subcommands are those of the Tk text widget, with one more each:
- mark data markName ?value?
-
Returns or sets the value kept with the mark markName. Returns the value (an empty result,
undefin Perl, if the mark has none); with value, sets it and returns nothing,undefremoving the value. A mark that does not exist is an error (there is no mark named "m"). See Values. - tag data tagName index ?value?
-
Returns or sets the value kept with the run of the tag tagName that contains the character at index. Returns the value (an empty result,
undefin Perl, if the run has none); with value, sets it and returns nothing,undefremoving the value. A character without the tag is an error (no run of tag "b" at 1.6), as is a tag that does not exist. See Values.
The dump subcommand
.t dump ?-all -text -mark -tag -window -image -block -values? ?-command script? index ?index2?
dump is Tk's, and looks into blocks: the text, marks, tag toggles, windows and images inside a block are reported with their (external) indices; with -block (part of -all) a block entry (the block type, at the block's head) and a blockend entry (after its tail) surround them.
With -values (not part of -all; alone it means -all -values), every entry gets a fourth field: for a mark entry, the value of the mark (mark data), for a tagon entry, the value of the run the toggle starts (tag data), a copy in either case; for every other entry, and for marks and runs without a value, undef (an empty string in Tcl). So the result stays a list of entries of one length, four elements each instead of three. A -command callback gets the fourth field as a fourth argument (without -values it gets three, as before). The values of block nodes (block nodedata) and the instance data of blocks (block data) are not in the dump: a block carries a tree of them, which block list shows (the header of a Tk::Text::Block); the block, blockend, tagoff, text, window and image entries have undef. Without -values the dump is as before.
.t dump -mark -values 1.0 end
;# mark m 1.2 mv mark insert 3.0 {} ...
Undo and redo of block and tag changes
With -undo on, block insert, block split, block trim, tag add and tag remove are recorded for edit undo, as insertions and deletions are (Tk's text widget records neither tags nor, of course, blocks). The undo reverses each of them, the redo does it again:
block split: the undo deletes the separator the split put in; the deletion joins the two leaves, and the nodes the split cut, up to their common ancestor (see "Deletion of text in blocks"); levels the split added above the root are taken away again (asblock trimwould). Outside blocks the split put in a newline, which the undo deletes.block insert: the undo dissolves the new block by deleting its head (see "Destruction of blocks"): its contents come back where they were, with their tags, marks and nested blocks. The values of the leaves the block insert moved whole into the block go back to those leaves, the joins and merges it made are undone (see "Node values and editing"), and its instance data (block data) and the values of its own nodes are kept in the undo step for the redo. If the range of the block insert crossed nodes of an enclosing block (seeblock insertin "Block subcommands"), the undo also gives every separator of the range, and the one after it, the level it had, so that the nodes of the enclosing block are those before the block insert, and the values of the nodes block insert emptied, or left on the end side, come back to them. No text moves for that, and the undo is one step, as always.block trim: the undo adds the root again, with the value it had.tag addandtag removeover a range: the undo gives the tag in that range exactly the ranges it had there before, the run values included (a run that tag add extended keeps its value on the part that remains, the values of the runs it merged come back). Changes of the tagsel(the selection) are not recorded, nor are those that change nothing (adding a tag where it is all over the range, removing it where it is nowhere).
A redo checks again what the command checks: if the change cannot be made again (the block type of a block insert was deleted, or made -empty while the range is not empty; the block a block trim worked on is gone or cannot be trimmed), the redo does nothing, and the values its undo step keeps are freed when the step is discarded.
What these changes drop goes into their undo step as for deletions (see "Undo and redo"): the losers of joins and merges, the nodes block insert empties, a root block trim drops, the runs tag remove removes; the undo gives them back, the redo takes them again.
Each of these changes is a kind of edit of its own for -autoseparators, as insertions and deletions are: following Tk's rule, a separator goes into the undo history when a change is of another kind than the last one, so that a run of changes of the same kind (several tag add in a row, as typing is a run of insertions) is one undo step, and a change of another kind starts a new one (tag add and tag remove are two kinds, as insertion and deletion are). To make one step of several changes of different kinds, switch -autoseparators off and put in edit separator yourself. A program that uses tags for display only (highlighting found text, say) can switch -undo off around those calls: tags do not move text, so the history stays valid. These changes also count for edit modified, as insertions and deletions do, with -undo off too (but for those of sel and those that change nothing); a program that highlights can keep the flag with edit modified around the calls.
Not recorded (so not undone, and what they drop is freed when they return): tag delete, tag configure, mark set, mark unset, block delete, block configure, and the setting of values (block data, block nodedata, mark data, tag data).
Values
A Perl scalar can be kept with every node of the tree of a block (the leaves included), with every mark and with every run of a tag:
.t block nodedata index level ?value?
.t mark data markName ?value?
.t tag data tagName index ?value?
In Perl these are $t->blockNodedata($index, $level, ?$value?), $t->markData($name, ?$value?) and $t->tagData($tag, $index, ?$value?). Without a value they return the value, or undef if there is none; with a value they set it, and setting undef removes the value. The values are data only: the display does not depend on them (setting a node value does not redisplay the block, and the layout callback does not receive node values), and dump reports those of marks and runs only with -values (see "The dump subcommand"). They stay with their node, mark or run through edits, come back with undo, and are freed at the moments listed in "When values are freed".
Which node, which run
The position given to block nodedata names a leaf of the innermost block it is inside:
a character of a leaf (or a block nested in it, or an empty block, which occupies one index unit of the leaf) names that leaf;
an interleaf separator, and the tail of the block, name the leaf before them;
the head of a block belongs to the enclosing structure, as for insertion (see "Insertion in blocks"): it names a leaf of the enclosing block, and is an error outside of blocks.
An empty block has no leaves, hence no node values. A position outside of every block is an error (bad index "2.0": not inside a block).
The level picks the leaf (0) or one of its ancestors: 1 is the parent of the leaf, 2 the parent of that node, and so on. A negative level counts down from the root: -1 is the root, -2 the child of the root on the way to the leaf, and so on. A node is reached from every position in it, the root from every position in the block. A level beyond the root, or a negative level below the leaf, is an error. With a fraction {num|den} on line 2 (head 2.0, num 2.1-2.3, the separator 2.4, den 2.5-2.7, the tail 2.8):
.t block nodedata 2.2 0 N ;# the leaf num
.t block nodedata 2.4 0 ;# N: the separator names num
.t block nodedata 2.8 0 ;# the tail names den: nothing
.t block nodedata 2.6 -1 R ;# the root (level 1 here)
.t block nodedata 2.2 -2 ;# N: down from the root, the leaf
.t block nodedata 2.0 0 ;# bad index "2.0": not inside a block
.t block nodedata 2.2 2 ;# bad level "2": the block containing
;# 2.2 has 1 level above its leaves
A run of a tag is a maximal stretch of characters carrying it. It continues over line ends, interleaf separators, and heads and tails of blocks: a run that covers a block contains it. tag data names the run of the character at the position; every character of the run names the same run.
Copies
The widget keeps a copy of the scalar it is given, as block data does, and reading returns a copy; the elements of block list hold copies too. A reference is copied as a reference: an object given as a value stays alive as long as the widget keeps the value. So freeing a value below means that the widget drops its copy; an object is destroyed (and its DESTROY method runs) when its last reference goes.
Node values and editing
The values live in the tree, so they move with the text.
Insertion inside a leaf does not change values. A newline inserted in a leaf (or
block splitat level 0) splits it: the first part keeps the value, the new leaf starts without one.block splitat a higher level does the same on each level: the node before the cut keeps its value, the new node after it starts without one. Nodes it adds above the root start without values, except that the value of the root moves to the new root, so that level -1 keeps naming it.A leaf whose text becomes empty keeps its value.
A deletion deletes a leaf, value and all, if the range holds all of its text together with the separator before it (the separator or tail after it need not be in the range), and a node if it holds all of its leaves in this way. Otherwise the leaf where the range starts and the leaf where it ends are joined, and if they have different parents, their ancestors are joined on each level up to the common ancestor (see "Deletion of text in blocks"). On each level the joined node keeps the value of the node on the start side if it has one, else it takes the value of the node on the end side; the other value is freed. The starting leaf always survives a join, even when all of its text is in the range: in
{num|mid|den}, deletingmid|keeps the value ofmidon the joined leaf (the inverse of insertingmidand a newline at the start ofden), while deleting|middeletes the leafmidwith its value. The last of a block's nodes directly above the leaves also holds the block's tail, so a deletion never removes it whole (nor its ancestors below the root, which hold the tail too): when all its leaves are deleted, it is joined to the node before it, and its value follows the rule for joined nodes: it moves to that node if that node has no value, and is dropped otherwise.A deletion that deletes a block deletes all of its node values; one that dissolves it (it holds its head or tail, see "Destruction of blocks") frees all of its node values too, the values of the leaves whose contents join the enclosing structure included. The values in blocks nested in what is left stay with those blocks.
block trimremoves the root: the new root (its only child) keeps the value of the old root if it had one, else its own; the other value is freed.block insertinside a block moves leaves into the new block. A leaf moved whole keeps its value as a leaf of the new block (a first leaf with nothing before index1, and a last leaf with nothing after index2 but its separator, move whole). Where index1 or index2 cuts a leaf, the part left in the enclosing block keeps the value and the moved part starts without one; the two parts left on both sides of the new block are one leaf, which keeps the value of the first if it has one, else takes the value of the second, the other being freed. Nodes of the enclosing block left without leaves disappear, with their values.
The instance data of a block (block data) is freed with the block, under the same rule as the values ("When values are freed").
Run values and editing
When runs become one (
tag addover the gap between them, a deletion of the gap, a deletion of the head of a block between them), the run keeps the value of the leftmost of them that has one; the other values are freed. A run whose text is all deleted takes no part.A run shortened at either end (by
tag removeor a deletion) keeps its value. A run cut in two (bytag removein its middle, or by text inserted with a list of tags that lacks the tag) leaves the value on the left part; the right part starts without one. A run extended bytag addkeeps its value.Text inserted inside a run without a list of tags, a newline included, is in the run (the inserted text takes the tags present on both sides, as in Tk); text inserted at the start or the end of a run is not.
block splitandblock insertinside a run do not cut it;block insertat the start of a run puts the start of the run, value and all, inside the new block.A run whose text is all deleted, or which
tag removecovers entirely, is gone with its value.tag deletefrees the values of all the runs of the tag.
Mark values
The value stays with the mark when it moves: mark set on an existing mark, mark gravity, edits (a deletion moves the marks of its range to its start), undo putting the mark back. Edits never remove a mark, so they never free its value. A mark set anew after mark unset, also one re-created by an undo, starts without a value. The marks insert and current can have values too (mark unset ignores them, as before). block list shows a mark with a value as [name, value] (see "What else is in the widget?").
When values are freed
A node value is freed when it is replaced (or set to undef), when its node is deleted, when its block is deleted or dissolved, when it loses a join (deletion, block insert), when block trim drops it, when block insert empties its node, and when the widget is destroyed. A mark value is freed when it is replaced (or set to undef), when mark unset removes the mark, and when the widget is destroyed. A run value is freed when it is replaced (or set to undef), when all the text of the run is deleted, when tag remove covers the whole run, when tag delete removes the tag, when it loses a merge, and when the widget is destroyed. With -undo on, the edits that can be undone (insertions, deletions, block insert, block split, block trim, tag add, tag remove) do not free what they drop: it is kept by their undo step ("Undo and redo"), and freed when the step is discarded. Nothing else frees a value: in particular, setting other values, tag configuration, moves of marks and unrelated edits do not.
Freeing a value can run Perl code (a DESTROY method), so a value is never freed in the middle of a change: the values that a widget command drops are freed, in order, when that command returns (a Perl method or a binding that makes several widget calls frees after each of them). A DESTROY method may thus read the widget, and sees it as it is after the change: when a deletion of line 2 frees a value, the DESTROY method sees the index end one line up already. It may change the widget too (see below); to know where the value was attached before it was detached, use -valuecommand (see "Telling the program: -valuecommand"). When the widget is destroyed, its remaining values (those in the undo history included) are freed after it is gone, and a DESTROY method that calls it gets the usual error for a destroyed widget.
Changes made from a DESTROY method. While the values a command dropped are being freed, a DESTROY method may change the widget. Such a change is an undo step of its own: it does not merge into the step of the command that dropped the value, nor into the next change. The values it drops join the values being freed and are freed in the same pass, after those already waiting (so still before the Perl method that made the first command returns). The values are freed in rounds: those the command dropped in round 1, those dropped by changes made from their DESTROY methods in round 2, and so on. A chain of such changes (a value freed by a change made from a DESTROY method, whose own DESTROY method changes the widget, and so on) has a limit, 10 to begin with: a change in the round of the limit is refused with the error cannot modify .t while its values are being freed, 10 changes deep, unless the object making it asks for more rounds (see below). So a chain of 9 changes, in rounds 1 to 9, is always made. (2.04 refused every change while values were being freed, a stopgap until the program could learn where a value was before it was detached.)
More rounds: DESTROYmult. When a change from a DESTROY method is about to be made in the round of the limit, the widget asks the object whose DESTROY method is attempting it, calling, in scalar context,
$more = $object->DESTROYmult($n, $limit);
$n is 1 for the first such request of this freeing pass, 2 for the next, and so on; $limit is the current limit. If $more is a positive integer, the limit becomes $limit + $more and the change is made; the next time the chain reaches the new limit, the widget calls DESTROYmult($n + 1, $limit + $more). A method that always answers 5 is thus called with (1, 10), (2, 15), (3, 20) and so on. Other changes in a round below the raised limit are made without asking. The change is refused as above, with the error naming the current limit (cannot modify .t while its values are being freed, 15 changes deep once it was raised by 5), if
the answer is 0,
undef, negative, not a number, or not an integer;there is no object to ask (see below), or it is not a blessed object;
the object cannot
DESTROYmult(!$object->can('DESTROYmult'); an inherited method, or one thatcanreports, will do);DESTROYmult(orcan) dies: its error is reported as a background error (Tk::Error), as those of the-valuecommandcallback are, and the answer counts as 0.
A change that DESTROYmult itself attempts is refused, without asking again. The limit and the count of requests belong to one freeing pass, that is to one outermost widget command (a command made by Perl code that the freeing runs is part of the pass): the next command starts again with the limit 10 and request 1. The call leaves $@ as it was; DESTROYmult should not keep a reference to its object (it is being destroyed).
Which object is asked. The object whose DESTROY method is the innermost one running when the change is attempted, that is the DESTROY method that makes the change, itself or through the subroutines it calls. When a value is an object whose own DESTROY makes the change, that is the value. When the change is made by the DESTROY method of an object held inside the value being freed (in an unblessed array or hash that is the value, or in a field of an object that is the value), that inner object is asked, not the value: its method is the one that knows what its change needs, and an unblessed value could not be asked at all. Perl calls an object's DESTROY method before it frees what the object holds, so an object held by the value is usually destroyed after the value's DESTROY has returned; if the value's DESTROY frees it itself (delete $self->{child}), both are running, and the inner one is asked. The object is found as caller finds the arguments of a call (in @DB::args): the first argument of the innermost DESTROY method written in Perl, also when the method has shifted it. A DESTROY method that has replaced its @_ leaves nothing to ask.
Commands refused while the -valuecommand runs. While the callback of -valuecommand runs, the widget refuses the commands that would modify it, with the error cannot modify .t while its -valuecommand runs: the command that called it has not made its change yet. Reading commands, and those that only change the view, work as usual. The rule: a command that would change something, or create a tag or a block type, is refused; a query of an existing one is not. The commands refused are:
insert,delete, andconfigurewith options to set;tag add,tag remove,tag delete,tag raise,tag lower,tag datawhen it sets something, andtag configureandtag bindwhen they set something or name a tag that does not exist (a query would create it);mark set,mark unset, andmark gravityandmark datawhen they set something;block insert,block split,block trim,block delete,block configurewhen it sets something or names a block type that does not exist (a query would create it),block addline,block deletelines, andblock dataandblock nodedatawhen they set something;image create,window create, andimage configureandwindow configurewith options to set;edit undo,edit redo,edit reset,edit separator, andedit modifiedwith a value.
Everything else works: get, index, compare, dump, search, bbox, dlineinfo, the queries of tag, mark, block, image, window, edit and configure, cget, see, xview, yview, scan and debug.
Undo and redo
With -undo on, a deletion does not free the values it drops (of deleted nodes and runs, of the blocks it deletes or dissolves, their instance data included, the losers of joins and merges): they go into its undo step, each with an address that is valid again once the deletion is undone (where the node's first leaf or the run starts, the node's level, the tag's name; where a block's head is, for its instance data). edit undo re-creates the text (the blocks with their depth, and the runs as separate runs again), then gives every value back to the node, run or block at its address, and moves back the values a join moved. edit redo takes them into the step again. The undo of an insertion and its redo do the same. A value the undo finds on the node or run it gives a value back to (one set after the edit, or of a run made since and merged with the restored one) is not freed either: it waits in the step, and the redo gives it back. If the undo finds no node at an address, the value is freed.
The values in an undo step are freed when the step is discarded: by edit reset, when the history grows beyond -maxundo steps, when a new edit after an undo drops the steps that could have been redone, and when the widget is destroyed.
Marks need no records: the undo moves an existing mark back with its value. block insert, block split, block trim, tag add and tag remove keep what they drop in their undo steps in the same way (see "Undo and redo of block and tag changes"). tag delete, mark unset and the setting of values are not undoable, so the values they drop are freed when they return.
The redo of an insertion re-inserts it exactly: when the insertion is undone, the inserted range is recorded in block-list form, as a deletion records what it deletes (at that moment the range is as the insertion left it, the later recorded changes having been undone), and the redo inserts that list (Tk 8.4 re-inserts the plain string). So the text comes back with the tags it was inserted with (not those of the text around it), with the separators it made in a block, and with the marks that were in it when it was undone; then the values come back to its runs and nodes. If the recorded indices have become stale (changes made with -undo off) and the range cuts blocks, the redo inserts the plain string.
The undo keeps its own records of the values; its own block list of the deleted text leaves them out (the instance data of blocks included, and those of marks, which the undo never needs: it moves an existing mark back with its value), so that it holds no extra reference to them. A program re-creating text from the elements of block list sets no values unless it does so itself.
Telling the program: -valuecommand
With the option -valuecommand, the widget tells the program, before a change is made, which values the change will detach and where they are, while the widget is not changed yet; and afterwards which values an undo or a redo gave back and which a discarded undo step frees. For most commands this is before the command changes anything; the commands that make several changes in a row tell before each of them (see the note "Postponed" below). The callback is called as
$cb->($widget, $event, $kind, $where, $value, $cause)
with $value the value (as block nodedata and the others return it), and:
$kindand$where-
The owner of the value and its place, an array reference:
node [index, level] blockNodedata(@$where) returns the value run [tag, start, end] tagData(tag, start) returns it mark [name, index] markData(name) returns it block [index] the head of the block (block data)A node (the leaves included) is named by the position where its first leaf starts and its level counted from the leaves (0 for a leaf), as in "Undo and redo". A block is named by its head;
block dataat the head returns the value for an empty block, and for another block at a position inside it that is not inside a block nested in it (its tail, for one). $event-
drop-
before the change: the value is detached and freed when the command ends;
stash-
before the change: the value goes into the undo step of the change (
-undoon), or, for a value that an undo or a redo finds where it gives another back, into the step it applies; move-
before the change: a merge (of two leaves, nodes or runs that become one) gives the value to another owner. The last element of
$whereis an array reference naming the new owner, in the same form, as it is before the change:[index, level]or[tag, start, end]; restore-
an undo or a redo gave the value back: called once it is back (before the rest of the command), with its place then;
discard-
an undo step that held the value was thrown away (
edit reset,-maxundo, a new change dropping the steps that could be redone), or an undo or a redo found no place for it: called at the end of the command, just before the value is freed, with the place the step recorded, which may not exist any more (a run's is[tag, start], a position on a line that is gone is given as recorded); late-
a value was detached that the widget did not foresee: called at the end of the command, after the change, with the place the value had before it if the widget knows it, else
$whereisundef. This should not happen. Withdebugon, the command fails then (as when a detach was foreseen but did not happen as told), so that tests catch it.
$cause-
The command:
delete,insert,tag add,tag remove,tag delete,block insert,block trim,block split,undo,redo,reset(edit reset),separator(edit separator),configure(-maxundo);setfor the commands that set a value (block nodedata,tag data,mark data,block data, undef included) andunsetformark unset.
The calls before a change are made once the command has checked its arguments, before it changes anything, for a command that makes one change.
Postponed: telling everything before a command that makes several changes starts; today these commands tell before each of their changes. The approved design said that the program is told before the command changes anything. For the commands that make several changes in a row, the widget tells before each change instead, the widget being as the previous change left it (so a $where names the place at that moment, not before the command). These commands are:
edit undoandedit redo, which apply the recorded changes of a step one by one: each is told just before it is applied;insertwith lists of tags (insert index chars tagList ?chars tagList ...?): each piece is inserted, then the tags it got from the text around it are taken off and those of its list put on, one tag after the other, and each of these is told just before it is made;tag addandtag removewith several ranges: each range is told before it is tagged or untagged;a deletion through the end of the text, which first takes the tags off the final newline (told then), and then deletes (told then).
Also, a value that an undo or a redo displaces (one it finds where it gives another back, "Undo and redo") is told (stash) just before it moves, and restore comes as soon as a value is back, not at the end of the command. The owner postponed the question whether to tell everything at the start of such commands (which would need the look-ahead of all their changes from the widget as it is before the first); see BUGS 27.
While the callback runs, the widget can be read but not changed: the commands listed in "When values are freed" are refused, with the error cannot modify .t while its -valuecommand runs. (A DESTROY method, which runs once the change is made, may change the widget.) The callback cannot refuse the change. An error in the callback is reported as a background error (Tk::Error) and the command goes on (see "When Perl code called by the widget dies"). The callback should not destroy the widget.
Nothing is told when the widget is destroyed (its values are freed then, see "When values are freed"), nor about values that have no Perl part (in a widget built with representation B, a container that holds only other slots). Without the option nothing of this runs: no look-ahead, no table.
The ready-made callback. With
$t->configure(-valuecommand => 'DETACH');
the widget calls its method DETACH (a callback given as a string is a method of the widget), which passes the notification on to values that are objects with a DETACH method of their own:
$value->DETACH($widget, $event, $kind, $where, $cause)
at the same moments as above; other values (plain scalars, objects without such a method) are skipped. A subclass of Tk::eText may define its own DETACH (and call $w->SUPER::DETACH(...) to pass the values on). As with any -valuecommand, the commands then do the look-ahead; an error in a DETACH method is a background error.
When Perl code called by the widget dies
The widget runs Perl code at three places that may die: the DESTROY methods of the values it frees, the -valuecommand callback (or, with -valuecommand => 'DETACH', the DETACH methods of the values) and DESTROYmult. None of these errors stops the widget command that ran the code, and none of them makes a value freed twice or kept for ever:
- A
DESTROYmethod dies -
Perl does not let an error leave a
DESTROYmethod: it makes it the warning(in cleanup)message, with a tab before it (categorymisc), given only if warnings are on where the error is raised (use warningsthere, orperl -w); otherwise the error is lost. The value is freed all the same, the other values waiting are freed after it, and the widget command that dropped them returns normally, with its usual result. A change the method made before it died stays made, as an undo step of its own. - A change refused inside a
DESTROYmethod -
The refusal (
cannot modify .t while its values are being freed, 10 changes deep, see "When values are freed") is an error raised inside theDESTROYmethod, so it is the case above: unless it is caught, it becomes an "(in cleanup)" warning, and the values and the command go on. It is raised by the widget method, which Perl/Tk compiles in Tk.pm withoutuse warnings: if it leavesDESTROYas it is, the warning is given only underperl -w($^W), and is lost otherwise. To know, catch it withevalinsideDESTROY:sub DESTROY { my $self = shift; eval { $self->{widget}->insert('end', "gone\n"); 1 } or warn "not made: $@"; } - The
-valuecommandcallback dies, or aDETACHmethod -
The error is reported as a background error (
Tk::Error, called when Tk is next idle), and the command goes on as if the callback had returned: the change is made, and the values are freed, kept or given back as usual, each once; nothing the callback was given is kept. Each call that dies is one background error. (Perl/Tk itself keeps about half a kilobyte for each background error, whatever reported it, a binding included; that memory is not the widget's.) DESTROYmultdies-
A background error, and the answer counts as 0: the change is refused ("When values are freed"), and that refusal, raised inside a
DESTROYmethod, is the case above.
Additional text widget options
-valuecommand-
A callback told before a command detaches values, see "Telling the program: -valuecommand";
'DETACH'passes the notification on to values that are objects with aDETACHmethod. Empty (or undef) by default. -getFlags-
The value is an integer, binary bits of this integer denote current text representation options. If no bits are set, the operations that consider text contents as a string behave like the standard Tk text widget.
If bit
1is set, the string representation of a text range always gives a string of the same length as the length of the interval in the index space. If some text annotation results in an empty string in the standard representation, it is represented as an appropriate number of*s if this bit is set. Currently this concerns embedded windows only, which are represented as*.All undocumented bits are reserved and should be 0.
Minitutorial
Example of a simple "pedestal" block
Suppose you are satisfied with the standard layout procedure, but want to extend the resulting group of lines 10 points to the right (so when part of block is selected, selection extends 10 points to the right of the rightmost element in leaves), and want to add a blue 3D background of width 5 with "height" 2 around the resulting guy, and draw the block on gray 3D background of width 2.
Note that it is not enough to use a tag even for gray background, since the border of the tag is inside the rectangle that contains the letter, and to get a correct pedestal look we want the border to surround the letter, not to be drawn outside of them.
In what follows we use TCL as the language for callback. Of course, the resulting code will be much simpler in some other languages.
First, we create the 2 new additional elements to display:
.t tag configure backgr1 -background blue -border 2 -relief raised
.t tag configure backgr2 -background gray90 -border 2 -relief raised
.t insert 1.0 \n backgr1
set backgrId1 [.t block addline 1.0]
.t delete 1.0 1.0+1c
.t insert 1.0 \n backgr2
set backgrId2 [.t block addline 1.0]
.t delete 1.0 1.0+1c
(or we could use existing ones, if possible). The third row creates a row in the text widget that is empty, and has tag "backgr1". This row will show the background only, and we will use it to show the raised background behind the block. The fourth row memorizes the id of this additional line, and the fifth one returns the text in the widget to its initial state. The line is not shown anymore, but the way to show it is preserved in a safe place. The second element is created in the same way.
Next, since we are satisfied with the way the leaves of the tree are places on the screen (i.e., one under another), we do not want to be concerned with internal structure of the block tree, so we ask the widget to lie about internal structure of the tree:
.t block config myBlock -layoutdepth 1 \
-layoutwidths 1 -layoutcmd myLayoutCmd
Now the data given to myLayoutCmd will be always the same, as if the block consisted of one leaf only that is the direct child of the root. So the arguments the myLayoutCmd receives are the following ones:
proc myLayoutCmd {block x row} {
global backgrId1 backgrId2
set c [lindex $row 0]
set w [lindex $row 2]
set tw [lindex $row 3]
set h [lindex $row 4]
set b [lindex $row 5]
Now $c, $w, $tw, $h, $b contain the count, width, total width, height and baseline of the contents of the block. Next we extend the total width of the row.
set tw [expr $tw+10]
set tw2 [expr $tw+4]
set tw1 [expr $tw+10]
We will not replace the width of the row, so mouse events could be directed to outside of the block if clicked in the extended area. (In fact they won't, since we will extend the size of the ambient block.) Next we calculated widths of additonal rows,
set h2 [expr $h+4]
set h1 [expr $h+10]
set b2 [expr $b+2]
set b1 [expr $b+5]
and their height and baselines. All is prepared now to layout the rows:
set addrow1 [list $backgrId1 0 0 $tw1 $tw1 $h1 $b1]
set addrow2 [list $backgrId2 3 3 $tw2 $tw2 $h2 $b2]
Note that the same list $addrow1 is good for specifying the size of the total block, since the first element of the list (that is $backgrId) is ignored in the information for the whole block. Now we need to move the real contents of the block 5 points to the right and down with respect to the rectangle occupied by the block, and return the calculated information:
set row [list $c 5 5 $w $tw $h $b]
return [list $addrow1 $row $addrow1 $addrow2]
}
Note that it is vital to put addrow2 after addrow1, since it should be drawn after the addrow1 for it to appear to be on top of addrow1.
That's all! Now you can create a binding for insertion of empty block into the widget (this binding supposes that bindtags are reverted):
bind .text <Control-Meta-m> {
%W block insert myBlock insert
%W mark set index index-1c
break
}
This binding moves the insertion point inside the block, so you are ready to fill block with whatever information you need.
Sample code in the distribution of extended text widget provides other examples of blocks: superSub, Fraction, and so on.
Example of a simple "tabulation" block
Here we describe how to code blocks that contain no editable information, but provide geometry management. Consider an example of tabulation: if we implement tabulation as a block, the size of this block should change depending on the position of the start, but the only editing operation should be the deletion of the block as a whole.
While it is possible to implement this kind of block using the same types of blocks as in the previous section, we will need a lot of code change in the bindings if we use this approach: a usual block takes at least 2 positions in the index space, so it is possible to make an insertion inside this block. Thus we either need correction of keybindings that move the insertion point, or should correct the the insertion code to check whether the insertion happens inside a block of this type. If we do not do this, we need additional decision how to handle blocks of this type that have not-empty contents.
The solution is to use "empty" blocks that take only 1 position in the index space, so it is impossible to insert text inside them. We make block type empty by using configuration option -empty:
.t block configure Tab -empty on -layoutcmd {layoutTab 5 35}
Note the spaces in the name of layoutcmd: No quoting is performed during the call, so 5 and 35 become first two arguments of layoutTab procedure. This procedure can be as simple as follows:
proc layoutTab {min mult block x} {
global backgrId2
set w [expr $min + $mult - ($x + $min - 1) % $mult - 1]
set totblock [list $backgrId2 0 0 $w $w 5 3]
return [list $totblock $totblock]
}
The only "working" row is the set w one. It calculates the width of the block using the following rule:
the width is at least $min, and the right end is on the position that is proportional to $mult counting from the left of the line.
The last row returns a list of length 2. The first element is the description of the block as a whole, the next one is necesssarily the description of an additional element (since there are no "regular" leaves in the tree). This additional element is the same size as the block itself, and is used only to provide some visual feedback. We use id $backgrId2 created elsewhere (say, by the code in the previous example), and ask for the rectangle to be 3 points above the baseline, and 2 points below.
AUTHOR
Ilya Zakharevich <ilya@math.ohio-state.edu>