proc TagAll {} {
global seltxt
set l1 [string length $seltxt]
scan [.ed index end] %d nl
set curpos [.ed index insert]
for {set i 1} {$i < $nl} {incr i} {
.ed mark set last $i.end
set lpos [.ed index last]
set curpos [.ed search -forwards -exact $seltxt $curpos $lpos]
if {$curpos != ""} {
.ed mark set insert $curpos
scan [.ed index "insert + $l1 chars"] %f pos
.ed tag add $seltxt $curpos $pos
.ed tag configure $seltxt -background Bisque3
.ed mark set insert "insert + $l1 chars"
set curpos $pos
} else {
set curpos $lpos
}
}
}
The Tk text widget specific command ".ed tag add" takes a string for the name of the tag and assigns that tag to all the characters (or phrase) between the two positions given to it as arguments after the tag name. All the tag names are registered in the name space and all occurances of the tagged text could be subsequently collectively referred to by their tag names.
In this procedure wherever a match for a given string is found, it is tagged. The string is used as the tag name (e.g., all occurences of "jack" is tagged and the tag name is "jack").
You can display tagged text differently by calling ".ed tag configure" as in this procedure where the tagged word is displayed with different background colour throughout: The final result when you execute this script should be:
You can also add bindings to tagged text by calling for instance
".ed tag bind{ .ed delete "insert + [string length $seltxt] chars" .ed insert insert "I have removed tagged text and inserted this" }
You should of course add a sensible course of action than the above ;-) the rest of the procedure is made up of Tcl/Tk commands already explained. Note that any word or a phrase could have more than one tag associated with it too.