Perl in a Nutshell

Perl in a NutshellSearch this book
Previous: 18.10 The Listbox WidgetChapter 18
Perl/Tk
Next: 18.12 The Canvas Widget
 

18.11 The Text Widget

Create a text widget with the Text method:

$parentwidget->Text ( options)
The standard configuration options that apply to Text are: -background, -bg, -borderwidth, -bd, -cursor, -exportselection, -font, -foreground, -fg, -height, -highlightbackground, -highlightcolor, -highlightthickness, -insertbackground, -insertborderwidth, -insertofftime, -insertontime, -insertwidth, -padx, -pady, -relief, -selectbackground, -selectborderwidth, -selectforeground, -state, -takefocus, -width, -xscrollcommand, and -yscrollcommand.

Other options are:

-setgrid => boolean

Turns on gridding for the text widget. Default is 0 (off).

-spacing1 => amount

Defines the amount of space left on the top of a line of text that starts on its own line. Default is 0.

-spacing2 => amount

Defines the amount of space left on the top of a line of text after it has been automatically wrapped by the text widget. Default is 0.

-spacing3 => amount

Defines the amount of space left after a line of text that has been ended by "\n". Default is 0.

-tabs => list

Specifies a list of tab stops to use in the text widget. Default is undefined (no tab stops).

-wrap => mode

Sets the mode for determining automatic line wrapping. Values are "none" (no wrapping), "char" (wrap at any character), or "word" (wrap at a word boundary). Default is "char".

18.11.1 Text Indexes and Modifiers

In a Text widget, several indexes are defined to identify positions in the text widget, for use by the methods used for retrieving or manipulating text. These indexes are:

n.m

Numbers representing character m on line n.

@x,y

The character closest to the x,y coordinate.

end

The end of the text.

insert

The character after the insert cursor.

current

The position closest to the mouse cursor.

mark

Other marks defined for the widget (see discussion of text marks later in this section).

sel.first

The first selected character.

sel.last

The character just after the last selected character.

tag.first

The first character in the widget of the specified tag type.

tag.last

The character just after the last character of the specified tag type.

widget

The location of an embedded widget.

There are also several modifiers to use with text indexes. They are:

+ n lines
- n lines

n lines before or after the index.

+ n chars
- n chars

n characters before or after the index.

linestart

The first character on the line.

lineend

The last character on the line (often a newline).

wordstart

The first character in the word.

wordend

The character after the last character in the word.

18.11.2 Text Methods

In addition to configure and cget, the following methods are defined for the Text widget.

bbox

Returns the location and dimensions of the bounding box surrounding the character at the specified index. The returned list contains four numbers representing (respectively) the x coordinate of the upper-left corner, the y coordinate of the upper-left corner, the width of the text in pixels, and the height of the text in pixels.

compare

Performs a comparison on two indexes. For example:

