in reply to how to open and highlight text
I did something similar not too long ago. Here's a little demo script showing one way to do it. It has configurable search parameters and highlight colors.
I see zentara has already posted an example. Oh well. Here's another :-) For demonstration purposes, it loads itself into the text widget.
use strict; use warnings; use Tk; my %widget; $widget{main} = MainWindow->new; $widget{text} = $widget{main}->Scrolled( 'Text', -scrollbars => 'se' ) ->pack( -expand => 1, -fill => 'both' ); $widget{hilitemode} = 'regex'; $widget{hilitecolor} = '#ABCDEF'; configure_tag(); $widget{frame} = $widget{main}->Frame()->pack( -side => 'bottom', -anchor => 's' ); $widget{frame}->Label( -text => 'Highlight Character(s) or Regex', ) ->pack( -side => 'top', -pady => 2, -padx => 2, -anchor => 'n' ); $widget{hilight_entry} = $widget{frame}->Entry( -width => 40, -background => 'white', -relief => 'sunken', )->pack( -padx => 3, -pady => 3, -anchor => 'n' ); $widget{subframe} = $widget{frame}->Frame()->pack( -side => 'bottom', -anchor => 's' ); $widget{subframe}->Radiobutton( -variable => \$widget{hilitemode}, -value => 'exact', -text => 'Exact', )->grid( -row => 0, -column => 1 ); $widget{subframe}->Radiobutton( -variable => \$widget{hilitemode}, -value => 'regex', -text => 'Regex', )->grid( -row => 0, -column => 2 ); $widget{subframe}->Button( -text => 'Highlight Color', -command => sub { my $color = $widget{main}->chooseColor( -initialcolor => $widget{hilitecolor}, -title => 'Choose Highlight Color' ); $widget{hilitecolor} = $color if $color; configure_tag(); } )->grid( -row => 0, -column => 3 ); seek( DATA, 0, 0 ); $widget{text}->insert( 'end', $_ ) for <DATA>; $widget{hilight_entry}->insert( 'end', '\$widget\{\w+\}' ); $widget{main}->repeat( 400, \&hilite ); MainLoop; sub hilite { my $highlight_term = $widget{hilight_entry}->get; $widget{text}->tagRemove( 'hilight', '1.0', 'end' ); return unless length $highlight_term; if ( $widget{hilitemode} eq 'exact' ) { $highlight_term = quotemeta($highlight_term); } else { return unless isvalid($highlight_term); } my $length; my $index = '1.0'; while ($index) { $index = $widget{text}->search( '-regexp', -count => \$length, '--', $highlight_term, $index, 'end' ); if ($index) { $widget{text} ->tagAdd( 'hilight', $index, $index . ' +' . $length . ' +c' ); $index = $widget{text}->index( $index . ' +' . $length . ' +c' ); } } } sub configure_tag { $widget{text} ->tagConfigure( 'hilight', -background => $widget{hilitecolor} ) +; } sub isvalid { my $term = shift; return eval { "" =~ m/$term/; 1 } || 0; } __DATA__
|
|---|