Version 0 of Searching in a text widget

Updated 2006-11-28 11:59:58 by suchenwi

Richard Suchenwirth 2006-11-28 - Here is example code for searching substrings in a text widget. When an instance is found, it is highlighted with the hilite tag. At end of the text content, the search wraps around. The global variable status reports the position of a found substring.

 proc find {w what} {
    foreach {from to} [$w tag ranges hilite] {
        $w tag remove hilite $from $to
    }
    set pos [$w search -count n -- $what insert+2c]
    if {$pos eq ""} {
        set ::status "not found: $what"
    } else {
        set ::status "found at $pos: $what"
        $w mark set insert $pos
        $w see $pos
        $w tag add hilite $pos $pos+${n}c
    }
 }

# Demo with an entry for the search term:

 pack [entry .e -textvariable Find] -fill x
 bind .e <Return> {find .t $Find}

 pack [text .t -wrap word]
 .t tag configure hilite -background orange

 pack [label .l -textvariable status] -anchor w

Category Example