if ($text->compare('insert', '==', 'end') { 
	# we're at the end of the text
}
The valid operators are <, <=, ==, >=, and !=.

debug

Given a boolean, turns debugging on or off.

delete

Deletes text from the text widget. To delete everything:

$text->delete(0, 'end');

dlineinfo

Returns the location and dimensions of the bounding box surrounding the line at the specified index. The returned list contains five numbers representing (respectively) the x coordinate of the upper-left corner, the y coordinate of the upper-left corner, the width of the text in pixels, the height of the text in pixels, and the baseline position of the line.

get

Returns the text located in the given index range.

index

Given a named index, returns its numeric equivalent in the format line.char.

insert

Inserts text into the widget at the specified location. The second argument is the text to insert and the third argument is either a single tag or a list reference containing the names of multiple tags to apply to the text. Subsequent arguments alternate between text and tags. For example:

$text->insert('end', 'You want to do ', 'normal', 
                     'what?!', ['bold','red']);

search

Returns the index containing a particular string in the text widget. For example, to search backwards for a case-insensitive hostname starting from the end of the text:

$hostindex = $text->search(-nocase, -backwards, $hostname, 'end');
The search method takes several switches to modify the search, each starting with "-". The first argument that does not start with "-" is taken to be the search string. The switches are:
-forwards

Search forwards starting at the specified index.

-backwards

Search backwards starting at the specified index.

-exact

Match the string exactly (default).

-regexp

Treat the pattern as a regular expression.

-nocase

Ignore case.

-count => \$variable

Store the number of matches into the specified variable.

--

Interpret the next argument as the pattern. (Useful when the pattern starts with a "-".)

see

Scrolls the text so that the portion of the text containing the specified index is visible.

window

Embeds widgets within the Text widget. The first argument can be any of: 'create', 'names', 'cget', and 'configure'.

create

Inserts an embedded widget at a specified index. Each widget occupies one character in the text widget. The widget must have already been created as a child of the text widget. For example:

$button = $text->Label(-text => "How ya doing?");
$text->window('create','end', -window => $button);
Here, the -window option is used to identify the widget to embed. The list of options to window ('create') is:
-align

Determines the positioning within the line of text. Values are 'baseline', 'bottom', 'top', or 'center' (default).

-padx

Adds padding in the x direction.

-pady

Adds padding in the y direction.

-window

Identifies the widget to embed.

names

Returns a list of widget types embedded into the text widget.

cget

Returns information on the widget at the specified index.

$text->window('cget',0);

configure

Configures widget at the specified index.

$text->window('configure',0,-background => "green");

xview

Manipulates the text in view. With no arguments, returns a list of two numbers between 0 and 1, defining what portion of the text is currently hidden on the left and right sides, respectively. With arguments, the function of xview changes:

index

If the first argument is an index, that position becomes the leftmost position in view.

moveto

Moves the specified fraction of the text to the left of the visible portion.

scroll

Scrolls the text left or right by the specified number of units (characters, in this context) or pages. Used primarily as a callback to a scrollbar; pressing on an arrow would move by units (characters), and pressing on the trough would move by pages. The number is either 1 or -1, to move forwards or backwards, respectively.

yview

Manipulates the text in view. With no arguments, returns a list of two numbers between 0 and 1, defining what portion of the text is currently hidden on the top and bottom, respectively. With arguments, the function of yview changes:

index

If the first argument is an index, that position becomes the topmost position in view.

moveto

Moves the specified fraction of the text to the top of the visible portion.

scroll

Scrolls the text up or down by the specified number of units (lines, in this context) or pages. Used primarily as a callback to a scrollbar; pressing on an arrow would move by units (lines), and pressing on the trough would move by pages. The number is either 1 or -1, to move forwards or backwards, respectively.

18.11.3 Tags

You can associate a distinct set of format properties to a portion of the text using tags. A tag is defined with the tagConfigure method, and text is associated with a tag via an option to the insert or tagAdd method. For example:

$text->Text->pack;
$text->tagConfigure('bold', -font =>
     '-*-Courier-Medium-B-Normal-*-120-*-*-*-*-*-*");
$text->insert('end', "Normal text\n");
$text->insert('end', "Bold text\n", 'bold');
There are several methods defined for manipulating text tags. They are:

tagAdd

Adds a tag to the text within the specified index range. For example, to assign the "bold" tag defined above to the current selection:

$text->tagAdd('bold','sel.first','sel.last');
You can supply multiple ranges as arguments to tagAdd.

tagBind

Executes a callback when a specified event happens on the tagged text. For example:

$text->tagBind('goto_end', "<Button-1>", sub {shift->see('end');} );

tagConfigure

Creates or changes settings for a text tag, for example:

$text->tagConfigure('link', -foreground => 'red');
Options for configuring text tags are:
-background => color

The color to use behind the text.

-bgstipple => bitmap

A pattern to draw behind the text.

-borderwidth => amount

The width of the edge drawn around the text.

-fgstipple => bitmap

A pattern used to draw the text.

-font => fontname

The font used for the text.

-foreground => color

The color of the text.

-justify => position

The justification of the text (any of 'left', 'right', and 'center'). The default is 'left'.

-lmargin1 => amount

The indentation for the first line of a paragraph.

-lmargin2 => amount

The indentation for subsequent lines of a paragraph (for hanging indents).

-offset => amount

The amount the text is raised or lowered from the baseline (for subscripts and superscripts).

-overstrike => boolean

Draws the text with a line through it.

-relief => type

The type of edges drawn around the text. Values for type can be 'flat', 'groove', 'raised', 'ridge', and 'sunken'. Default is 'flat'.

-rmargin => amount

The right margin.

-spacing1 => amount

The amount of space left on the top of a line of text that starts on its own line.

-spacing2 => amount

The amount of space left on the top of a line of text after it has been automatically wrapped by the text widget.

-spacing3 => amount

The amount of space left after a line of text that has been ended by "\n".

-tabs => list

A list of tab stops to use in the text widget.

-underline => boolean

Whether to underline the text.

-wrap => mode

Sets the mode for determining automatic line wrapping. Values are "none" (no wrapping), "char" (wrap at any character), or "word" (wrap at a word boundary).

tagCget

Returns configuration settings for a tag.

tagDelete

Deletes the specified tag(s).

tagRemove

Removes the tags from the text in the specified index range. (The tag itself remains defined, but is no longer applied to that text.)

tagRaise

Increases priority for a specified tag. With only one argument, the tag takes highest priority over all others; with a second argument of another tag, the tag's priority is just higher than the second tag. For example:

$text->tagRaise('bold','italic');

tagLower

Decreases priority for a specified tag. With only one argument, the tag takes lowest priority to all others; with a second argument of another tag, the tag's priority is just lower than the second tag. For example:

$text->tagLower('italic','bold');
(The outcome of this code is effectively identical to that of the previous example.)

tagNames

Returns the names of all tags applying to the specified index. With no index specified, returns all tags defined for the text widget, regardless of whether they have been applied.

@defined_tags = $text->tagNames;

tagRanges

Returns a list of index ranges to which the specified tag is defined. The returned list contains pairs of starting and ending indexes for the ranges.

@bold_indexes = $text->tagRanges('bold');

tagNextrange

Given a tag name and an index, returns the next index range to which the specified tag is defined.

@next_bold = $text->tagRanges('bold', 'insert');

18.11.4 Marks

A mark refers to a particular position in between characters in a text widget. Once you create a mark, you can use it as an index. The gravity of the mark affects which side the text is inserted. "Right" gravity is the default, in which case the text is inserted to the right of the mark.

The two marks that are automatically set are "insert" and "current". The "insert" mark refers to the position of the insert cursor. The "current" mark is the position closest to the mouse cursor.

The following methods are defined for marking:

markGravity

Sets the gravity of a mark. For example:

$text->markGravity('insert', 'left');

markNames

Returns a list of all marks defined for the text widget.

markSet

Creates a mark at a specified index.

$text->markSet('saved', 'insert');

markUnset

Deletes mark(s) from the text widget.

$text->markUnset('saved');

Note that you cannot delete the "insert" or "current" marks.


Previous: 18.10 The Listbox WidgetPerl in a NutshellNext: 18.12 The Canvas Widget
18.10 The Listbox WidgetBook Index18.12 The Canvas Widget