Text(3pm)
okay bestie, welcome to Text(3pm) β the User Contributed Perl Documentation page for Tk::Text, aka the create-and-manipulate-Text-widgets icon π
β¨
π NAME π
Tk::Text β Create and manipulate Text widgets π¦
β¨ SYNOPSIS β¨
The classic call is this, and then you get a whole menu of standard options:
$text = $parent->Text(?options?);
-background -highlightbackground -insertontime -selectborderwidth
-borderwidth -highlightcolor -insertwidth -selectforeground
-cursor -highlightthickness -padx -setgrid
-exportselection -insertbackground -pady -takefocus
-font -insertborderwidth -relief -xscrollcommand
-foreground -insertofftime -selectbackground -yscrollcommand
π WIDGET-SPECIFIC OPTIONS π
πΈ height πΈ
- Name:
height - Class:
Height - Switch:
-height
Specifies the desired height for the window, in units of characters in the font given by the -font option. Must be at least one. so no zero-height nonsense, bestie π
β¨ spacing1 β¨
- Name:
spacing1 - Class:
Spacing1 - Switch:
-spacing1
Requests additional space above each text line in the widget, using any of the standard forms for screen distances. If a line wraps, this option only applies to the first line on the display. This option may be overridden with -spacing1 options in tags. extra headroom energy, but only for the first display line when wrapping π
π«§ spacing2 π«§
- Name:
spacing2 - Class:
Spacing2 - Switch:
-spacing2
For lines that wrap (so that they cover more than one line on the display) this option specifies additional space to provide between the display lines that represent a single line of text. The value may have any of the standard forms for screen distances. This option may be overridden with -spacing2 options in tags. breathing room between the wrapped bits π¬οΈ
π¦ spacing3 π¦
- Name:
spacing3 - Class:
Spacing3 - Switch:
-spacing3
Requests additional space below each text line in the widget, using any of the standard forms for screen distances. If a line wraps, this option only applies to the last line on the display. This option may be overridden with -spacing3 options in tags. a little footer padding for every line πΏ
π state π
- Name:
state - Class:
State - Switch:
-state
Specifies one of two states for the text: normal or disabled. If the text is disabled then characters may not be inserted or deleted and no insertion cursor will be displayed, even if the input focus is in the widget. so if it's disabled, don't try to type β it's giving locked π
π tabs π
- Name:
tabs - Class:
Tabs - Switch:
-tabs
Specifies a set of tab stops for the window. The option's value consists of a list of screen distances giving the positions of the tab stops. Each position may optionally be followed in the next list element by one of the keywords left, right, center, or numeric, which specifies how to justify text relative to the tab stop. left is the default; it causes the text following the tab character to be positioned with its left edge at the tab position. right means that the right edge of the text following the tab character is positioned at the tab position, and center means that the text is centered at the tab position. numeric means that the decimal point in the text is positioned at the tab position; if there is no decimal point then the least significant digit of the number is positioned just to the left of the tab position; if there is no number in the text then the text is right-justified at the tab position. For example, -tabs => [qw/2c left 4c 6c center/] creates three tab stops at two-centimeter intervals; the first two use left justification and the third uses center justification. If the list of tab stops does not have enough elements to cover all of the tabs in a text line, then Tk extrapolates new tab stops using the spacing and alignment from the last tab stop in the list. The value of the tabs option may be overridden by -tabs options in tags. If no -tabs option is specified, or if it is specified as an empty list, then Tk uses default tabs spaced every eight (average size) characters. tab stops but make it fashion π
π― width π―
- Name:
width - Class:
Width - Switch:
-width
Specifies the desired width for the window in units of characters in the font given by the -font option. If the font doesn't have a uniform width then the width of the character 0 is used in translating from character units to screen units. math but make it text π
π wrap π
- Name:
wrap - Class:
Wrap - Switch:
-wrap
Specifies how to handle lines in the text that are too long to be displayed in a single line of the text's window. The value must be none or char or word. A wrap mode of none means that each line of text appears as exactly one line on the screen; extra characters that don't fit on the screen are not displayed. In the other modes each line of text will be broken up into several screen lines if necessary to keep all the characters visible. In char mode a screen line break may occur after any character; in word mode a line break will only be made at word boundaries. choose your fighter π₯
π DESCRIPTION π
The Text method creates a new window (given by the $text argument) and makes it into a text widget. Additional options, described above, may be specified on the command line or in the option database to configure aspects of the text such as its default background color and relief. The text command returns the path name of the new window. boom, new widget just dropped π
A text widget displays one or more lines of text and allows that text to be edited. Text widgets support four different kinds of annotations on the text, called tags, marks, embedded windows or embedded images. Tags allow different portions of the text to be displayed with different fonts and colors. In addition, perl/Tk callbacks can be associated with tags so that scripts are invoked when particular actions such as keystrokes and mouse button presses occur in particular ranges of the text. See "TAGS" below for more details. four annotation girlies and they all serve π
The second form of annotation consists of marks, which are floating markers in the text. Marks are used to keep track of various interesting positions in the text as it is edited. See "MARKS" below for more details. floating markers, literally tracking the vibe π
The third form of annotation allows arbitrary windows to be embedded in a text widget. See "EMBEDDED WINDOWS" below for more details. windows inside windows, inception but make it Tk πͺ
The fourth form of annotation allows Tk images to be embedded in a text widget. See "EMBEDDED IMAGES" below for more details. pics in your text, iconic πΌοΈ
π¨ Big note, bestie: The Perl/Tk Text widget does not support undo/redo, use the TextUndo widget instead. no take-backs in this one π
β¨ INDICES β¨
Ok bestie, listen up π A lot of the methods for texts take one or more indices as arguments. An index is literally just a string that points to a particular place in a text β like where to insert characters, or one endpoint of a range of characters to delete. It's giving coordinates for your text era. π
Indices have the syntax:
base modifier modifier modifier ...
Where base gives a starting point and the modifiers adjust the index from that starting point (e.g. move forward or backward one character). Every index must contain a base, but the modifiers are optional. No cap.
The base forms (the main character energy) π
The base for an index must have one of these forms:
line.charβ indicates thechar'th character on lineline. Lines are numbered from 1 for consistency with other UNIX programs that use this numbering scheme. Within a line, characters are numbered from 0. Ifcharisendthen it refers to the newline character that ends the line. π@x,yβ indicates the character that covers the pixel whosexandycoordinates within the text's window arexandy. πendβ indicates the end of the text (the character just after the last newline). β¨markβ indicates the character just after the mark whose name ismark. π·οΈtag.firstβ indicates the first character in the text that has been tagged withtag. This form generates an error if no characters are currently tagged withtag. πtag.lastβ indicates the character just after the last one in the text that has been tagged withtag. This form generates an error if no characters are currently tagged withtag. π$widgetβ indicates the position of the embedded window referenced by$widget. This form generates an error if$widgetdoes not reference to an embedded window. πͺimageNameβ indicates the position of the embedded image whose name isimageName. This form generates an error if there is no embedded image by the given name. πΌοΈ
If the base could match more than one of the above forms, such as a mark and imageName both having the same value, then the form earlier in the above list takes precedence. So like, first come first served, bestie. π
Modifiers (the glow-up era) β¨
If modifiers follow the base index, each one of them must have one of the forms listed below. Keywords such as chars and wordend may be abbreviated as long as the abbreviation is unambiguous. Slay, abbreviations.
+ count charsβ adjust the index forward bycountcharacters, moving to later lines in the text if necessary. If there are fewer thancountcharacters in the text after the current index, then set the index to the last character in the text. Spaces on either side ofcountare optional. β‘οΈ- count charsβ adjust the index backward bycountcharacters, moving to earlier lines in the text if necessary. If there are fewer thancountcharacters in the text before the current index, then set the index to the first character in the text. Spaces on either side ofcountare optional. β¬ οΈ+ count linesβ adjust the index forward bycountlines, retaining the same character position within the line. If there are fewer thancountlines after the line containing the current index, then set the index to refer to the same character position on the last line of the text. Then, if the line is not long enough to contain a character at the indicated character position, adjust the character position to refer to the last character of the line (the newline). Spaces on either side ofcountare optional. β¬οΈ- count linesβ adjust the index backward bycountlines, retaining the same character position within the line. If there are fewer thancountlines before the line containing the current index, then set the index to refer to the same character position on the first line of the text. Then, if the line is not long enough to contain a character at the indicated character position, adjust the character position to refer to the last character of the line (the newline). Spaces on either side ofcountare optional. β¬οΈlinestartβ adjust the index to refer to the first character on the line. πlineendβ adjust the index to refer to the last character on the line (the newline). πwordstartβ adjust the index to refer to the first character of the word containing the current index. A word consists of any number of adjacent characters that are letters, digits, or underscores, or a single character that is not one of these. π§wordendβ adjust the index to refer to the character just after the last one of the word containing the current index. If the current index refers to the last character of the text then it is not modified. π«Ά
If more than one modifier is present then they are applied in left-to-right order. For example, the index end - 1 chars refers to the next-to-last character in the text and insert wordstart - 1 c refers to the character just before the first one in the word containing the insertion cursor. Periodt. π
π·οΈ TAGS π·οΈ
Okay so the first way you can annotate stuff in text widgets is with a tag, and bestie it's giving main character energy fr. A tag is literally just a text string that you associate with some of the characters in a text. Tags can contain any characters you want, but honestly? Probably best to dodge `` (space), +, or -. Why? Because those characters have special meaning in indices, so tags containing them can't be used as indices. That's the whole tea. π
You can have any number of tags associated with characters in a text. Each tag may refer to a single character, a range of characters, or several ranges of characters. And an individual character may have any number of tags associated with it β it's polyamorous like that, no cap. π
A priority order is defined among tags, and this order gets used when implementing some of the tag-related functions described below. When a tag is defined (by associating it with characters or setting its display options or binding callbacks to it), it is given a priority higher than any existing tag. You can redefine the priority order of tags using the $text->tagRaise and $text->tagLower methods. Slay. β¨
the three purposes, because tags are multitalented π
Tags serve three purposes in text widgets. Let's go.
1. They control how info shows up on screen π¨
By default, characters are displayed as determined by the background, font, and foreground options for the text widget. But display options can be associated with individual tags using the $text->tagConfigure method. If a character has been tagged, then the display options associated with the tag override the default display style. Iconic behavior honestly.
The following options are currently supported for tags:
-background => colorβcolorspecifies the background color to use for characters associated with the tag. It may have any of the forms accepted byTk_GetColor.-bgstipple => bitmapβbitmapspecifies a bitmap that is used as a stipple pattern for the background. It may have any of the forms accepted byTk_GetBitmap. Ifbitmaphasn't been specified, or if it is specified as an empty string, then a solid fill will be used for the background.-borderwidth => pixelsβpixelsspecifies the width of a 3-D border to draw around the background. It may have any of the forms accepted byTk_GetPixels. This option is used in conjunction with the-reliefoption to give a 3-D appearance to the background for characters; it is ignored unless the-backgroundoption has been set for the tag. π-elide => booleanβelidespecifies whether the data should be elided. Elided data is not displayed and takes no space on screen, but further on behaves just as normal data. (Ghost mode activated π»)-data => valueβ allows an arbitrary perl scalar value to be associated with the tag.-fgstipple => bitmapβbitmapspecifies a bitmap that is used as a stipple pattern when drawing text and other foreground information such as underlines. It may have any of the forms accepted byTk_GetBitmap. Ifbitmaphasn't been specified, or if it is specified as an empty string, then a solid fill will be used.-font => fontNameβfontNameis the name of a font to use for drawing characters. It may have any of the forms accepted byTk_GetFontStruct.-foreground => colorβcolorspecifies the color to use when drawing text and other foreground information such as underlines. It may have any of the forms accepted byTk_GetColor.-justify => justifyβ if the first character of a display line has a tag for which this option has been specified, thenjustifydetermines how to justify the line. It must be one ofleft,right, orcenter. If a line wraps, then the justification for each line on the display is determined by the first character of that display line.-lmargin1 => pixelsβ if the first character of a text line has a tag for which this option has been specified, thenpixelsspecifies how much the line should be indented from the left edge of the window.pixelsmay have any of the standard forms for screen distances. If a line of text wraps, this option only applies to the first line on the display; the-lmargin2option controls the indentation for subsequent lines.-lmargin2 => pixelsβ if the first character of a display line has a tag for which this option has been specified, and if the display line is not the first for its text line (i.e., the text line has wrapped), thenpixelsspecifies how much the line should be indented from the left edge of the window.pixelsmay have any of the standard forms for screen distances. This option is only used when wrapping is enabled, and it only applies to the second and later display lines for a text line.-offset => pixelsβpixelsspecifies an amount by which the text's baseline should be offset vertically from the baseline of the overall line, in pixels. For example, a positive offset can be used for superscripts and a negative offset can be used for subscripts.pixelsmay have any of the standard forms for screen distances.-overstrike => booleanβ specifies whether or not to draw a horizontal rule through the middle of characters.booleanmay have any of the forms accepted byTk_GetBoolean.-relief => reliefβreliefspecifies the 3-D relief to use for drawing backgrounds, in any of the forms accepted byTk_GetRelief. This option is used in conjunction with the-borderwidthoption to give a 3-D appearance to the background for characters; it is ignored unless the-backgroundoption has been set for the tag.-rmargin => pixelsβ if the first character of a display line has a tag for which this option has been specified, thenpixelsspecifies how wide a margin to leave between the end of the line and the right edge of the window.pixelsmay have any of the standard forms for screen distances. This option is only used when wrapping is enabled. If a text line wraps, the right margin for each line on the display is determined by the first character of that display line.-spacing1 => pixelsβpixelsspecifies how much additional space should be left above each text line, using any of the standard forms for screen distances. If a line wraps, this option only applies to the first line on the display.-spacing2 => pixelsβ for lines that wrap, this option specifies how much additional space to leave between the display lines for a single text line.pixelsmay have any of the standard forms for screen distances.-spacing3 => pixelsβpixelsspecifies how much additional space should be left below each text line, using any of the standard forms for screen distances. If a line wraps, this option only applies to the last line on the display.-tabs => tabListβtabListspecifies a set of tab stops in the same form as for the-tabsoption for the text widget. This option only applies to a display line if it applies to the first character on that display line. If this option is specified as an empty string, it cancels the option, leaving it unspecified for the tag (the default). If the option is specified as a non-empty string that is an empty list, such as-tabs = " ">, then it requests default 8-character tabs as described for the tabs widget option.-underline => booleanβbooleanspecifies whether or not to draw an underline underneath characters. It may have any of the forms accepted byTk_GetBoolean.-wrap => modeβmodespecifies how to handle lines that are wider than the text's window. It has the same legal values as the-wrapoption for the text widget:none,char, orword. If this tag option is specified, it overrides the-wrapoption for the text widget.
when the options start fighting βοΈ
If a character has several tags associated with it, and if their display options conflict, then the options of the highest priority tag are used. Periodt.
If a particular display option hasn't been specified for a particular tag, or if it is specified as an empty string, then that option will never be used; the next-highest-priority tag's option will be used instead. And if no tag specifies a particular display option, then the default style for the widget will be used. The hierarchy is real. π
2. Event bindings π―
The second purpose for tags is event bindings. You can associate bindings with a tag in much the same way you can associate bindings with a widget class: whenever particular X events occur on characters with the given tag, a given <perl/Tk callback|Tk::callbacks> will be executed.
Tag bindings can be used to give behaviors to ranges of characters; among other things, this allows hypertext-like features to be implemented. Lowkey iconic. For details, see the description of the tagBind widget method below. π₯
3. Managing the selection βοΈ
The third use for tags is in managing the selection. See "THE SELECTION" below. π
β¨ MARKS β¨
okay so the second flavor of annotation in text widgets is a mark. Marks are literally just little bookmarks for remembering specific places in your text. They're kinda like tags β they got names, they point at places in the file β but here's the plot twist: a mark isn't tied to any particular characters. Nope. A mark lives in the gap between two characters. π
And only one single position can be associated with a mark at any given time. That's the rule, bestie.
The way marks handle deletion is so different from tags. If the characters around a mark get deleted? The mark survives β it just gets new neighbor characters, no big deal. But if the characters containing a tag get deleted, the tag just loses its association with characters in the file entirely. rip tag. π
You can mess with marks using the $text->mark text widget method, and you can find out where they're at right now by using the mark name as an index in methods. iykyk β¨
Every mark also has a gravity, which is either left or right. Gravity = what happens to the mark when text gets inserted right at the point of the mark. The math is simple:
- If a mark has left gravity, it's treated as if it were attached to the character on its left, so the mark stays to the left of any text inserted at the mark position.
- If a mark has right gravity, new text inserted at the mark position shows up to the right of the mark.
The gravity for a mark defaults to right. periodt.
Also important: the name space for marks is different from the one for tags. So like, the same name can be used for both a mark and a tag, but they will refer to different things. No cap.
Two marks have special significance, and you're gonna wanna know about both:
- The mark
insertis associated with the insertion cursor, as described under "THE INSERTION CURSOR" below. π - The mark
currentis associated with the character closest to the mouse, and it gets adjusted automatically to track the mouse position and any changes to the text in the widget. (one exception:currentis not updated in response to mouse motions if a mouse button is down β the update gets deferred until all mouse buttons have been released.)
π«Ά Heads up bestie: neither of these special marks may be deleted. Not up for debate.
πͺ EMBEDDED WINDOWS πͺ
The third form of annotation in text widgets is an embedded window. Each embedded window annotation makes a window show up at a particular point in the text. πΈ
You can have any number of embedded windows in a text widget, and any widget can be used as an embedded window β subject to the usual rules for geometry management, which require the text window to be the parent of the embedded window, or a descendant of its parent. The embedded window's position on the screen gets updated as the text is modified or scrolled, and it will be mapped and unmapped as it moves into and out of the visible area of the text widget. π«
Each embedded window takes up one character's worth of index space in the text widget, and you can refer to it either by the name of its embedded window or by its position in the widget's index space. And if the range of text containing the embedded window gets deleted? Then the window gets destroyed. π
When an embedded window gets added to a text widget with the widgetCreate method, you can associate a bunch of configuration options with it. Those options can be modified later with the widgetConfigure method. The following options are currently supported:
-align => whereβ If the window isn't as tall as the line it's displayed in, this option decides where in the line the window sits. where has to be one of:top(align the top of the window with the top of the line),center(center the window within the range of the line),bottom(align the bottom of the window with the bottom of the line's area), orbaseline(align the bottom of the window with the baseline of the line). π-create => callbackβ Specifies a callback that may be evaluated to create the window for the annotation. If no-windowoption has been specified for the annotation, this callback gets evaluated when the annotation is about to be displayed on screen. callback must create a window for the annotation and return the name of that window as its result. And if the annotation's window ever gets deleted, callback will be evaluated again the next time the annotation is displayed. β¨-padx => pixelsβ pixels specifies the amount of extra space to leave on each side of the embedded window. It may have any of the usual forms defined for a screen distance (seeTk_GetPixels).-pady => pixelsβ pixels specifies the amount of extra space to leave on the top and on the bottom of the embedded window. It may have any of the usual forms defined for a screen distance (seeTk_GetPixels).-stretch => booleanβ If the requested height of the embedded window is less than the height of the line it's displayed in, this option lets you say whether the window should be stretched vertically to fill its line. And if the-padyoption has been specified as well, then the requested padding will be retained even if the window gets stretched. π«Ά-window => $widgetβ Specifies the name of a window to display in the annotation.
πΌοΈ EMBEDDED IMAGES πΌοΈ
The final form of annotation in text widgets is an embedded image. Each embedded image annotation makes an image show up at a particular point in the text. π
You can have any number of embedded images in a text widget, and a particular image can be embedded in multiple places in the same text widget. The embedded image's position on the screen gets updated as the text is modified or scrolled. Each embedded image takes up one character's worth of index space in the text widget, and you can refer to it either by its position in the widget's index space, or by the name it's assigned when the image is inserted into the text widget with imageCreate. And if the range of text containing the embedded image gets deleted, then that copy of the image is removed from the screen. π
When an embedded image gets added to a text widget with the image create method, a name unique to this instance of the image is returned. That name can then be used to refer to this image instance. The name is taken to be the value of the -name option (described below). If the -name option isn't provided, the -image name gets used instead. And if the imageName is already in use in the text widget, then #nn gets added to the end of the imageName, where nn is an arbitrary integer. This insures the imageName is unique. β¨
Once this name is assigned to this instance of the image, it does not change β even though the -image or -name values can be changed with image configure.
When an embedded image gets added to a text widget with the imageCreate method, several configuration options can be associated with it. These options can be modified later with the image configure method. The following options are currently supported:
-align => whereβ If the image isn't as tall as the line it's displayed in, this option decides where in the line the image sits. where has to be one of:top(align the top of the image with the top of the line),center(center the image within the range of the line),bottom(align the bottom of the image with the bottom of the line's area), orbaseline(align the bottom of the image with the baseline of the line). π-image => imageβ Specifies the name of the Tk image to display in the annotation. If image isn't a valid Tk image, then an error is returned.-name => ImageNameβ Specifies the name by which this image instance may be referenced in the text widget. If ImageName isn't supplied, then the name of the Tk image gets used instead. If the imageName is already in use,#nngets appended to the end of the name, as described above. β¨-padx => pixelsβ pixels specifies the amount of extra space to leave on each side of the embedded image. It may have any of the usual forms defined for a screen distance.-pady => pixelsβ pixels specifies the amount of extra space to leave on the top and on the bottom of the embedded image. It may have any of the usual forms defined for a screen distance.
π THE SELECTION π
Selection support is implemented via tags. If the exportSelection option for the text widget is true, then the sel tag gets associated with the selection. Here's the whole tea, numbered:
- Whenever characters are tagged with
sel, the text widget will claim ownership of the selection. π - Attempts to retrieve the selection will be serviced by the text widget, returning all the characters with the
seltag. - If the selection gets claimed away by another application or by another window within this application, then the
seltag will be removed from all characters in the text. - Whenever the
seltag range changes, a virtual event<<Selection>>is generated. β¨
The sel tag is automatically defined when a text widget is created, and it may not be deleted with the `$text->tagDelete` method. Furthermore, the selectBackground, selectBorderWidth, and selectForeground options for the text widget are tied to the -background, -borderwidth, and -foreground options for the sel tag: changes in either will automatically be reflected in the other. π«Ά
π THE INSERTION CURSOR π
The mark named insert has special significance in text widgets. It's defined automatically when a text widget is created, and it may not be unset with the `$text->markUnset` widget command.
The insert mark represents the position of the insertion cursor, and the insertion cursor will automatically be drawn at this point whenever the text widget has the input focus. π
πΈ THE MODIFIED FLAG πΈ
The text widget can keep track of changes to the content of the widget by means of the modified flag. Inserting or deleting text will set this flag. The flag can also be queried, set and cleared programatically. And whenever the flag changes state, a <<Modified>> virtual event is generated. See the edit modified widget command for more details. β¨
π WIDGET METHODS π
The Text method creates a widget object. This object supports the configure and cget methods described in Tk::options, which can be used to enquire and modify the options described above. The widget also inherits all the methods provided by the generic Tk::Widget class.
The following additional methods are available for text widgets. In addition, the extended text widget methods as documented in "Mastering Perl/Tk" are included in this pod (with permission from the publisher, O'Reilly and Associates Inc.). π«Ά
$text->adjustSelectβ Moves the end point of the selection and anchor point to the mouse pointer location. π±οΈ$text->bbox(index)β bestie, this one's giving where is that character at π It hands you back a list of four things describing the screen area of the character at index: the first two are the x and y coords of the upper-left corner of the area that character takes up, and the last two are the width and height of that area. If the character is only partially visible on screen, the return value only reflects the visible part (no cap). And if the character isn't visible at all? Empty list. That's it. That's the whole vibe. π«Ά$text->clipboardColumnCopyβ does a rectangular copy of whatever text is currently selected, with basic compensation for tab characters. Very demure, very mindful β¨$text->clipboardColumnCutβ same energy as above but it's a rectangular cut of the currently selected text, also with basic compensation for tab characters. π$text->clipboardColumnPasteβ rectangular paste of the text sitting in the clipboard. The upper-left corner is specified by the current position of the insert mark, with basic compensation for tab characters. π$text->compare(index1, op, index2)β compares index1 and index2 using the relational operator op, returning1if the relationship checks out and0if it doesn't. op has to be one of<,<=,==,>=,>, or!=. If op is==then you get1when both indices refer to the same character; if op is<then you get1when index1 refers to an earlier character in the text than index2, and so on. Iconic little comparator, honestly. β$text->Contents(?args?)β query or change the entire contents of the text widget. No arguments? You get the whole entire contents back, no filter, no crumbs. Any arguments given? The entire contents get deleted and replaced by the argument list. Main character energy, fr fr. π$text->debug(?boolean?)β if boolean is specified it has to be one of the true or false values thatTcl_GetBooleanaccepts. True value β internal consistency checks get turned on in the B-tree code associated with text widgets. False value β the debugging checks get turned off. Either way the command returns an empty string. If boolean isn't specified, the command returnsonoroffto tell you whether debugging is on.
Heads up bestie β there is a single debugging switch shared by all text widgets: turning debugging on or off in any widget turns it on or off for all widgets. And for widgets with large amounts of text, those consistency checks may cause a noticeable slow-down. π
$text->delete(index1, ?index2?)β deletes a range of characters. If both index1 and index2 are specified, it deletes all characters starting with the one at index1 and stopping just before index2 β meaning the character at index2 is not deleted. If index2 doesn't specify a position later in the text than index1, then no characters are deleted. If index2 isn't specified, just the single character at index1 gets deleted.
Not allowable: deleting characters in a way that would leave the text without a newline as the last character. Don't do it. The command returns an empty string.
If more indices are given, multiple ranges of text will be deleted. All indices are first checked for validity before any deletions are made. They're sorted and the text is removed from the last range to the first range so deleted text doesn't cause undesired index shifting side-effects. If multiple ranges with the same start index are given, then the longest range is used. If overlapping ranges are given, they get merged into spans that don't cause deletion of text outside the given ranges due to text shifted during deletion. So much detail, so much care π
$text->deleteSelectedβ deletes the currently selected text. Simple. Clean. Slay. β¨$text->deleteTextTaggedWith(tag)β deletes the text tagged with the tag parameter. π$text->deleteToEndofLineβ deletes from the insert mark location to the end of the line. π¦$text->dlineinfo(index)β returns a list with five elements describing the area occupied by the display line containing index. First two elements: x and y coords of the upper-left corner of the area occupied by the line. Third and fourth: the width and height of the area. Fifth: the position of the baseline for the line, measured down from the top of the area. All of this is measured in pixels, no cap. π
If the current wrap mode is none and the line extends beyond the boundaries of the window, the area returned reflects the entire area of the line, including the portions that are out of the window. If the line is shorter than the full width of the window, the area returned reflects just the portion of the line occupied by characters and embedded windows. And if the display line containing index isn't visible on screen? Empty list, bestie. π
$text->dump(?switches?, index1, ?index2?)β returns the contents of the text widget from index1 up to, but not including, index2 β and it brings the text plus info about marks, tags, and embedded windows. If index2 isn't specified, it defaults to one character past index1. The information comes back in this exact format:
key1 value1 index1 key2 value2 index2 ...
The possible key values are text, mark, tagon, tagoff, and $text. The corresponding value is the text, mark name, tag name, or window name. The index information is the index of the start of the text, the mark, the tag transition, or the window. One or more of the following switches (or abbreviations thereof) may be specified to control the dump:
-allβ return information about all elements: text, marks, tags, and windows. This is the default. π-command => callbackβ instead of returning the information as the result of the dump operation, invoke the callback on each element of the text widget within the range. The callback has three arguments appended to it before it is evaluated: the key, value, and index. π«Ά-markβ include information about marks in the dump results. β-tagβ include information about tag transitions in the dump results. Tag information is returned astagonandtagoffelements that indicate the begin and end of each range of each tag, respectively. π-textβ include information about text in the dump results. The value is the text up to the next element or the end of range indicated by index2. A text element does not span newlines. A multi-line block of text that contains no marks or tag transitions will still be dumped as a set of text segments that each end with a newline. The newline is part of the value. π-windowβ include information about embedded windows in the dump results. The value of a window is its Tk pathname, unless the window has not been created yet. (It must have a create script.) In this case an empty string is returned, and you must query the window by its index position to get more information. πͺ
$text->edit( option, ?arg, arg ...? );β this command controls the undo mechanism and the modified flag. The exact behavior depends on the option argument that follows theeditargument. The following forms of the command are currently supported:$text->editModified( ?boolean? );β if boolean isn't specified, returns the modified flag of the widget. The insert, delete,edit undoandedit redocommands, or the user, can set or clear the modified flag. If boolean is specified, sets the modified flag of the widget to boolean. π$text->editRedo;β (Not implemented, use TextUndo.) When the-undooption is true, reapplies the last undone edits provided no other edits were done since then. Generates an error when the redo stack is empty. Does nothing when the-undooption is false. π$text->editReset;β (Not implemented, use TextUndo.) Clears the undo and redo stacks. π§Ή$text->editSeparator;β (Not implemented, use TextUndo.) Inserts a separator (boundary) on the undo stack. Does nothing when the-undooption is false. βοΈ$text->editUndo;β (Not implemented, use TextUndo.) Undoes the last edit action when the-undooption is true. An edit action is defined as all the insert and delete commands that are recorded on the undo stack in between two separators. Generates an error when the undo stack is empty. Does nothing when the-undooption is false. π
$text->FindAll(mode, case, pattern)β removes any current selections and then performs a global text search. All matches get tagged with theseltag. π―
mode can be -exact or -regexp. See the search command for more information.
case can be -nocase or -case. See the search command for more information.
pattern is an exact string to match if mode is -exact, or a regular expression if the match mode is -regexp. π
$text->FindAndReplaceAll(mode, case, find, replace)β same as theFindAllmethod, however it additionally substitutes the matched text with the characters in replace. β¨$text->FindAndReplacePopUpβ creates a find-and-replace popup window if one doesn't already exist. If there's currently selected text, then the'find'field will be'pre-filled'with the selection. πͺ$text->FindNext(direction, mode, case, pattern)β removes any current selections and then performs a forward or reverse text search. All matches get tagged with theseltag. direction can be-forwardsor-backwards. mode, case and pattern are as for theFindAllmethod. π$text->FindPopUpβ creates a find popup, if one doesn't yet exist. If there's currently selected text, then the'find'field will be'pre-filled'with the selection. π«§$text->FindSelectionNextβ gets the currently selected text and removes all selections. It then finds the next exact, case-sensitive string that matches in a forward direction and selects the text and makes the new selection visible. Obsessed with the precision honestly. π$text->FindSelectionPreviousπ β grabs whatever text is currently selected and then yeets every single selection. After that it hunts for the next exact, case-sensitive string match, but going in reverse, then selects that text and scrolls it into view so the new selection is visible. Bestie said "find me the one before", and it delivers.$text->get(index1, ?index2?)π«Ά β hands you back a range of characters. You get everything starting atindex1and ending just beforeindex2β meaning the character sitting atindex2is not included, periodt. Leaveindex2off and you just get the single character atindex1. If there's nothing in that range (sayindex1is past the end of the file, orindex2is less than or equal toindex1) you get an empty string back. If the range has embedded windows in it, no info about them shows up in the returned string. And here's the slay part: pass multiple index pairs and you get multiple ranges returned in a list. Invalid ranges don't get represented as empty strings in that list β they just don't show up. Ranges come back in the same order you passed them toget. π$text->getSelectedπΈ β returns the text that's currently selected. That's it, that's the whole vibe.$text->GetTextTaggedWith(tag)π β returns the text that's tagged with thetagparameter. iykyk.$text->GotoLineNumber(line_number)π¦ β sets the insert mark toline_numberand makes sure that line is actually visible. No more "where am I" energy.$text->GotoLineNumberPopUp(line_number)β¨ β pops up a little popup, pre-filled with selected numeric text (if there is any), or with the line number fromGotoLineNumber(if there is any). Cute lil helper, fr fr.$text->image(option, ?arg, arg, ...?)$text->imageOption(?arg, arg, ...?)πΌοΈ β this one is all about manipulating embedded images. What it actually does depends on theoptionargument that comes after theimageprefix. Here are the forms it supports right now:
$text->image(option, ?arg, arg, ...?)
$text->imageOption(?arg, arg, ...?)
$text->imageCget(index, option)β returns the value of a configuration option for an embedded image.indextells it which embedded image you mean, andoptionnames the particular configuration option you want β and that option must be one of the ones listed in "EMBEDDED IMAGES".$text->imageConfigure(index, ?option, value, ...?)β query or modify the config options of an embedded image. Nooptiongiven? You get a list describing all the available options for the embedded image atindex(peepTk::optionsfor how that list is formatted). Give anoptionwith novalueand you get a list describing just that one named option β and that list will be identical to the matching sublist from the no-option case. Give one or moreoption-valuepairs and it modifies those option(s) to the given value(s); in that case it returns an empty string. Check "EMBEDDED IMAGES" for which options are supported. π§$text->imageCreate(index, ?option, value, ...?)β creates a brand new image annotation that shows up in the text at the position given byindex. You can throw in any number ofoption-valuepairs to configure the annotation. It returns a unique identifier you can use as an index to refer back to this image. Again, "EMBEDDED IMAGES" has the supported options and a description of that identifier it hands back. π$text->imageNamesβ returns a list whose elements are the names of every image instance currently embedded in$text. Headcount time.
$text->index(index)π β returns the position matchingindexin the formline.char, wherelineis the line number andcharis the character number. Andindexitself can be any of the forms described up in "INDICES".$text->insert(index, chars, ?tagList, chars, tagList, ...?)βοΈ β inserts all of thecharsarguments right before the character atindex. Ifindexpoints at the end of the text (aka the character after the last newline), the new text actually goes in just before that last newline instead. Now, the tagging rules, listen up:- One
charsargument and notagList? The new text receives any tags present on both the character before and the character after the insertion point. If a tag is on only one of those two characters, it does not get applied to the new text. Balance, bestie. tagListgiven? It's a list of tag names, and the new characters get all the tags in that list and no others β doesn't matter what tags are floating around the insertion point.- Multiple
chars-tagListpairs? Same effect as if you'd issued a separateinsertwidget command for each pair, in order. And the lasttagListargument can be left out entirely.
- One
$text->Insert(string)π¨ β ok do NOT confuse this with the lowercaseinsertmethod, they are different girlies. This one insertsstringat the point of the insertion cursor. And if there's a selection in the text that covers the point of the insertion cursor, it deletes the selection first before inserting. Clean slate energy.$text->InsertKeypress(character)β¨οΈ β insertscharacterat the insert mark. If you're in overstrike mode, it first deletes the character at the insert mark. (Firsts deletes, as the ancestors decreed. π)$text->InsertSelectionπ β inserts the current selection at the insert mark.$text->insertTabπ β inserts a tab (\t) character at the insert mark. Tiny but mighty.$text->mark(option, ?arg, arg, ...?)π β used to manipulate marks. What it does exactly depends on theoptionargument followingmark. Currently supported forms:$text->markGravity(markName, ?direction?)β nodirectiongiven? Returnsleftorright, telling you which of its adjacent charactersmarkNameis attached to. Give adirectionand it must beleftorright; the gravity ofmarkNamegets set to that value. It's giving... alignment. π§$text->markNamesβ returns a list whose elements are the names of all the marks currently set.$text->markNext(index)β returns the name of the next mark at or afterindex. Ifindexis in numerical form, the search begins at that index. Ifindexis the name of a mark, the search begins immediately after that mark. And yeah, it can still return a mark at the same position if there are multiple marks at the same index. These semantics meanmark nextcan be used to step through all the marks in a text widget in the same order as the mark info returned by thedumpoperation. If a mark has been set to the specialendindex, it appears to be afterendwith respect to themark nextoperation. No marks afterindex? You get an empty string. β$text->markPrevious(index)β returns the name of the mark at or beforeindex. Ifindexis numerical, the search for the previous mark begins with the character just before that index. Ifindexis a mark name, the search begins immediately before that mark. Still can return a mark at the same position if multiple marks share the same index. Somark previoussteps through all the marks in a text widget in the reverse order of the mark info from thedumpoperation. Empty string if there's nothing beforeindex. π$text->markSet(markName, index)β sets the mark namedmarkNameto a position just before the character atindex. IfmarkNamealready exists, it gets moved from its old position; if it doesn't exist, a new mark is created. Returns an empty string. β¨$text->markUnset(markName?, markName, markName, ...?)β removes the mark corresponding to each of themarkNamearguments. The removed marks won't be usable in indices anymore and won't be returned by future calls to$text->markNames. Returns an empty string. Gone, reduced to atoms. π
$text->markExists(markname)π β returns true ifmarknameexists, false otherwise.$text->menu(?menu?)π½οΈ β give it a menu reference as an argument and the text widget's menu gets adjusted to use this new menu. Passundefas the menu argument and it disables the current text widget menu. Omit themenuargument altogether and you get the current text widget menu reference back. Choose your own adventure.$text->openLineπ β inserts a newline (\n) at the insert mark. Simple as.$text->OverstrikeMode(?boolean?)ποΈ β omitbooleanand it returns the overstrike mode; pass one and it sets the overstrike mode toboolean.Truemeans overstrike mode is enabled.$text->PostPopupMenu(x,y)π±οΈ β creates a popup menu at the specified(x,y)pixel coordinates. The default menu has File, Edit, Search and View menu items which cascade to sub-menus for further commands. And there's an implicit<Button-3>binding to this method that posts the menu right over the cursor. Iconic. π$text->ResetAnchorβ β sets the selection anchor to whichever end is farthest from theindexargument. It's giving "pick the other one".$text->scan(option, args)or$text->scanoption(args)π β this is how scanning on texts gets implemented. Two forms, depending onoption:
$text->scan(option, args) or
$text->scanoption(args)
$text->scanMark(x, y)β recordsx,yand the current view in the text window, so a laterscanDragtomethod can use them. Typically this one gets associated with a mouse button press in the widget. Returns an empty string. π$text->scanDragto(x, y)β computes the difference between itsxandyarguments and thexandyarguments from the lastscanMarkmethod for the widget. Then it adjusts the view by 10 times the difference in coordinates. This one is typically associated with mouse motion events in the widget, to produce that effect of dragging the text at high speed through the window. Return value is an empty string. Wheeee π
β¨ $text->search(?switches,? pattern, index, ?stopIndex?) β¨
Okay so this is the search bar of your dreams, bestie. It hunts through the text in $text starting at index, looking for a run of characters that matches pattern. Find one? You get back the index of the first character in the match. Nope? Empty string, and we're sobbing. π
Drop one or more of these switches (or any abbreviation of them, we're not gatekeeping) to steer the search:
-forwardsβ the search proceeds forward through the text, finding the first matching range starting at or after the position given byindex. This is the default. π-backwardsβ walking backwards now π, finding the matching range closest toindexwhose first character is beforeindex.-exactβ exact matching only: the characters in the matching range have to be identical to those inpattern. Also the default. π-regexpβ treatpatternas a regular expression and match it against the text using the rules for regular expressions (peep theregexpcommand for the details).-nocaseβ ignore case differences between thepatternand the text. Not today, capitalization. π-count varNameβ the argument following-countgives the name of a variable; if a match is found, the number of characters in the matching range gets stored in that variable. π-hiddenβ find hidden text as well. By default only displayed text gets found.--β this switch has no effect except to terminate the list of switches: the next argument gets treated aspatterneven if it starts with-.
Now the fine print, and it matters:
The matching range has to be entirely within a single line of text. For regular expression matching, the newlines get removed from the ends of the lines before matching β so use the $ feature in regular expressions to match the end of a line. For exact matching, the newlines are retained. π«Ά
If stopIndex is specified, the search stops at that index: for forward searches, no match at or after stopIndex gets considered; for backward searches, no match earlier in the text than stopIndex gets considered. If stopIndex is omitted, the entire text gets searched β when the beginning or end of the text is reached, the search continues at the other end until the starting location is reached again; but if stopIndex is specified, no wrap-around happens. Periodt.
β¨ $text->see(index) β¨
Adjusts the view in the window so the character given by index is completely visible. If index is already visible, the command does nothing (king of minding its own business π§). If index is a short distance out of view, it nudges the view just enough to make index visible at the edge of the window. And if index is far out of view, then it centers index in the window. Main character energy, honestly.
β¨ $text->selectAll β¨
Selects all the text in the widget. Everything. All of it. Slay. π
β¨ $text->selectLine β¨
Selects the line with the insert mark.
β¨ $text->selectWord β¨
Selects the word with the insert mark.
β¨ $text->SetCursor(position) β¨
Moves the insert mark to position. Easy peasy. π
β¨ $text->tag(option, ?arg, arg, ...?) β¨
This is the tag-manipulation command. What it actually does depends on the option argument that follows the tag argument. Here are the forms currently supported, bestie:
$text->tagAdd(tagName, index1, ?index2, index1, index2, ...?)
Associate the tag tagName with all of the characters starting with index1 and ending just before index2 (the character at index2 isn't tagged, no cap). A single command can hold any number of index1-index2 pairs. If the last index2 is omitted, then the single character at index1 gets tagged. And if there are no characters in the specified range (like index1 is past the end of the file, or index2 is less than or equal to index1), then the command has no effect. π¦
$text->tagBind(tagName, ?sequence?, ?script?)
This one associates script with the tag given by tagName. Whenever the event sequence given by sequence occurs for a character that's been tagged with tagName, the script gets invoked. It's like the bind command except it operates on characters in a text rather than entire widgets. See the Tk::bind documentation for the complete details on the syntax of sequence and the substitutions performed on script before invoking it.
If all arguments are specified, then a new binding is created, replacing any existing binding for the same sequence and tagName β unless the first character of script is +, in which case script augments an existing binding rather than replacing it. In this case the return value is an empty string. If script is omitted, the command returns the script associated with tagName and sequence (an error occurs if there's no such binding). And if both script and sequence are omitted, the command returns a list of all the sequences for which bindings have been defined for tagName.
The only events for which bindings may be specified are those related to the mouse and keyboard (like Enter, Leave, ButtonPress, Motion, and KeyPress) or virtual events. Event bindings for a text widget use the current mark described under "MARKS" above. An Enter event triggers for a tag when the tag first becomes present on the current character, and a Leave event triggers for a tag when it ceases to be present on the current character. Enter and Leave events can happen either because the current mark moved or because the character at that position changed.
Heads up bestie, these events are different thanEnterandLeaveevents for windows. Not the same thing, don't mix them up. π
Mouse and keyboard events get directed to the current character. And if a virtual event is used in a binding, that binding can trigger only if the virtual event is defined by an underlying mouse-related or keyboard-related event.
It's possible for the current character to have multiple tags, and for each of them to have a binding for a particular event sequence. When this happens, one binding gets invoked for each tag, in order from lowest-priority to highest priority. If there are multiple matching bindings for a single tag, then the most specific binding gets chosen (see the documentation for the bind command for details). continue and break commands within binding scripts get processed in the same way as for bindings created with the bind command.
And if bindings are created for the widget as a whole using the bind command, then those bindings will supplement the tag bindings. The tag bindings get invoked first, followed by bindings for the window as a whole. Order matters, iykyk. π₯
$text->tagCget(tagName, option)
Returns the current value of the option named option associated with the tag given by tagName. option may have any of the values accepted by the tag configure method.
$text->tagConfigure(tagName, ?option?, ?value?, ?option, value, ...?)
Similar to the configure method, except it modifies options associated with the tag given by tagName instead of modifying options for the overall text widget. If no option is specified, the command returns a list describing all of the available options for tagName (see Tk::options for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (and this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given option(s) to have the given value(s) in tagName β and in this case the command returns an empty string. Peep "TAGS" above for the details on the options available for tags. π
$text->tagDelete(tagName, ?tagName, ...?)
Deletes all tag information for each of the tagName arguments. The command removes the tags from all characters in the file and also deletes any other information associated with the tags, like bindings and display information. Returns an empty string. It's giving total wipeout. π
$text->tagLower(tagName?, belowThis?)
Changes the priority of tag tagName so that it's just lower in priority than the tag whose name is belowThis. If belowThis is omitted, then tagName's priority gets changed to make it the lowest priority of all tags.
$text->tagNames(?index?)
Returns a list whose elements are the names of all the tags that are active at the character position given by index. If index is omitted, then the return value will describe all of the tags that exist for the text β and that includes all tags that have been named in a $text->tag widget command but haven't been deleted by a $text->tagDelete method, even if no characters are currently marked with the tag. The list gets sorted in order from lowest priority to highest priority. πΈ
$text->tagNextrange(tagName, index1, ?index2?)
Searches the text for a range of characters tagged with tagName where the first character of the range is no earlier than the character at index1 and no later than the character just before index2 (a range starting at index2 will not be considered). If several matching ranges exist, the first one gets chosen. The command's return value is a list containing two elements: the index of the first character of the range, and the index of the character just after the last one in the range. If no matching range is found, the return value is an empty string. And if index2 isn't given, it defaults to the end of the text. β
$text->tagPrevrange(tagName, index1, ?index2?)β okay so this one goes hunting for a range of characters wearingtagName, where the range's very first character sits before the character atindex1and no earlier than the character atindex2. And yes, a range that starts right atindex2totally counts, it's invited to the party. π If more than one range matches, the one closest toindex1gets picked. π
What comes back to you? A list with two elements, bestie: the index of the range's first character, and the index of the character just after the last one in the range. β¨ If literally no matching range shows up, you get an empty string back β it's giving "nobody's home". π
Oh, and if you don't hand over index2? It defaults to the beginning of the text. π
$text->tagRaise(tagName, ?aboveThis?)β this bumps the priority oftagNameup so it's just higher in priority than the tag namedaboveThis. Ranked higher, periodt. If you leaveaboveThisoff entirely,tagNamegets yeeted all the way to the top β highest priority of all the tags. π$text->tagRanges(tagName)β returns a whole list describing every range of text that's been tagged withtagName. The first two elements = the first tagged range in the text, the next two = the second range, and so on, forever and ever, amen. π¦
Inside each pair, element one is the index of the first character of the range, and element two is the index of the character just after the last one in that range. If there are no characters tagged with tagName, you get an empty string. π
$text->tagRemove(tagName, index1, ?index2, index1, index2, ...?)β stripstagNameoff every character starting atindex1and ending just beforeindex2(so the character sitting atindex2is untouched, it did nothing wrong). π ββοΈ
And the glow-up: one single command can hold any number of index1-index2 pairs. If the last index2 is omitted then the single character at index1 is tagged. If there are no characters in the range you specified (like, index1 is past the end of the file, or index2 is less than or equal to index1), the command just does nothing β no drama. π This command returns an empty string.
$text->ToggleInsertModeβ flips the current overstrike mode. Switch up, switch down. π$text->unselectAllβ unselects all the text in the widget. Clean slate, no selection, we move. β¨$text->WhatLineNumberPopupβ pops up a little popup showing the current line number of the insert mark. Cute, informative, on brand. π$text->widget(option?, arg, arg, ...?)$text->widgetOption(?arg, arg, ...?)β this one is the embedded-window wrangler. πͺ The behavior depends on whichever option argument follows the window argument, and the forms it supports right now are:$text->windowCget(index, option)β hands you back the value of a configuration option for an embedded window.indexsays which embedded window we're talking about, andoptionnames the specific configuration option β which has to be one of the ones listed up in "EMBEDDED WINDOWS". No freelancing. π$text->windowConfigure(index?, option, value, ...?)β query or modify the config options of an embedded window. If you pass nooptionat all, it returns a list describing all the available options for the embedded window atindex(peepTk::optionsfor the tea on the format of that list β). If you giveoptionwith novalue, it returns a list describing that one named option β and that list will be identical to the matching sublist from the no-option case. If you pass one or moreoption-valuepairs, it modifies those option(s) to hold those value(s), and in that case the command returns an empty string. Options supported? Check "EMBEDDED WINDOWS" above, bestie. π«Ά$text->windowCreate(index?, option, value, ...?)β creates a brand new window annotation that'll show up in the text at the position given byindex. You can throw in any number ofoption-valuepairs to configure that annotation. Again: see "EMBEDDED WINDOWS" above for what's supported. Returns an empty string. π$text->windowNamesβ returns a list whose elements are the names of every window currently embedded in$text. Roll call! π
$text->xview(option, args)β the horizontal-motion queen. π Use it to query and change the horizontal position of the text inside the widget's window. It takes any of these forms:$text->xviewβ returns a list with two elements. Each one is a real fraction between 0 and 1, and together they describe the chunk of the document's horizontal span that's visible in the window. Like, if the first element is.2and the second is.6, then 20% of the text is off-screen to the left, the middle 40% is visible in the window, and 40% is off-screen to the right. π
Important vibe check: those fractions refer only to the lines actually visible in the window. If every line in the window is super short and fully visible, you'll get 0 and 1 back β even if there are other lines in the text that are way wider than the window. These are the same values passed to scrollbars via the -xscrollcommand option. β¨
$text->xviewMoveto(fraction)β adjusts the view so thatfractionof the text's horizontal span is off-screen to the left.fractionis a fraction between 0 and 1.$text->xviewScroll(number, what)β shifts the view left or right according tonumberandwhat.numbermust be an integer.whatmust be eitherunitsorpages, or an abbreviation of one of those. Ifwhatisunits, the view moves left or right bynumberaverage-width characters on the display; if it'spages, the view moves bynumberscreenfuls. Negativenumber= characters farther to the left become visible; positivenumber= characters farther to the right become visible. βοΈ
$text->yview(?args?)β the vertical counterpart, and honestly iconic. π Use it to query and change the vertical position of the text in the widget's window. Forms:$text->yviewβ returns a list with two elements, both real fractions between 0 and 1. The first element gives the position of the first character in the top line of the window, relative to the text as a whole (so 0.5 means it's halfway through the text, for example). The second element gives the position of the character just after the last one in the bottom line of the window, relative to the text as a whole. Same values that get passed to scrollbars via the-yscrollcommandoption. π$text->yviewMoveto(fraction)β adjusts the view so the character given byfractionappears on the top line of the window.fractionis a fraction between 0 and 1;0means the first character in the text,0.33means the character one-third of the way through the text, and so on. π§$text->yviewScroll(number, what)β adjusts the view up or down according tonumberandwhat.numbermust be an integer.whatmust be eitherunitsorpages. Ifwhatisunits, the view adjusts up or down bynumberlines on the display; if it'spages, the view adjusts bynumberscreenfuls. Negativenumber= earlier positions in the text become visible; positivenumber= later positions become visible. βοΈ$text->yview(?-pickplace,? index)β changes the view in$text's window so thatindexbecomes visible. If the-pickplaceoption isn't specified,indexshows up at the top of the window. If-pickplaceis specified, the widget gets to choose whereindexlands:- If
indexis already visible somewhere in the window, the command does absolutely nothing. π - If
indexis only a few lines off-screen above the window, it gets positioned at the top of the window. - If
indexis only a few lines off-screen below the window, it gets positioned at the bottom of the window. - Otherwise,
indexgets centered in the window. π―
- If
π¨ Heads up bestie: the-pickplaceoption has been obsoleted by theseewidget command (see handles both x- and y-motion to make a location visible, whereas-pickplaceonly handles motion in y). It's giving deprecated. π
$text->yview(number)β this makes the first character on the line after the one given bynumbervisible at the top of the window.numbermust be an integer. This command used to be used for scrolling, but now it's obsolete. π΅β¨
β¨ BINDINGS β¨
Tk just auto-magically makes class bindings for texts so they do stuff by default, no cap. And bestie, when I say "word" down below, I mean a contiguous little group of letters, digits, or _ characters β OR literally any single character that isn't one of those. That's the whole definition. π
[1]β Clicking mouse button 1 puts the insertion cursor right before the character chillin' underneath the mouse cursor, sets the input focus to this widget, and clears any selection in the widget. Then if you drag with mouse button 1, it strokes out a selection between the insertion cursor and the character under the mouse. π[2]β Double-clicking with mouse button 1 selects the word under the mouse and parks the insertion cursor at the beginning of the word. Keep dragging after a double click and you'll stroke out a selection made of whole words. slay.[3]β Triple-clicking with mouse button 1 selects the line under the mouse and drops the insertion cursor at the beginning of the line. Drag after a triple click and the selection is made of whole lines. iconic behavior honestly.[4]β You can adjust the ends of the selection by dragging with mouse button 1 while Shift is held down β this adjusts the end of the selection that was nearest to the mouse cursor when button 1 got pressed. If the button was double-clicked before dragging, the selection gets adjusted in units of whole words; if it was triple-clicked, then it adjusts in units of whole lines. π[5]β Clicking mouse button 1 with the Control key down repositions the insertion cursor without touching the selection. so chill of it.[6]β Type any normal printing characters and they get inserted right at the point of the insertion cursor. periodt.[7]β Drag with mouse button 2 and you can adjust the view in the widget. If mouse button 2 is clicked without moving the mouse, the selection gets copied into the text at the position of the mouse cursor. TheInsertkey also inserts the selection, but at the position of the insertion cursor instead. β¨[8]β If the mouse gets dragged out of the widget while button 1 is pressed, the entry will automatically scroll to make more text visible (assuming there is more text off-screen on the side where the mouse left the window). π¦[9]β TheLeftandRightkeys move the insertion cursor one character left or right; they also clear any selection in the text. IfLeftorRightis typed with the Shift key down, the insertion cursor moves and the selection extends to include the new character.Control-LeftandControl-Rightmove the insertion cursor by words, andControl-Shift-LeftandControl-Shift-Rightmove by words and extend the selection.Control-bandControl-fdo the exact same thing asLeftandRight.Meta-bandMeta-fdo the exact same thing asControl-LeftandControl-Right. iykyk π[10]β TheUpandDownkeys move the insertion cursor one line up or down and clear any selection in the text. IfUporRightis typed with the Shift key down, then the insertion cursor moves and the selection is extended to include the new character.Control-UpandControl-Downmove the insertion cursor by paragraphs (groups of lines separated by blank lines), andControl-Shift-UpandControl-Shift-Downmove the insertion cursor by paragraphs and extend the selection too.Control-pandControl-ndo the exact same thing asUpandDown. πΈ[11]β TheNextandPriorkeys move the insertion cursor forward or backwards by one screenful and clear any selection in the text. If the Shift key is held down whileNextorPrioris typed, the selection extends to include the new character.Control-vmoves the view down one screenful without moving the insertion cursor or adjusting the selection. π[12]βControl-NextandControl-Priorscroll the view right or left by one page without moving the insertion cursor or affecting the selection. no thoughts, just scrolling.[13]βHomeandControl-amove the insertion cursor to the beginning of its line and clear any selection in the widget.Shift-Homemoves the insertion cursor to the beginning of the line and extends the selection to that point.[14]βEndandControl-emove the insertion cursor to the end of the line and clear any selection in the widget.Shift-Endmoves the cursor to the end of the line and extends the selection to that point.[15]βControl-HomeandMeta-<move the insertion cursor to the beginning of the text and clear any selection in the widget.Control-Shift-Homemoves the insertion cursor to the beginning of the text and also extends the selection to that point.[16]βControl-EndandMeta->move the insertion cursor to the end of the text and clear any selection in the widget.Control-Shift-Endmoves the cursor to the end of the text and extends the selection to that point.[17]β TheSelectkey andControl-Spaceset the selection anchor to the position of the insertion cursor. They do not affect the current selection.Shift-SelectandControl-Shift-Spaceadjust the selection to the current position of the insertion cursor, selecting from the anchor to the insertion cursor if there wasn't any selection previously. π[18]βControl-/selects the entire contents of the widget. main character move fr.[19]βControl-\clears any selection in the widget. bye bestie π[20]β TheF16key (labelledCopyon many Sun workstations) orMeta-wcopies the selection in the widget to the clipboard, if there is a selection. π«Ά[21]β TheF20key (labelledCuton many Sun workstations) orControl-wcopies the selection in the widget to the clipboard and deletes the selection. If there's no selection in the widget, then these keys have no effect at all.[22]β TheF18key (labelledPasteon many Sun workstations) orControl-yinserts the contents of the clipboard at the position of the insertion cursor. β¨[23]β TheDeletekey deletes the selection, if there is one in the widget. If there's no selection, it deletes the character to the right of the insertion cursor. π[24]βBackspaceandControl-hdelete the selection, if there is one in the widget. If there's no selection, they delete the character to the left of the insertion cursor.[25]βControl-ddeletes the character to the right of the insertion cursor.[26]βMeta-ddeletes the word to the right of the insertion cursor. girlboss deletion.[27]βControl-kdeletes from the insertion cursor to the end of its line; if the insertion cursor is already at the end of a line, thenControl-kdeletes the newline character instead. π[28]βControl-oopens a new line by inserting a newline character in front of the insertion cursor without moving the insertion cursor.[29]βMeta-backspaceandMeta-Deletedelete the word to the left of the insertion cursor.[30]βControl-xdeletes whatever is selected in the text widget.[31]βControl-treverses the order of the two characters to the right of the insertion cursor. chaos, but make it typo-fixing.[32]βControl-z(andControl-underscoreon UNIX whentk_strictMotifis true) undoes the last edit action if the-undooption is true. Does nothing otherwise.[33]βControl-Z(orControl-yon Windows) reapplies the last undone edit action if the-undooption is true. Does nothing otherwise.
If the widget is disabled using the -state option, then its view can still be adjusted and text can still be selected β but no insertion cursor will be displayed and no text modifications will take place. π
The behavior of texts can be changed by defining new bindings for individual widgets or by redefining the class bindings.
π§ TIED INTERFACE π§
The Perl/Tk Text widget also has built-in TIEHANDLE methods for print and printf statements. Which means β bestie, listen β you can print to file handles tied to a Text widget, and the tied methods automatically insert the print statement's arguments into the Text widget. it's giving effortless. π
For example:
#!/usr/local/bin/perl -w
use POSIX 'acos';
use Tk;
use strict;
my $mw = MainWindow->new;
my $text = $mw->Text(qw/-width 40 -height 10/)->pack;
tie *STDOUT, ref $text, $text;
print "Hello Text World!\n";
printf "pi ~= %1.5f", acos(-1.0);
MainLoop;
To tie a scrolled Text widget, use the Subwidget method to get to the "real" widget:
my $text = $mw->Scrolled('Text')->pack;
tie *STDOUT, 'Tk::Text', $text->Subwidget('scrolled');
π PERFORMANCE ISSUES π
Text widgets should run efficiently under a variety of conditions. The text widget uses about 2-3 bytes of main memory for each byte of text, so texts containing a megabyte or more should be practical on most workstations. Text is represented internally with a modified B-tree structure that makes operations relatively efficient even with large texts. Tags are included in the B-tree structure in a way that allows tags to span large ranges or have many disjoint smaller ranges without loss of efficiency. Marks are also implemented in a way that allows large numbers of marks. In most cases it is fine to have large numbers of unique tags, or a tag that has many distinct ranges. β¨
One performance problem can arise if you have hundreds or thousands of different tags that all have the following characteristics: the first and last ranges of each tag are near the beginning and end of the text, respectively, or a single tag range covers most of the text widget. The cost of adding and deleting tags like this is proportional to the number of other tags with the same properties. In contrast, there is no problem with having thousands of distinct tags if their overall ranges are localized and spread uniformly throughout the text. πΈ
Very long text lines can be expensive, especially if they have many marks and tags within them. π
The display line with the insert cursor is redrawn each time the cursor blinks, which causes a steady stream of graphics traffic. Set the -insertofftime option to 0 to avoid this.
π¦ SEE ALSO π¦
Tk::ROText Tk::TextUndo
π KEYWORDS π
text, widget
and that's the whole page, bestie!! π«Ά this one came from the perl v5.40.1 release, dated 2025-04-13, living its best life as Text(3pm). go forth and text-widget responsibly. mwah π
π¦ where this page comes from
- debian trixie: perl-tk 1:804.036+dfsg1-5
- ubuntu questing: perl-tk 1:804.036+dfsg1-5
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms