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 is S.

Marks

The contents is the name of the mark, the classes are Tk::Text::MarkLeft with id L, and Tk::Text::MarkRight with id R. 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 marks insert and current are not set from a list, nor are their values.

Tags

The contents is the name of the tag, the classes are Tk::Text::TagOn with id T, and Tk::Text::TagOff with id t. The start of a run of a tag that has a value (see Values) is a Tk::Text::TagOn holding 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, -pady and -stretch; the class is Tk::Text::EmbWin with id W. 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, -padx and -pady; the class is Tk::Text::EmbImage with id I. 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 undef if 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, with undef for a node without a value. For a fraction with value R on the root and N on 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 an object of class Tk::Text::BlockSeparator, with id |, the contents being the "depth" of the separator: the level of the lowest node that holds the leaves on both sides of it, counted up from the nodes directly above the leaves. The minimal possible depth is 0, for separators between leaves of the same parent; in a tree whose leaves are equally deep, 1 is a separator between leaves whose parents are siblings, and so on. The depth in the first element is that of the root on the same scale (0 for a fraction {num|den}).

In a tree whose leaves are at different depths (a "ragged" tree, see "Ragged trees") the depths are those of a uniform tree that the widget keeps: every leaf is as deep as the deepest one, a shallower leaf hanging from its parent through padding nodes, which are not nodes of the tree (no command names them). The header's depth and the depths of the separators count these too. The separator before a leaf with padding is a pair instead of a number: a reference to an array (blessed into the same class, Perl only) of the depth and the number of padding nodes directly above the leaf (its defect). A first leaf with padding, which has no separator before it, gets the pair [undef, defect] in front of it. Separators before leaves without padding stay numbers, so the list of a tree whose leaves are equally deep is as before. With {x|2|3} on line 2, the 2|3 made the leaves of a node S (R( x | S( 2 | 3 ) )):

[['F', 1], [undef, 1], 'x', 1, '2', 0, '3']   # R( x | S( 2 | 3 ) )
[['F', 1], '2', 0, '3', [1, 1], 'x']          # R( S( 2 | 3 ) | x )

(the separators shown as their contents). A program reads both forms with

my ($d, $defect) = UNIVERSAL::isa($sep, 'ARRAY') ? @$sep : ($$sep, 0);

At a separator of depth s, both leaves next to it have defects of at most s. A block that is a single leaf (see block flatten) has the depth -1, and no pair: [['F', -1], 'numden'].

The object class in Perl is Tk::Text::Block, the class id is B.

Empty

An empty block is dumped in the same way with the object class being Tk::Text::Empty, the class id being E. 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.

The leaves of the tree may be at different distances from the root (a "ragged" tree, since 2.06, see "Ragged trees").

Ragged trees

