in reply to Extracting information from a Text widget
#!/usr/bin/perl use warnings; use strict; use Tk; use Tk::LabEntry; my $mw = MainWindow->new( -bg => 'black' ); $mw->geometry('100x30+100+15'); my $file_name = shift || $0; my $file; open (FH,"< $file_name"); read( FH, $file, -s FH ); close FH; my $search_string = ''; my $kind = 'exact'; my $stringframe = $mw->Frame; my $ss = $stringframe->LabEntry( -label => 'Search string:', -width => 40, -labelPack => [qw/-side left -anchor w/], -textvariable => \$search_string )->pack(qw/-side left/); my $ss_button = $stringframe->Button( -text => 'Highlight' ); $ss_button->pack(qw/-side left -pady 5 -padx 10/); my $text = $mw->Scrolled(qw/Text -setgrid true -scrollbars e/); $text->tagConfigure( 'search', -foreground => 'red',-background => ' +white' ); $text->insert('0.0', $file); $text->mark(qw/set insert 0.0/); my $subframe = $mw->Frame; my $exact = $subframe->Radiobutton( -text => 'Exact match', -variable => \$kind, -value => 'exact' ); my $regexp = $subframe->Radiobutton( -text => 'Regular expression', -variable => \$kind, -value => 'regexp' ); $exact->pack( qw/-side left/, -fill => 'x' ); $regexp->pack( qw/-side right/, -fill => 'x' ); $stringframe->pack(qw/-side top -fill x/); $subframe->pack(qw/-side top -fill x/); $text->pack(qw/-expand yes -fill both/); my $command = sub { &search_text($text,\$search_string,'search',$kind) + }; $ss_button->configure( -command => $command ); $ss->bind( '<Return>' => $command ); MainLoop; ###################################################################### +#3 sub search_text { # The utility procedure below searches for all instances of a give +n # string in a text widget and applies a given tag to each instance + found. # Arguments: # # w - The window in which to search. Must be a text widget. # string - Reference to the string to search for. The search i +s done # using exact matching only; no special characters. # tag - Tag to apply to each instance of a matching string. my ( $w, $string, $tag, $kind ) = @_; #print "@_\n"; return unless ref($string) && length($$string); $w->tagRemove( $tag, qw/0.0 end/ ); my ( $current, $length ) = ( '1.0', 0 ); while (1) { $current = $w->search( -count => \$length, "-$kind", $$string, $current +, 'end' ); last if not $current; warn "Posn=$current count=$length\n", $w->tagAdd( $tag, $current, "$current + $length char" ); $current = $w->index("$current + $length char"); } } # end search_text
|
|---|