Until 2.05 every leaf of a block was at the same distance from the root. Since 2.06 the leaves may be at different depths: block sprout gives a part of a leaf (or a whole leaf) a node of its own, block flatten makes a node one leaf again, and the editing commands keep the depths. For example R( x | S( 2 | 3 ) ), a root R whose children are a leaf x and a node S with the leaves 2 and 3 (this notation is used below: | separates siblings).

  • Levels. The commands that name nodes count the real ancestors of a leaf: block nodedata index level (and block flatten) take the leaf the index names as level 0, its parent as 1, and so on, and a negative level counts down from the root (-1 the root, -2 its child on the way to the leaf). So the number of levels depends on the leaf: in the example, x has one level above it, 2 has two. block at and block of give the structure of the real tree (a list of lists, with a number for each leaf: [1, [1, 1]] above), and so do the arguments of the layout callback. The places of node values (Values, "Telling the program: -valuecommand") are given the same way: where the node's first leaf starts, and the node's level counted from that leaf.

  • Padding. Internally the widget keeps the tree uniform: a leaf shallower than the deepest one hangs from its parent through padding nodes, which are not nodes of the tree: no command names them and they hold no values. The user sees them in two places only: in block list, whose depths are those of the uniform tree (the separator before a leaf with padding is a pair of the depth and the number of padding nodes above the leaf, its defect, see "What else is in the widget?"), and in the levels of block split, which are those of the uniform tree (in a leaf with padding, the lowest levels cut only padding, see block split). The same real tree can have several lists (consecutive leaves of the same parent may share their padding or not); the undo gives back the padding exactly.

  • Editing. A newline typed in a leaf, or block split at level 0, makes a sibling of the leaf, at its depth. A deletion that joins two leaves of different depths first gives the shallower one nodes of its own, one above the other, until both are equally deep, and then joins them as in a tree whose leaves are equally deep (see "Deletion of text in blocks"): deleting from inside a to inside y in C( a | B( y | z ) ) gives C( W( ay | z ) ), the new node W taking the value of B. block insert across leaves of different depths makes the leaves of its range children of the new block's single node, as for any range. Every change is undone exactly: the tree, the padding and the values come back.

  • Single leaves. block flatten at the root makes the block a single leaf, without nodes: its depth in block list is -1, block at gives its structure as one number, block nodedata at level 0 and -1 names the leaf, and the layout callback gets the leaf as its single argument. A change that gives it a second leaf gives it a root again (see block flatten).

  • Temporary choices. Which sequence of steps an edit uses (a deletion wraps the shallower leaf, block flatten follows a fixed recipe), which values survive (block sprout shares the former leaf's value, the joins keep the start side's), and the -valuecommand events of these commands (copy, new, the events told step by step) are provisional; see BUGS 28.

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, and its depth (in a block that is a single leaf, the block gets a root, the parent of the leaves). The -valuecommand callback is told new for each new leaf (see "Telling the program: -valuecommand").

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. If the two leaves are not equally deep below their common ancestor (a ragged tree, see "Ragged trees"), the shallower one first gets new nodes above it, one level at a time (as block sprout with one index would give it), until both are equally deep; then the nodes are merged in pairs as above. (Leaves and nodes that the range holds whole are deleted first, see "Node values and editing".) The -valuecommand callback is told what the deletion detaches and the nodes it makes (see "Telling the program: -valuecommand").

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: stolen lines (see block addline) and ornaments (see "Ornaments of blocks").

  • (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 (in a block that is a single leaf, the leaf is the only argument). In a ragged tree (see "Ragged trees") the arguments follow the tree of the block: a node's list holds the lists of its leaves and of its nodes side by side, in their order. All the arguments are lists, and

  • if the child is a leaf, then the list consists of the repeat count (necessarily 1), current y offset 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 that are lists of numbers (and should be of the form {dd ... dd}), of lengths 1, 7, or 13, and a fourth one, an ornament (see below). 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.

Any element but the first may also be an ornament of the block (new in 2.08, provisional): a list whose first element is the name of a type of ornament (line, polygon, rectangle, oval, arc, text), followed by numbers, the coordinates of its points (pairs x y, in pixels from the top left corner of the block), and then options and their values, as for ornament create (see "Ornament subcommands"):

['line', 0,14, 3,20, 8,2, 30,2, -width => 1]     # a radical's stroke

An ornament is not a leaf (it is not counted among them) and may come anywhere after the first element. It is drawn with the block, every time the block is drawn: with -layer under (before the text of the leaves, after the stolen lines returned before it in the list), or over the text (the default, after the leaves). See "Ornaments of blocks". A bad ornament (a coordinate that is not a number, an odd number of coordinates, a wrong number of points for its type, a bad option) is reported as other bad results are: a background error, and the block is laid out as if it had no layout callback.

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}

    (w is not very important), put after leaves.

  • Ornament - {type x1 y1 ... ?-option value ...?}, anywhere after the block layout.

Abbreviations:

IGnored, Width, Total Width, Height, Baseline, XOffset, YOffset, Repeat Count, Block Id

None of the returned data is used for clipping. However, it is used in directing the mouse events and reporting bounding boxes (not that of ornaments).

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. In a ragged tree (see "Ragged trees") the true depth is that of the deepest leaf, and a shallower leaf is presented inside lists of one element down to the given depth, so that the callback sees every leaf at that depth.

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

-layoutcmd

Layout callback.

-layoutdepth

Depth of simulated tree for layout callback. Default -1.

-layoutwidths

List of widths of levels of simulated tree for layout callback. Default {}.

-empty

Boolean value that specifies that the blocks of this type contain no leaves (empty blocks).

-ornaments

A list of ornaments drawn for every displayed block of this type (templates; new in 2.08, provisional), each {type point point ... ?-option value ...?} as the arguments of ornament create, whose points are computed from the boxes of the block and of its leaves: see "Ornaments of blocks". Default {} (none). A value that does not parse is an error, and the old value stays.

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: a node is a list of its children, in a ragged tree leaves and nodes side by side ([1, [1, 1]] for R( x | S( 2 | 3 ) )); a block that is a single leaf gives one number (see "Ragged trees").

of index

Returns information in the innermost block that contains the given index or empty list if there is no such block. See at subcommand 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 leaves ab and cd, the other with ef and gh, block insert G 1.2 1.9 (over b|cd|ef) gives {a{b|cd|ef}|gh}: the leaves b, cd and ef of the new block are children of its single node, and the root of the outer block still has two nodes, one with the leaf a{b|cd|ef}, the other with gh. (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 first: a new node is inserted between the root and all its children (one for each level missing), so that the root, which stays the root and keeps its value, has one child; the new node is then split as above.

  • In a ragged tree (see "Ragged trees") the levels are those of the uniform tree the widget keeps, padding nodes included (as the depths of block list): a leaf with d padding nodes above it (its defect) has d levels that cut only its padding, so block split at a level up to d makes the new leaf a sibling of the leaf, as a newline does, and each level above d cuts one real node (its parent, then the parent of that node, and so on). For ax in R( ax | N( b | c ) ) on line 2 (one padding node above ax), block split 2.2 1 gives R( a | x | N( b | c ) ), as block split 2.2 0 does, and block split 2.2 2 inserts a node R1 between R and its children and splits it: R( R1( a ) | Y( x | N( b | c ) ) ). In a block that is a single leaf, split at level 0 gives the block a root again, and at level 1 or more adds a root above the leaf first (see block flatten).

Returns the number of levels added above the root (-1 outside of blocks). The new nodes and the new leaf have no values (the root keeps its value when levels are added: they are inserted below it, see "Node values and editing"); the -valuecommand callback is told new for each. 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.

sprout index1 ?index2?

With one index, the leaf that index1 names (as block nodedata index1 0 names it, see "Which node, which run") gets a new node above it, whose only child it is (a wrap):

P( ... | L | ... )   ->   P( ... | N( L ) | ... )

With {num} on line 2 (head 2.0, num 2.1-2.3, the tail 2.4), .t block sprout 2.1 gives R( N( num ) ) and returns 0. It works on any leaf, the only leaf of a block included, in nested blocks too (the innermost block holding the index), and in a block that is a single leaf (see block flatten), which first gets a root: R( N( leaf ) ). It is the same as the two-index form from the delimiter before the leaf to just after the one after it, which cannot name the only leaf of a block (that range belongs to the enclosing structure). The value of the leaf moves to the new node; the leaf has none afterwards. (Since 2.06; decision O8.)

With two indices, the leaf that holds the range from index1 to index2 gets a node of its own for that range: the leaf L, a child of the node P, becomes three children of P, the text before the range (the start piece), a new node N holding the range as its only leaf (the middle piece), and the text after the range (the end piece):

P( ... | L | ... )   ->   P( ... | start | N( middle ) | end | ... )

So the leaves of the tree are no longer all at the same depth. A range that begins at the start of the leaf's text makes an empty start piece; one that begins one position earlier, on the delimiter before the leaf (the head of the block, or the separator before the leaf), makes none. In the same way a range that ends at the end of the leaf's text makes an empty end piece, and one that ends just after the separator (or the tail) after the leaf makes none: with both delimiters, the leaf just gets a node above it. With {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 sprout 2.2 2.3   ;# {n|u|m|den}: R( n | N( u ) | m | den )
.t block sprout 2.1 2.4   ;# R( | N( num ) | | den ): two empty leaves
.t block sprout 2.0 2.5   ;# R( N( num ) | den )
.t block sprout 2.0 2.3   ;# R( N( nu ) | m | den )
.t block sprout 2.2 2.2   ;# R( n | N( ) | um | den ): an empty middle

(R( a | N( b ) ) is a root R with a leaf a and a node N whose only leaf is b.) Where the range could be read with either of two leaves (it holds just the separator between them), the leaf before the separator is taken. The range must not hold a separator (other than the two delimiters), must not be reversed, and its ends must be in the same block (a block nested wholly in the range moves into the middle piece). The separators go in as with block split at level 0 (marks and tags at the cuts behave the same). Returns the number of separators put in (0, 1 or 2).

The value of the former leaf (see Values) goes to the start piece, the new node and the end piece (those that are made) as the same value: a reference shared, not a copy; the middle leaf gets none. (These choices are temporary.)

How the other commands work on such trees is in "Ragged trees".

Recorded for undo; see "Undo and redo of block and tag changes". Refused while the -valuecommand callback runs.

flatten index level

Flattens a node of the innermost block containing index into one leaf: the node level levels above the leaf index names, counted as for nodedata (0 the leaf itself, 1 its parent, and so on; -1 the root, -2 a child of the root on the way to the leaf). Every separator inside the node is deleted, and where the leaves on its two sides are not equally deep, the deeper one loses the nodes that hold it alone; then the node itself goes, its only leaf taking its place. As steps: until the node's only child is a leaf, the separator inside it farthest to the right whose two leaves are equally deep below their common ancestor is deleted (the join of "Deletion of text in blocks", the nodes on the two sides merged in pairs); if there is none, the deepest node inside it whose only child is a leaf (the one farthest to the right among equally deep ones) is replaced by that leaf (a pull out); then the node itself is pulled out. With {num|den} on line 2:

.t block sprout 2.2 2.5    ;# {n|um|den}: R( n | N( um ) | den )
.t block flatten 2.3 1     ;# R( n | um | den ), returns 0
.t block flatten 2.3 -1    ;# {numden}: the block is one leaf, returns 2

Level 0 does nothing (and is not recorded for undo); a level beyond the leaf's root is an error, worded as for nodedata ("... has 1 level above this leaf"). Blocks nested in the text flattened stay as they are. Returns the number of separators deleted.

The values (see Values): a join keeps the start side's value of each pair merged, or takes the end side's if the start side has none (as a deletion does); a pull out gives the leaf the node's value if the node has one (the leaf's own goes), else the leaf keeps its own (as block trim does). The values that go are kept in the undo step. (The choice of the steps and these rules are temporary.)

Flattening at the root makes the block a single leaf, which is then its own root: block at gives its structure as one number (the leaf's length), nodedata at level 0 and at -1 names the leaf, the layout callback gets the leaf as its single argument, block list gives the depth -1, and block trim refuses it. A newline in the leaf (or block split at level 0) gives the block a real root again, with the two leaves as its children; block split at level 1 or more adds a real root above the leaf, as when a level reaches past the root (the pieces are leaves of the new root; each level more adds one more level, as before); block sprout first gives the block a real root, so that the result is R( start | N( middle ) | end ). The undo of each of these makes the block a single leaf again.

Recorded for undo, one step (see "Undo and redo of block and tag changes"). Refused while the -valuecommand callback runs.

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 (down to the leaf itself). The levels are counted for the leaf index names: in a tree whose leaves are at different depths (see "Ragged trees") the number of levels above a leaf depends on the leaf. Returns the value (an empty result, undef in Perl, if the node has none); with value, sets it and returns nothing, undef removing 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.

A stolen line is a picture: it keeps the size it had, stretched or cut to the box the callback gives it. Strokes that must follow the size of what they decorate (the sign of a radical, the bar of a fraction, the rules of a table) are simpler as ornaments of the block (see "Ornaments of blocks"); the demo uses stolen lines only for glyphs (the delimiters of its LR block) and backgrounds.

deletelines

Deletes all the "stolen" lines.

list from to

See "What else is in the widget?".

Ornaments

(New in 2.08, provisional: the names, the forms of points and the behaviour may change.)

An ornament is a drawing primitive of the kind a canvas has (a line, a polygon, a rectangle, an oval, an arc, a text) whose coordinates are not numbers but reference points: points computed from the places where the characters of the text are drawn. The ornament is computed anew whenever the text is redrawn, so it follows the text it refers to. It takes no room: the text is laid out as if it were not there, and it is drawn over the text, or under it (over the backgrounds of tags).

Points

A point is a list whose first element says how it is computed:

at index ?anchor?

A place on the box of the character at index (as bbox would give it, but not clipped to the window, and for the last character of a display line only its own width, where bbox gives it the rest of the line; inside a block, the box of the character in its leaf).

range index1 index2 ?anchor?

A place on the smallest box that holds the boxes of the characters from index1 up to, not including, index2 (for an empty range, the box of index1 with no width). Its baseline is that of its first character.

line index1 index2 n ?anchor?

A place on the piece of the range from index1 up to index2 that is in its n-th display line: the smallest box that holds the boxes of the range's characters on that display line. n counts from 0 for the first display line of the range, and from -1 for the last; a number beyond the range's display lines gives the nearest one. Inside a block, the display lines are those of its leaves. The display lines are taken in the order of the text (top-level lines from the top down). Only the display lines in the window are known: the part of the range above the window is one piece (the stand-in of index1), the part below it another (the stand-in of index2).

outline index1 index2

Allowed only as a point of a line or a polygon (an error elsewhere, in ornament point or inside another point): it stands for all the corners of the outline of the range, the union of the pieces of its display lines (see line), clockwise from the top left corner of the first piece. For a range over several display lines that is the shape a selection has: the first piece from its first character to its right end, the middle lines whole, the last piece up to its last character (8 corners; more when the middle lines differ in width). The pieces are taken as bands from the top down: a band reaches down to the next one (the space between lines is inside), and pieces side by side (the leaves of a block) make one band, their bounding box. ornament coords gives every corner.

mix weight point ?weight point ...?

The weighted mean of the points (the weights must not add up to 0).

offset point dx dy

The point moved by dx to the right and dy down: screen distances (such as 3 or 2p), or numbers with the unit em or ex (such as 0.5em or -1ex), measured at every redisplay in the font of point: an em is the width of M in that font, an ex half its ascent. The font of an at point is that of the character at its index (the one after the position; with a leftward wrapper, the one before it); that of a range or line point, the largest font in it (the one with the largest em), or with the units emmin, emmid, emmax, exmin, exmid, exmax, its smallest font, the mean of its smallest and largest, or its largest; that of mix, min, max, xy, yx and offset, the font of their first point. A position that is not displayed has the widget's font.

xy point1 point2

The x coordinate of point1 with the y coordinate of point2.

yx point1 point2

The y coordinate of point1 with the x coordinate of point2 (its font is that of point1).

min point ?point ...?, max point ?point ...?

The smallest (largest) x and the smallest (largest) y of the points.

leaf k ?anchor?, block ?anchor?

Only in the ornaments of a block type: see "Ornaments of blocks".

The anchor is one of nw, n, ne, w, center (or c), e, sw, s, se (as in Tk), bw, b, be: the left end, the middle and the right end of the baseline, or mw, m, me: the same on the mid line, half an x-height above the baseline (the x-height is half the ascent of the font of the point: that of its character; for a range, of the largest font in it; the widget's font for a stand-in). It may also be a list of two numbers fx fy: the place at the fraction fx of the width from the left and fy of the height from the top ([0.5, 0.5] is center). The default is bw.

An index that names no mark and no tag (such as 2.5, 2.5+3c or 2.0 lineend) is resolved when the ornament is created (or its points replaced), and the ornament keeps the position as a private mark of its own: the point stays on its character whatever is inserted or deleted before it. A private mark has right gravity (text inserted at it goes before it), except the end of a range, which has left gravity (text inserted at the end of a range stays outside it). An index that names a mark or a tag (insert, mymark+3c, sel.first), end, @x,y, or the name of an embedded image or window, is kept as it is written and computed again at every redisplay. An ornament whose index no longer exists (its mark was unset, its tag removed) is not drawn.

Wherever an index goes, a wrapper makes a private mark of a given gravity, of any index (resolved now, even if it names a mark):

leftward index

A private mark with left gravity (text inserted at it goes after it).

rightward index

A private mark with right gravity.

In Perl a wrapper is an array reference too: [at => [leftward => 'insert']]. The program never sees the private marks: they are not in mark names, mark next, mark previous, dump or block list, cannot be named (the names of marks starting with the character \001 are reserved: mark set refuses them), and never have a value. Deleting an ornament, replacing its points or destroying the widget removes them. ornament points gives the index of each private mark as it is now (a wrapped one as the wrapper: [leftward => '2.7']). When a deletion moved a private mark, its undo puts it back, as it does with the program's marks.

A position that is not displayed (above or below the window) gets a stand-in place: where it would be if every text line between it and the window took one line height (that of the top or bottom display line), with no width. Its x is the one the position had when it was last displayed (each index of each point remembers it, as a place in its display line: it follows horizontal scrolling); if it has not been displayed since the point was given, the middle of the text area, or, with the widget option -ornamentproportional, the place proportional to its offset in its text line (relative to the line's length) across the text area. No line is laid out for a stand-in. A position hidden by -elide between displayed lines gets the place of the next displayed character. An ornament none of whose positions is displayed is not drawn (even a shape whose ends are above and below the window).

When a deletion removes all the text an ornament refers to, the ornament is deleted with it (unless its option -keep is set). Only an ornament all of whose indices are private marks qualifies (one that uses a mark of the program, a tag, end or @x,y is never deleted this way); it is deleted if the character of each at point (the character after its mark, or before it for a mark of left gravity) is deleted, and the range of each range point is inside the deleted text.

Ornaments are not part of the text: they are temporary. Undo does not create or delete them (the undo of a deletion does not bring back an ornament it deleted), and neither dump nor block list shows them.

In Perl a point is an array reference, nested ones for the points it is made of:

$text->markSet(from => '1.4');
$text->markSet(to => '1.12');
# A light box under a range, and an arched arrow between two words.
$text->ornamentCreate('rectangle', [range => 'from', 'to', 'nw'],
    [range => 'from', 'to', 'se'], -fill => '#ffe9a8', -layer => 'under');
$text->ornamentCreate('line', [at => 'from', 's'],
    [offset => [mix => 1, [at => 'from', 's'], 1, [at => 'to', 's']], 0, 20],
    [at => 'to', 's'], -smooth => 1, -arrow => 'last', -fill => 'red');

Ornaments of blocks

A block may have ornaments of its own, drawn with it: the layout callback may return them among its lists (see "Layout callback"), with coordinates in pixels from the top left corner of the block. They take no room and are not leaves; they are drawn every time the block is drawn, under its text (-layer under: before the text of the leaves, and among the stolen lines in the order the callback returned them) or over it (the default: after the leaves), and only where the block's line is drawn (as the rest of what the block draws, they are not clipped to the block, but to its display line). The options are those of ornament create (-keep has no effect; -state hidden hides it). They are not listed by ornament names, have no id and cannot be configured: the callback gives them anew at every layout of the block (their options are read then, once per layout).

A block type may also have ornaments drawn for every block of the type that is displayed: the option -ornaments of block configure, a list of ornament specifications (templates) such as

$text->blockConfigure('Fraction', -ornaments => [
    ['line', [xy => [block => 'w'], [leaf => 0, 's']],
             [xy => [block => 'e'], [leaf => 0, 's']]],   # the bar
]);

each a type, its points and options, as the arguments of ornament create. The points of a template are computed for each block when it is laid out, from two forms of point that exist only there:

leaf k ?anchor?

A place on the box of the k-th leaf of the block (from 0, in the order of the arguments of the layout callback, which is the order of the leaves in the block's tree, depth first): the smallest box that holds its display lines as they are laid out in the block. Its baseline is that of the leaf's first display line, its font that of the leaf's first character (for an empty leaf, the font of the block).

block ?anchor?

A place on the box of the whole block: its width, and its height and baseline (the ascent and descent the layout gave it). Its font is that of the text the block stands in (the tags at the block's position).

and from mix, offset, xy, yx, min and max of such points (an offset in em or ex uses the font of its point, as above). Points with indices (at, range, line, outline) are refused there, and leaf and block are refused everywhere else. The anchors are those of Points (the baseline, the mid line and fractions included; the default is bw). A template that names a leaf beyond the last one, or a leaf the layout callback does not show (a {1} list), is not drawn for that block. Templates are drawn before the ornaments the layout callback returned, in each layer, and in their order; under the text they come before the stolen lines too. block cget gives the list as it was given.

Ornament subcommands

ornament create type point ?point ...? ?option value ...?

Creates an ornament and returns its id (a number). type is line (2 points or more), polygon (3 or more), rectangle, oval or arc (2: opposite corners of the box), or text (1). Ornaments are drawn in the order they were created.

ornament delete id ?id ...?
ornament names

The ids of the ornaments.

ornament configure id ?option? ?value option value ...?
ornament cget id option
ornament points id ?point point ...?

Returns the points of the ornament (as lists, with the indices of its private marks as they are now), or replaces them.

ornament coords id

The points as they are now (x1 y1 x2 y2 ..., in pixels from the top left corner of the window, before smoothing and arrowheads), or an empty list if the ornament is not drawn.

ornament point point

Computes a point now: returns its x and y, and 1 if a position it uses is displayed (0 if only stand-ins were used).

The options (each type has those that apply to it):

-fill color

The color of a line or a text; the inside of the other types (by default none; black for a polygon, a line and a text).

-outline color

The outline of a polygon, rectangle, oval or arc (by default black, for a polygon none).

-width distance

Of the line or outline (1).

-dash list

A dash pattern: lengths in pixels of the dashes and the gaps, such as 4 2 (by default a solid line).

-capstyle, -joinstyle

As for a canvas line (butt, round).

-smooth boolean

A line or polygon becomes a curve, as on a canvas: quadratic splines through the midpoints of its segments, bent toward the points between them (an open line still starts and ends at its end points).

-arrow none|first|last|both, -arrowshape {a b c}

Arrowheads of a line, as on a canvas (8 10 3).

-start degrees, -extent degrees, -style pieslice|chord|arc

Of an arc, as on a canvas: the part of the oval in the box from the angle -start (0 by default: from the right, counterclockwise) over -extent degrees (90 by default; at most 360 either way), drawn as a pie slice (the default), a chord (the arc closed by a straight line), or the arc alone (not filled).

-text string, -font font, -anchor anchor

Of a text: what it says (one line), its font (by default the widget's) and the place of its box (a Tk anchor) at its point (center by default).

-keep boolean

Keep the ornament when its text is deleted (by default it is deleted with it, see above).

-layer over|under

Over the text (the default) or under it.

-state normal|hidden

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, undef in Perl, if the mark has none); with value, sets it and returns nothing, undef removing 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, undef in Perl, if the run has none); with value, sets it and returns nothing, undef removing 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, block sprout, block flatten, 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 (as block trim would). 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 (see block insert in "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; in a tree whose leaves are at different depths (see "Ragged trees") the leaves of the range get back their depths too. 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.

  • block flatten: the undo does the steps back in reverse order (each separator deleted comes back with the nodes it joined, each node pulled out gets its leaf and value back); the tree and the values are exactly those before the flatten. The redo flattens again.

  • block sprout (either form): the undo takes the new node out again (the middle leaf takes its value, if it has one), then deletes the separators the sprout put in (the start piece keeps its value, those of the middle and end pieces go into the undo step); the tree and the values are exactly those before the sprout. The redo sprouts again, and gives back the values the undo took.

  • A deletion that joined two leaves of different depths (see "Ragged trees"): the undo puts the text back with its structure (every leaf at its depth), gives the values back, and then takes out again, in reverse order, the nodes the deletion gave the shallower leaf before joining; the tree and the values are exactly those before the deletion (C( a | B( y | z ) ) again in the example of "Ragged trees"). A value set on such a node after the deletion goes into the undo step meanwhile, and comes back with the redo, which joins as the deletion did.

  • tag add and tag remove over 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 tag sel (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; block sprout and block flatten are kinds of their own). 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, which gives the number of levels above that leaf. The levels are those of the leaf the position names: in a ragged tree (see "Ragged trees") the same node can have different levels from different leaves, and the padding the widget keeps is never counted. In R( x | S( 2 | 3 ) ) on line 2 (x 2.1, 2 2.3, 3 2.5), nodedata 2.1 1 and nodedata 2.3 2 both name the root, which is nodedata 2.1 -1 and nodedata 2.5 -1 too, and nodedata 2.1 2 is an error ("... has 1 level above this leaf"). In a block that is a single leaf, level 0 and level -1 both name the leaf. 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 this leaf

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 split at level 0) splits it: the first part keeps the value, the new leaf starts without one. block split at 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 (in a leaf with padding, see "Ragged trees", the lowest levels cut only padding, which holds no values). Where the level reaches the root, it first inserts a new node between the root and all its children (one for each level missing): the root stays the root and keeps its value, the new node starts without one and is then cut as any other node.

  • 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"); if one of the two is less deep below the common ancestor than the other, it is first given new nodes above it, without values, until both are equally deep (the new node next to a node of the other side then takes that node's value by the rule that follows). 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}, deleting mid| keeps the value of mid on the joined leaf (the inverse of inserting mid and a newline at the start of den), while deleting |mid deletes the leaf mid with 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 trim removes 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 sprout shares the value of the former leaf between the start piece, the new node and the end piece (with one index, or a range from delimiter to delimiter, the value moves to the new node); the middle leaf has none. block flatten keeps, on each join, the start side's value (else the end side's), and on each pull out the node's value (else the leaf's); the others are freed (kept in the undo step). (Temporary choices, see BUGS 28.)

  • block insert inside 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 add over 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 remove or a deletion) keeps its value. A run cut in two (by tag remove in 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 by tag add keeps 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 split and block insert inside a run do not cut it; block insert at 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 remove covers entirely, is gone with its value. tag delete frees 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 that can reports, will do);

  • DESTROYmult (or can) dies: its error is reported as a background error (Tk::Error), as those of the -valuecommand callback 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, and configure with options to set;

  • tag add, tag remove, tag delete, tag raise, tag lower, tag data when it sets something, and tag configure and tag bind when they set something or name a tag that does not exist (a query would create it);

  • mark set, mark unset, and mark gravity and mark data when they set something;

  • block insert, block split, block trim, block delete, block configure when it sets something or names a block type that does not exist (a query would create it), block addline, block deletelines, and block data and block nodedata when they set something;

  • image create, window create, and image configure and window configure with options to set;

  • edit undo, edit redo, edit reset, edit separator, and edit modified with 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. So does a value set after a deletion on a leaf made of what was left of a block the deletion dissolved, also when that block was nested in another one: the undo re-creates the block, and the value waits in the step with the place the leaf has in the text without the deleted range, where the redo gives it back (eText/BUGS 26, 31). If the undo finds no node at an address otherwise, 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, provisionally, which nodes it will create without a value, new); 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:

$kind and $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 that leaf (0 for a leaf), as in "Undo and redo": blockNodedata(@$where) returns the value whatever the depths of the other leaves (see "Ragged trees"). A block is named by its head; block data at 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 (-undo on), 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 $where is 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);

copy

(Temporary.) before block sprout puts the value of a leaf on another owner too (the new node, the end piece): the value is shared, nothing is detached. $where is the place of the value, and its last element names the receiving owner as it is after the change.

new

(Provisional, decision O5.) before the change: the change will create a node or a leaf without a value; $where is the place it will have after the change, [index, level] (the level counted from the node's first leaf, as for the other events), and $value is undef. Told once for each such node or leaf: the new leaf of a newline typed in a block (or of block split), the second halves of the nodes block split cuts and the nodes it adds (see below), the root and the leaves of a new block (block insert) and the leaf of the enclosing block left when a whole leaf moves into the new block, the leaves that the separators of a block a deletion dissolves make in the block around it, the new node and the pieces of block sprout that do not receive a copy of the former leaf's value (its middle leaf always), the nodes a deletion gives the shallower of two leaves before joining them, and the root of a block that was a single leaf and gets a second one. Nodes and leaves that an undo or a redo re-creates are not told (they get back the values they had, restore), nor is the disappearance of a node without a value: a program that wants to follow every node can set a value on each node it is told about. With {num|den} on line 2, the value R on the root and N on num:

.t block split 2.2 1    ;# R( X( n ) | Y( um | den ) )

The split reaches the root, so it first inserts a new node R1 between the root R and all its children; R stays the root and keeps its value, but its address grows by one level, since a node was inserted below it (as for a wrap, see block sprout); then R1 is split into X( n ) and Y( um | den ). This tells new three times, before the change: R1 (that is, X) at [2.1 1], Y at [2.3 1] and the leaf um at [2.3 0]; then the value R is told move from [2.1 1] to [2.1 2] as R1 is inserted below it. blockNodedata(@$where) after the change names the node, unless a later step of the same command gives it a value (a deletion's join, telling move to that place). The ready-made DETACH callback passes new on to no value (there is none).

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 $where is undef. This should not happen. With debug on, 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, block sprout, block flatten, undo, redo, reset (edit reset), separator (edit separator), configure (-maxundo); set for the commands that set a value (block nodedata, tag data, mark data, block data, undef included) and unset for mark 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.

(Temporary.) In a tree whose leaves are at different depths, the steps of block sprout, and of a deletion that joins leaves of different depths, are told each just before it is made: giving a leaf a node above it changes the address of the nodes above the leaf of which it is the first leaf (their level grows by one), told as move with the new place as it is after the change; taking such a node out again (the undo of block sprout, or of such a deletion, after the values have come back) the same way back; the value of a leaf that moves to the node made above it is a move; the copies are told copy; the separators block sprout puts in are told nothing, as for block split. block flatten tells each of its steps just before it is made: a join as a deletion's join (move, drop or stash), a pull out as move of the node's value to the leaf, drop or stash of the leaf's own if both have one, and move of the nodes above whose address changes (their level shrinks by one). The nodes these steps create without a value are told new (see above): block sprout tells them all before its first step, with their places after the command; a deletion tells the nodes it gives the start leaf before giving them, with their places once all are made (the join then keeps them; those it gives the end leaf are merged into the start side's at once and are not told). Nothing is told when a root becomes padding again (the undo of these commands, block flatten at the root).

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 undo and edit redo, which apply the recorded changes of a step one by one: each is told just before it is applied;

  • insert with 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 add and tag remove with 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);

  • block flatten, block sprout, and a deletion that joins leaves of different depths (see above): each step is told just before it is made.

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 DESTROY method dies

Perl does not let an error leave a DESTROY method: it makes it the warning (in cleanup) message, with a tab before it (category misc), given only if warnings are on where the error is raised (use warnings there, or perl -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 DESTROY method

The refusal (cannot modify .t while its values are being freed, 10 changes deep, see "When values are freed") is an error raised inside the DESTROY method, 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 without use warnings: if it leaves DESTROY as it is, the warning is given only under perl -w ($^W), and is lost otherwise. To know, catch it with eval inside DESTROY:

sub DESTROY {
  my $self = shift;
  eval { $self->{widget}->insert('end', "gone\n"); 1 }
    or warn "not made: $@";
}
The -valuecommand callback dies, or a DETACH method

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

DESTROYmult dies

A background error, and the answer counts as 0: the change is refused ("When values are freed"), and that refusal, raised inside a DESTROY method, is the case above.

Additional text widget options

-valuecommand

A callback told before a command detaches values (or creates nodes without values), see "Telling the program: -valuecommand"; 'DETACH' passes the notification on to values that are objects with a DETACH method. 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 1 is 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; since 2.06 the widget ignores them (before, some of them changed what the widget's own extractions, block list and the undo's records, contained).

-ornamentproportional

A boolean (0 by default; new in 2.08, provisional). The x of the stand-in of a position of an ornament that is not displayed, and was never displayed since the ornament got it: when set, proportional to the position's offset in its text line (relative to the line's length) across the width of the text area; else the middle of the text area. See Ornaments.

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>

AVAILABILITY

ftp://ftp.math.ohio-state.edu/pub/users/ilya.