<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">#!perl -w
#
# T-Pad - A Perl/Tk GUI based Perl-script editor with syntax highlighting
#
# Usage: see Perl documentation in pod format (perldoc)
#
use strict;
use Tk;

{   ###########################################################################
    package TextHighlight;
    ###########################################################################

    use vars qw($VERSION %FUNC %FLOW %OPER);
    $VERSION = '4.04';

    my @FUNC = qw/AUTOLOAD BEGIN CHECK CORE DESTROY END INIT abs accept alarm atan2 bind binmode bless caller chdir chmod chomp chop chown chr chroot close closedir cmp connect cos crypt dbmclose dbmopen defined delete die dump each endgrent endhostent endnetent endprotoent endpwent endservent eof eval exec exists exit exp fcntl fileno flock fork format formline getc getgrent getgrgid getgrnam gethostbyaddr gethostbyname gethostent getlogin getnetbyaddr getnetbyname getnetent getpeername getpgrp getppid getpriority getprotobyname getprotobynumber getprotoent getpwent getpwnam getpwuid getservbyname getservbyport getservent getsockname getsockopt glob gmtime grep hex index int ioctl join keys kill lc lcfirst length link listen localtime log lock lstat map mkdir msgctl msgget msgrcv msgsnd new oct open opendir ord pack pipe pop pos print printf prototype push quotemeta rand read readdir readline readlink readpipe recv ref rename reset reverse rewinddir rindex rmdir scalar seek seekdir select semctl semget semop send setgrent sethostent setnetent setpgrp setpriority setprotoent setpwent setservent setsockopt shift shmctl shmget shmread shmwrite shutdown sin sleep socket socketpair sort splice split sprintf sqrt srand stat study substr symlink syscall sysopen sysread sysseek system syswrite tell telldir tie tied time times truncate uc ucfirst umask undef unlink unpack unshift untie utime values vec wait waitpid wantarray warn write/;
    my @FLOW = qw/continue do else elsif for foreach goto if last local my next our no package redo require return sub unless until use while __DATA__ __END__ __FILE__ __LINE__ __PACKAGE__/;
    my @OPER = qw/and eq ge gt le lt m ne not or q qq qr qw qx s tr y xor x/;

    # Build lookup tables
    @FUNC{@FUNC} = (1) x @FUNC; undef @FUNC;
    @FLOW{@FLOW} = (1) x @FLOW; undef @FLOW;
    @OPER{@OPER} = (1) x @OPER; undef @OPER;

    use Tk qw(Ev);
    use AutoLoader;

    # Set @TextHighlight::ISA = ('Tk::TextUndo')
    use base qw(Tk::TextUndo);

    Construct Tk::Widget 'TextHighlight';

    sub ClassInit {
        my ($class, $mw) = @_;
        $class-&gt;SUPER::ClassInit($mw);
        $mw-&gt;bind($class, '&lt;Control-o&gt;', \&amp;main::openDialog);
        $mw-&gt;bind($class, '&lt;Control-n&gt;', [\&amp;main::addPage, 'Untitled']);
        $mw-&gt;bind($class, '&lt;Control-s&gt;', [\&amp;main::saveDialog, 's']);
        $mw-&gt;bind($class, '&lt;Control-r&gt;', \&amp;main::runScript);
        $mw-&gt;bind($class, '&lt;F1&gt;', \&amp;main::commandHelp);
        return $class;
    }

    sub InitObject {
        my ($w, $args) = @_;
        $w-&gt;SUPER::InitObject($args);
        $w-&gt;tagConfigure('FUNC', -foreground =&gt; '#FF0000');
        $w-&gt;tagConfigure('FLOW', -foreground =&gt; '#0000FF');
        $w-&gt;tagConfigure('OPER', -foreground =&gt; '#FF8200');
        $w-&gt;tagConfigure('STRG', -foreground =&gt; '#848284');
        $w-&gt;tagConfigure('CMNT', -foreground =&gt; '#008284');
        $w-&gt;tagConfigure('MTCH', -background =&gt; '#FFFF00');
        # Default: font family courier, size 10
        $w-&gt;configure(-font =&gt; $w-&gt;fontCreate(qw/-family courier -size 10/));
        $w-&gt;{CALLBACK} = undef;
        $w-&gt;{CHANGES} = 0;
        $w-&gt;{LINE} = 0;
    }

    sub Button1 {
        my $w = shift;
        $w-&gt;SUPER::Button1(@_);
        &amp;{$w-&gt;{CALLBACK}} if ( defined $w-&gt;{CALLBACK} );
    }

    sub see {
        my $w = shift;
        $w-&gt;SUPER::see(@_);
        &amp;{$w-&gt;{CALLBACK}} if ( defined $w-&gt;{CALLBACK} );
    }

    # Set/Get the amount of changes
    sub numberChangesExt {
        my ($w, $changes) = @_;
        if ( @_ &gt; 1 ) {
            $w-&gt;{CHANGES} = $changes;
        }
        return $w-&gt;{CHANGES};
    }

    # Register callback function and call it immediately
    sub positionChangedCallback {
        my ($w, $callback) = @_;
        &amp;{$w-&gt;{CALLBACK} = $callback};
    }

    sub insert {
        my $w = shift;
        my ($s_line) = split(/\./, $w-&gt;index('insert'));
        $w-&gt;SUPER::insert(@_);
        my ($e_line) = split(/\./, $w-&gt;index('insert'));
        highlight($w, $s_line, $e_line);
        &amp;{$w-&gt;{CALLBACK}} if ( defined $w-&gt;{CALLBACK} );
    }

    # Insert text without highlight
    sub insertWHL {
        my $w = shift;
        $w-&gt;SUPER::insert(@_);
    }

    # Background highlight
    sub backgroundHL {
        my ($w, $l) = @_;
        my ($end) = split(/\./, $w-&gt;index('end'));
        $w-&gt;{LINE} = $end unless ( $w-&gt;{LINE} );
        # 'cut/delete' correction if needed
        if ( $w-&gt;{LINE} != $end ) {
            $l -= ($w-&gt;{LINE} - $end);
            if ( $l &lt; 0 ) { $l = 0 }
            $w-&gt;{LINE} = $end;
        }
        highlight($w, $l, $l+50 &gt; $end ? $end-1 : $l+50);
        if ( $l+50 &lt; $end ) {
            $w-&gt;after(50, [\&amp;backgroundHL, $w, $l+50+1]);
        }
        else { $w-&gt;{LINE} = 0 }
    }

    sub insertTab {
        my ($w) = @_;
        my $pos = (split(/\./, $w-&gt;index('insert')))[1];
        # Insert spaces instead of tabs
        $w-&gt;Insert(' ' x (4-($pos%4)));
        $w-&gt;focus;
        &amp;{$w-&gt;{CALLBACK}} if ( defined $w-&gt;{CALLBACK} );
        $w-&gt;break;
    }

    sub delete {
        my $w = shift;
        $w-&gt;SUPER::delete(@_);
        my ($line) = split(/\./, $w-&gt;index('insert'));
        highlight($w, $line, $line);
    }

    sub InsertKeypress {
        my $w = shift;
        $w-&gt;SUPER::InsertKeypress(@_);

        # Easy things easy...
        if ( $_[0] =~ /[([{&lt;"']/ ) {
            $w-&gt;SUPER::InsertKeypress(')') if ( $_[0] eq '(' );
            $w-&gt;SUPER::InsertKeypress(']') if ( $_[0] eq '[' );
            $w-&gt;SUPER::InsertKeypress('}') if ( $_[0] eq '{' );
            $w-&gt;SUPER::InsertKeypress('&gt;') if ( $_[0] eq '&lt;' );
            $w-&gt;SUPER::InsertKeypress('"') if ( $_[0] eq '"' );
            $w-&gt;SUPER::InsertKeypress("'") if ( $_[0] eq "'" );
            $w-&gt;SetCursor('insert-1c');
        }

        my ($line) = split(/\./, $w-&gt;index('insert'));
        highlight($w, $line, $line);
        &amp;{$w-&gt;{CALLBACK}} if ( defined $w-&gt;{CALLBACK} );
    }

    sub highlight {
        my ($w, $s_line, $e_line) = @_;

        # Remove tags from current area
        foreach ( qw/FUNC FLOW OPER STRG CMNT/ ) {
            $w-&gt;tagRemove($_, $s_line.'.0', $e_line.'.end');
        }

        foreach my $ln($s_line .. $e_line) {
            my $line = $w-&gt;get($ln.'.0', $ln.'.end');
            # Highlight: strings
            while ( $line =~ /("             # Start at double quote
                                  (?:        # For grouping only
                                      \\.|   # Backslash with any character
                                      [^"\\] # Must not be able to find
                                  )*         # Zero or more sets of those
                              "|
                              (?&lt;!\$)        # Prevent $' match
                              '              # Start at single quote
                                  (?:        # For grouping only
                                      \\.|   # Backslash with any character
                                      [^'\\] # Must not be able to find
                                  )*         # Zero or more sets of those
                              ')/gx ) {
                $w-&gt;tagAdd('STRG', $ln.'.'.(pos($line)-length($1)),
                           $ln.'.'.pos($line));
            }
            # Highlight: comments
            while ( $line =~ /(?&lt;!       # Lookbehind for neither
                                  [\$\\] # $ nor \
                              )\#        # Start of the comment
                             /gx ) {
                next if ( $w-&gt;tagNames($ln.'.'.(pos($line)-1)) &amp;&amp;
                          $w-&gt;tagNames($ln.'.'.(pos($line)-1)) eq 'STRG' );
                $w-&gt;tagAdd('CMNT', $ln.'.'.(pos($line)-1), $ln.'.end');
                $line = $w-&gt;get($ln.'.0', $ln.'.'.(pos($line)-1));
                last;
            }
            # Highlight: functions, flow control words and operators,
            # do not highlight hashes, arrays or scalars
            while ( $line =~ /(?&lt;!              # Lookbehind for neither
                                  [\%\@\$])     # %, @, nor $
                                      \b        # Match a word boundary
                                          (\w+) # Match a "word"
                                      \b        # Match a word boundary
                             /gx ) {
                if ( $OPER{$1} ) {
                    $w-&gt;tagAdd('OPER', $ln.'.'.(pos($line)-length($1)),
                               $ln.'.'.pos($line));
                }
                elsif ( $FLOW{$1} ) {
                    $w-&gt;tagAdd('FLOW', $ln.'.'.(pos($line)-length($1)),
                               $ln.'.'.pos($line));
                }
                elsif ( $FUNC{$1} || $1 =~ /^(\d+)$/ ) {
                    $w-&gt;tagAdd('FUNC', $ln.'.'.(pos($line)-length($1)),
                               $ln.'.'.pos($line));
                }
            }
        }
    }
} # END - package TextHighlight

###############################################################################
package main;
###############################################################################

use File::Find;
use File::Basename;
use Tk::HList;
use Tk::Dialog;
use Tk::ROText;
use Tk::Balloon;
use Tk::DropSite;
use Tk::NoteBook;
use Tk::Adjuster;

# Seed the random number generator
BEGIN { srand() if $] &lt; 5.004 }

# List of supported file patterns
my @filetypes = (
    ['Perl Scripts',     '.pl',  'TEXT'],
    ['Perl Modules',     '.pm',  'TEXT'],
    ['Perl CGI Scripts', '.cgi', 'TEXT']);

# Create main window and return window handle
my $mw = MainWindow-&gt;new(-title =&gt; 'T-Pad');

# Manage window manager protocol
$mw-&gt;protocol('WM_DELETE_WINDOW' =&gt; \&amp;exitCommand);

# Add menubar
$mw-&gt;configure(-menu =&gt;
my $menubar = $mw-&gt;Menu(-tearoff =&gt; $Tk::platform eq 'unix'));

# Add 'File' entry to the menu
my $file = $menubar-&gt;cascade(qw/-label File -underline 0 -menuitems/ =&gt;
    [
        [command =&gt; '~New',         -accelerator =&gt; 'Ctrl+N',
                                    -command =&gt; [\&amp;addPage, 'Untitled']],
        [command =&gt; '~Open...',     -accelerator =&gt; 'Ctrl+O',
                                    -command =&gt; \&amp;openDialog],
        [command =&gt; '~Close',       -command =&gt; \&amp;closeCommand,
                                    -state   =&gt; 'disabled'],
        '',
        [command =&gt; '~Save',        -accelerator =&gt; 'Ctrl+S',
                                    -command =&gt; [\&amp;saveDialog, 's']],
        [command =&gt; 'Save ~As...',  -command =&gt; [\&amp;saveDialog, 'a']],
        '',
        [command =&gt; 'E~xit',        -command =&gt; \&amp;exitCommand],
    ], -tearoff =&gt; $Tk::platform eq 'unix');

# Add 'Edit' entry to the menu
my $edit = $menubar-&gt;cascade(qw/-label Edit -underline 0 -menuitems/ =&gt;
    [
        [command =&gt; '~Undo',        -accelerator =&gt; 'Ctrl+Z',
                                    -command =&gt; [\&amp;menuCommands, 'eu']],
        [command =&gt; '~Redo',        -accelerator =&gt; 'Ctrl+Y',
                                    -command =&gt; [\&amp;menuCommands, 'er']],
        '',
        [command =&gt; 'Cu~t',         -accelerator =&gt; 'Ctrl+X',
                                    -command =&gt; [\&amp;menuCommands, 'et']],
        [command =&gt; 'C~opy',        -accelerator =&gt; 'Ctrl+C',
                                    -command =&gt; [\&amp;menuCommands, 'eo']],
        [command =&gt; 'P~aste',       -accelerator =&gt; 'Ctrl+V',
                                    -command =&gt; [\&amp;menuCommands, 'ea']],
        '',
        [command =&gt; 'Select A~ll',  -command =&gt; [\&amp;menuCommands, 'el']],
        [command =&gt; 'Unsele~ct All',-command =&gt; [\&amp;menuCommands, 'ec']],
    ], -tearoff =&gt; $Tk::platform eq 'unix');

# Add 'Misc' entry to the menu
my $misc = $menubar-&gt;cascade(qw/-label Misc -underline 0 -menuitems/ =&gt;
    [
        [command =&gt; '~Properties...',       -command =&gt; \&amp;propertiesDialog],
        [Checkbutton =&gt; 'CR~LF Conversion', -variable =&gt; \my $crlf],
        [command =&gt; "Script's PO~D...",     -command =&gt; \&amp;perlDoc],
        [command =&gt; '~Run',                 -accelerator =&gt; 'Ctrl+R',
                                            -command =&gt; \&amp;runScript],
    ], -tearoff =&gt; $Tk::platform eq 'unix');

# Add 'Help' entry to the menu
my $help = $menubar-&gt;cascade(qw/-label Help -underline 0 -menuitems/ =&gt;
    [
        [command =&gt; '~Commands...', -accelerator =&gt; 'F1',
                                    -command =&gt; \&amp;commandHelp],
        [command =&gt; '~About...',    -command =&gt; \&amp;aboutDialog],
    ], -tearoff =&gt; $Tk::platform eq 'unix');

# Add NoteBook metaphor
my $nb = $mw-&gt;NoteBook();

# Accept drops from an external application
$nb-&gt;DropSite(-dropcommand =&gt; \&amp;handleDND,
              -droptypes   =&gt; ($^O eq 'MSWin32' or ($^O eq 'cygwin' and
                              $Tk::platform eq 'MSWin32')) ? ['Win32'] :
                              [qw/KDE XDND Sun/]);

my ($tw, $cmdHelp, %pageName);
# Accept ASCII text file or file which does not exist
foreach ( @ARGV ) {
    if ( (-e $_ &amp;&amp; -T _) || !-e _ ) {
        addPage($_);
    }
}

# Add default page if there are no pages in notebook metaphor
unless ( keys %pageName ) {
    addPage('Untitled');
}

# Show filename over the 'pageName' using balloons
my ($balloon, $msg) = $mw-&gt;Balloon(-state =&gt; 'balloon',
                                   -balloonposition =&gt; 'mouse');
$balloon-&gt;attach($nb, -balloonmsg =&gt; \$msg,
                -motioncommand =&gt; sub {
                    my ($nb, $x, $y) = @_;
                    # Adjust screen to widget coordinates
                    $x -= $nb-&gt;rootx;
                    $y -= $nb-&gt;rooty;
                    my $name = $nb-&gt;identify($x, $y);
                    if ( defined $name ) {
                        $msg = 'File name: '.$pageName{$name}-&gt;FileName();
                        0; # Don't cancel the balloon
                    } else { 1 } # Cancel the balloon
                });

# Add status bar to the bottom of the screen
my $fr = $mw-&gt;Frame-&gt;pack(qw/-side bottom -fill x/);
$fr-&gt;Label(-textvariable =&gt; \my $st)-&gt;pack(qw/-side left/);
$fr-&gt;Label(-textvariable =&gt; \my $clk)-&gt;pack(qw/-side right/);
updateClock();

# Create Text widget where the user can type commands
my $cw = $mw-&gt;Scrolled(qw/Text
                          -spacing2 1 -spacing3 1
                          -scrollbars e -height 3
                          -background white
                          -relief ridge/)-&gt;pack(qw/-side bottom
                                                   -fill x -padx 1/);

# Miscellaneous configurations to the command window
$cw-&gt;configure(-font =&gt; $tw-&gt;cget(-font));
$cw-&gt;menu(undef);
$cw-&gt;tagConfigure('FILE', -foreground =&gt; '#0000FF');
$cw-&gt;tagBind('FILE', '&lt;Any-Enter&gt;' =&gt; sub {
    shift-&gt;configure(qw/-cursor hand2/);
});
$cw-&gt;tagBind('FILE', '&lt;Any-Leave&gt;' =&gt; sub {
    shift-&gt;configure(qw/-cursor xterm/);
});
$cw-&gt;tagBind('FILE', '&lt;ButtonRelease-1&gt;' =&gt; sub {
    my $text = shift;
    my ($l) = split(/\./, $text-&gt;index('current'));
    my $txt = $text-&gt;get($l.'.0', "$l.end");
    if ( $txt =~ /^(.*?)\((\d+)\)/ ) {
        addPage($1);
        gotoLine($2);
    }
});
mouseWheel($cw);

my $prev_cmd;
$mw-&gt;Adjuster-&gt;packAfter($cw, -side =&gt; 'bottom');
$nb-&gt;pack(qw/-side top -expand 1 -fill both/);

# Arrange for X events to invoke callbacks
$cw-&gt;bind('&lt;Return&gt;', \&amp;executeCommand);
$cw-&gt;bind('&lt;Escape&gt;', sub { $tw-&gt;focus });
$cw-&gt;bind('&lt;F1&gt;', \&amp;commandHelp);

# Start the GUI and eventloop
MainLoop;

# Create modal 'About' dialog
sub aboutDialog {
    my $popup = $mw-&gt;Dialog(
        -popover        =&gt; $mw,
        -title          =&gt; 'About T-Pad',
        -bitmap         =&gt; 'Tk',
        -default_button =&gt; 'OK',
        -buttons        =&gt; ['OK'],
        -text           =&gt; "T-Pad\nVersion 4.04 - 05-Aug-2003\n\n".
                           "Copyright (C) Tomi Parviainen\n".
                           "http://www.cpan.org/scripts/\n\n".
                           "Perl Version $]\n".
                           "Tk Version $Tk::VERSION",
        );
    $popup-&gt;resizable('no', 'no');
    $popup-&gt;Show();
}

# Add page to notebook metaphor
sub addPage {
    shift if UNIVERSAL::isa($_[0], 'TextHighlight');
    my $pageName = shift;

    # If the page exist, raise the old page and return
    foreach ( keys %pageName ) {
        if ( ($pageName{$_})-&gt;FileName() eq $pageName &amp;&amp;
              $pageName ne 'Untitled' ) {
            return $nb-&gt;raise($_);
        }
    }

    # Add new page with 'random' name to the notebook
    my $name = rand();
    my $page = $nb-&gt;add($name,
                        -label =&gt; basename($pageName),
                        -raisecmd =&gt; \&amp;pageChanged);

    # Create a widget with attached scrollbar(s)
    $tw = $page-&gt;Scrolled(qw/TextHighlight
                            -spacing2 1 -spacing3 1
                            -scrollbars ose -background white
                            -borderwidth 2 -width 80 -height 25
                            -relief sunken/)-&gt;pack(qw/-expand 1 -fill both/);

    $tw-&gt;FileName($pageName);
    $pageName{$name} = $tw;
    $tw-&gt;bind('&lt;FocusIn&gt;', sub {
        $tw-&gt;tagRemove('MTCH', '0.0', 'end');
    });

    # Change popup menu to contain 'Edit' menu entry
    $tw-&gt;menu($edit-&gt;menu);
    mouseWheel($tw);

    if ( keys %pageName &gt; 1 ) {
        # Enable 'File-&gt;Close' menu entry
        $file-&gt;cget(-menu)-&gt;entryconfigure(2 + ($Tk::platform eq 'unix'),
                                           -state =&gt; 'normal');
    }

    $nb-&gt;raise($name);

    # Write data to the new page. File 'Untitled' can
    # be used as a template for new script files!
    writeData($pageName);

    # Register callback function
    $tw-&gt;positionChangedCallback(\&amp;updateStatus);
}

# Remove page and disable 'Close' menu item when needed
sub closeCommand {
    if ( confirmCh() ) {
        delete $pageName{$nb-&gt;raised()};
        $nb-&gt;delete($nb-&gt;raised());
    }
    if ( keys %pageName == 1 ) {
        # Disable 'File-&gt;Close' menu entry
        $file-&gt;cget(-menu)-&gt;entryconfigure(2 + ($Tk::platform eq 'unix'),
                                           -state =&gt; 'disabled');
    }
}

# Confirm the changes user has made before proceeding
sub confirmCh {
    if ( $nb-&gt;pagecget($nb-&gt;raised(), -label) =~ /\*/ ) {
        my $answer = $tw-&gt;Dialog(
                        -popover =&gt; $mw, -text =&gt; 'Save changes to '.
                         basename($tw-&gt;FileName()), -bitmap =&gt; 'warning',
                        -title =&gt; 'T-Pad', -default_button =&gt; 'Yes',
                        -buttons =&gt; [qw/Yes No Cancel/])-&gt;Show;
        if ( $answer eq 'Yes' ) {
            saveDialog('s');
            return 0 if ( $nb-&gt;pagecget($nb-&gt;raised(), -label) =~ /\*/ ||
                          $tw-&gt;FileName() eq 'Untitled' );
        }
        elsif ( $answer eq 'Cancel' ) {
            return 0;
        }
    }
    return 1;
}

# Create Hierarchical List widget, which shows supported commands
# and a short description of each command
sub commandHelp {
    if ( defined $cmdHelp ) {
        $cmdHelp-&gt;focus;
        return;
    }
    $cmdHelp = $mw-&gt;Toplevel(-title =&gt; 'T-Pad Commands [Ctrl+Tab, ESC]');
    my $hl = $cmdHelp-&gt;Scrolled('HList', -header =&gt; 1, -columns =&gt; 2,
                                -scrollbars =&gt; 'osoe', -width =&gt; 70,
                                -height =&gt; 31)
                                -&gt;pack(qw/-expand 1 -fill both/);

    my %commands = (
        'a' =&gt; 'About T-Pad',
        'c' =&gt; 'Close an opened script file',
        'doc x' =&gt; 'Look up Perl documentation for built in function \'x\'',
        'eval x' =&gt; 'Evaluate expression \'x\'',
        'f x' =&gt; 'Find the specified pattern \'x\'',
        'fb x' =&gt; 'Find the specified pattern \'x\', proceed backward',
        'fc x' =&gt; 'Find the specified pattern \'x\', use match case',
        'ff o t x' =&gt; 'Find the specified pattern \'x\' from folder o, file'.
                      ' types t,'."\n".'Example: ff c:\perl\bin *.pl;*.pm Tk',
        'fr x' =&gt; 'Find the specified pattern \'x\', use regular expression',
        'g x' =&gt; 'Goto a specified line \'x\'',
        'n' =&gt; 'Create a new script file',
        'o' =&gt; 'Open an existing script file',
        'p' =&gt; 'File properties',
        'r [a]' =&gt; 'Run the active script, [with arguments a]',
        's' =&gt; 'Save the active script using the same filename',
        'sa' =&gt; 'Save the active script as a new file',
        'wc' =&gt; 'Change the wrap mode to \'char\'',
        'wn' =&gt; 'Change the wrap mode to \'none\'',
        'ww' =&gt; 'Change the wrap mode to \'word\'',
        'x' =&gt; 'Exit');

    my $position = 0;
    $hl-&gt;header('create', 0, -text =&gt; 'Command');
    $hl-&gt;header('create', 1, -text =&gt; 'Description');
    foreach ( sort keys %commands ) {
        $hl-&gt;add($position, -state =&gt; 'disabled');
        $hl-&gt;itemCreate($position,   0, -text =&gt; $_);
        $hl-&gt;itemCreate($position++, 1, -text =&gt; $commands{$_});
    }
    $cmdHelp-&gt;focus;
    $cmdHelp-&gt;protocol('WM_DELETE_WINDOW' =&gt; sub {
        $cmdHelp-&gt;withdraw;
        undef $cmdHelp;
    });
}

# Execute command given by the user
sub executeCommand {
    my ($ln, $col) = split(/\./, $cw-&gt;index('insert'));
    if ( ($_ = $cw-&gt;get(--$ln.'.0', "$ln.end")) eq '' ) {
        # Repeat previous command
        $_ = $prev_cmd ? $prev_cmd : '';
        $cw-&gt;delete($ln--.'.0', 'end');
        $cw-&gt;insert('end', "\n$_\n");
    }
    else { $prev_cmd = $_ }

    if ( /^a$/ )    { aboutDialog() }
    elsif ( /^c$/ ) {
        if ( keys %pageName &gt; 1 ) {
            closeCommand();
        }
    }
    elsif ( /^doc\s+(.+)$/ ) {
        my $doc = `perldoc -t -f $1`;
        unless ( $doc ) {
            $doc = "No documentation for perl function `$1' found";
        }
        $doc =~ s/\n+$//;
        $cw-&gt;insert('end', "$doc\n");
    }
    elsif ( /^eval\s+(.+)$/ ) {
        eval {
            my $r = eval $1;
            $cw-&gt;insert('end', ($r ? $r : 'undef')."\n");
        };
    }
    elsif ( /^f(.*?)\s+(.+)$/ ) {
        my ($cm, $da, $no, %sw) = ($1, $2, 0);
        if ( $cm =~ /c/ ) { $sw{-exact} = 1 }
        else              { $sw{-nocase} = 1 }
        if ( $cm =~ /r/ ) { $sw{-regexp} = 1 }
        if ( $cm =~ /b/ ) { $sw{-backwards} = 1 }
        if ( $tw-&gt;tagRanges('MTCH') ) {
            if ( $sw{-backwards} ) {
                $tw-&gt;markSet('insert', ($tw-&gt;tagRanges('MTCH'))[0]);
            }
            else {
                $tw-&gt;markSet('insert', ($tw-&gt;tagRanges('MTCH'))[1]);
            }
            $tw-&gt;tagRemove('MTCH', '0.0', 'end');
        }
        if ( $cm =~ /f/ ) {
            findFiles($da);
            return;
        }
        my $match = $tw-&gt;search(keys %sw, -count =&gt; \$no, '--',
                                $da, $tw-&gt;index('insert'));
        if ( $match ) {
            $tw-&gt;tagAdd('MTCH', $match, "$match + $no char");
            $tw-&gt;markSet('insert', "$match  + $no char");
            $tw-&gt;see('insert');
            $tw-&gt;markUnset('insert');
        }
        else {
            # Didn't match, ring the bell
            $mw-&gt;bell;
        }
    }
    elsif ( /^g\s*(\d+)$/ )  { gotoLine($1) }
    elsif ( /^n$/ )          { addPage('Untitled') }
    elsif ( /^o$/ )          { openDialog() }
    elsif ( /^p$/ )          { propertiesDialog() }
    elsif ( /^r\s*(.*)$/ )   { runScript($1) }
    elsif ( /^s$/ )          { saveDialog('s') }
    elsif ( /^sa$/ )         { saveDialog('a') }
    elsif ( /^w([ncw])$/ )   {
        my $wm = $1; # Wrap mode
        if ( $wm eq 'n' )    { $wm = 'none' }
        elsif ( $wm eq 'c' ) { $wm = 'char' }
        else                 { $wm = 'word' }
        $tw-&gt;configure(-wrap =&gt; $wm);
    }
    elsif ( /^x$/ )          { exitCommand() }
    else                     { $cw-&gt;insert('end', "-&gt;[ERROR]\n") }

    $cw-&gt;SetCursor('end-1char');
}

# Close all pages and quit T-Pad
sub exitCommand {
    while ( (my $pages = keys %pageName) &gt; 0 ) {
        closeCommand();
        # Check if the user has pressed 'Cancel' button
        last if ( keys %pageName == $pages );
    }
    exit if ( keys %pageName == 0 );
}

# Find '$data' pattern from files, scan recursively
sub findFiles {
    my ($path, $ext, $data) = split(/ /, shift);
    return unless ( defined $data );
    my ($dir, %files);

    find(sub {
        return if ( !-f || !-T || !defined $mw-&gt;focusCurrent ||
                    UNIVERSAL::isa($mw-&gt;focusCurrent, 'TextHighlight') );
        my $filename = $_;
        if ( !$dir || $dir ne $File::Find::dir ) {
            $cw-&gt;update;
            $dir = $File::Find::dir;
            undef %files;
            foreach ( split(/;/, $ext) ) {
                foreach ( glob("$_") ) {
                    $files{$_} = 1;
                }
            }
        }

        if ( $files{$filename} &amp;&amp; open(FILE, $filename) ) {
            while ( my $line = &lt;FILE&gt; ) {
                next unless ( $line =~ /\Q$data\E/i );
                chomp($line);
                $cw-&gt;insert('end', "$File::Find::name", 'FILE');
                $cw-&gt;insert('end', "($.):$line\n");
                $cw-&gt;SetCursor('end-1char');
                $cw-&gt;update;
            }
            close(FILE) or warn "$!";
        }
    }, $path);
}

# Goto line, which has been passed as a parameter
sub gotoLine {
    my $line = shift;
    $tw-&gt;markSet('insert', "$line.0");
    $tw-&gt;see('insert');
    $tw-&gt;markUnset('insert');
    $tw-&gt;tagRemove('MTCH', '0.0', 'end');
    $tw-&gt;tagAdd('MTCH', "$line.0", "$line.0 lineend + 1c");
}

# Get the filename of the drop and add new page to the notebook metaphor
sub handleDND {
    my ($sel, $filename) = shift;

    # In case of an error, do the SelectionGet in an eval block
    eval {
        if ( $^O eq 'MSWin32' ) {
            $filename = $tw-&gt;SelectionGet(-selection =&gt; $sel, 'STRING');
        }
        else {
            $filename = $tw-&gt;SelectionGet(-selection =&gt; $sel, 'FILE_NAME');
        }
    };
    if ( defined $filename &amp;&amp; -T $filename ) {
        addPage($filename);
    }
}

# Handle different menu accelerator commands, which cannot be handled
# directly in menu entry (because of the tight bind of $tw)
sub menuCommands {
    my $cmd = shift;
    if    ( $cmd eq 'eu' ) { $tw-&gt;undo }
    elsif ( $cmd eq 'er' ) { $tw-&gt;redo }
    elsif ( $cmd eq 'et' ) { $tw-&gt;clipboardCut }
    elsif ( $cmd eq 'eo' ) { $tw-&gt;clipboardCopy }
    elsif ( $cmd eq 'ea' ) { $tw-&gt;clipboardPaste }
    elsif ( $cmd eq 'el' ) { $tw-&gt;selectAll }
    elsif ( $cmd eq 'ec' ) { $tw-&gt;unselectAll }
}

# Support for mouse wheel
sub mouseWheel {
    my $w = shift;

    # Windows support
    $w-&gt;bind('&lt;MouseWheel&gt;', [sub {
        $_[0]-&gt;yviewScroll(-($_[1]/120)*3, 'units');
    }, Tk::Ev('D')]);

    # UNIX support
    if ( $Tk::platform eq 'unix' ) {
        $w-&gt;bind('&lt;4&gt;', sub {
            $_[0]-&gt;yviewScroll(-3, 'units') unless $Tk::strictMotif;
        });
        $w-&gt;bind('&lt;5&gt;', sub {
            $_[0]-&gt;yviewScroll( 3, 'units') unless $Tk::strictMotif;
        });
    }
}

# Pop up a dialog box for the user to select a file to open
sub openDialog {
    my $filename = $mw-&gt;getOpenFile(-filetypes =&gt; \@filetypes);
    if ( defined $filename and $filename ne '' ) {
        addPage($filename)
    }
}

# Notebook page has changed, change the focus to the new page
# and initialise status bar to reflect page data
sub pageChanged {
    $tw = $pageName{$nb-&gt;raised()};
    $tw-&gt;focus if ( !defined $mw-&gt;focusCurrent ||
                    UNIVERSAL::isa($mw-&gt;focusCurrent, 'MainWindow') ||
                    UNIVERSAL::isa($mw-&gt;focusCurrent, 'TextHighlight') );

    # Disable/Enable 'Misc-&gt;Properties' menu entry
    if ( -e $tw-&gt;FileName() ) {
        $misc-&gt;cget(-menu)-&gt;entryconfigure(0 + ($Tk::platform eq 'unix'),
                                           -state =&gt; 'active');
    }
    else {
        $misc-&gt;cget(-menu)-&gt;entryconfigure(0 + ($Tk::platform eq 'unix'),
                                           -state =&gt; 'disabled');
    }
    updateStatus();
}

# Look up Perl documentation in pod format
sub perlDoc {
    my $fileName = $tw-&gt;FileName();
    my $doc = `perldoc -t \"$fileName\"`;
    unless ( $doc ) {
        $doc = "No documentation found for \"$fileName\".\n";
    }
    my $tl = $mw-&gt;Toplevel(-title =&gt; "Perl Documentation in POD Format [".
                          (basename($tw-&gt;FileName()))."]");
    my $pod = $tl-&gt;Scrolled(qw/ROText -scrollbars oe -width 80 -height 25
                               -spacing2 1 -spacing3 1/);
    mouseWheel($pod);
    $pod-&gt;menu(undef);
    $pod-&gt;configure(-font =&gt; $tw-&gt;cget(-font));
    $pod-&gt;pack(qw/-expand 1 -fill both/);
    $pod-&gt;insert('1.0', $doc);
    $pod-&gt;focus;
}

# Create modal 'Properties' dialog
sub propertiesDialog {
    # Return if the file does not exist
    return unless ( -e $tw-&gt;FileName() );
    my $popup = $mw-&gt;Dialog(
        -popover =&gt; $mw,
        -title   =&gt; 'Source File Properties',
        -bitmap  =&gt; 'info',
        -default_button =&gt; 'OK',
        -buttons =&gt; ['OK'],
        -text    =&gt; "Name:\t".basename($tw-&gt;FileName()).
                "\nSize:\t".(stat($tw-&gt;FileName()))[7]." Bytes\n".
                "Saved:\t".localtime((stat($tw-&gt;FileName()))[9])."\n".
                "Mode:\t".sprintf("%04o", 07777&amp;(stat($tw-&gt;FileName()))[2])
        );
    $popup-&gt;resizable('no', 'no');
    $popup-&gt;Show();
}

# Run the script (currently with blocking the caller)
sub runScript {
    shift if UNIVERSAL::isa($_[0], 'TextHighlight');
    my $params = $_[0] ? $_[0] : '';

    if ( confirmCh() &amp;&amp; -e $tw-&gt;FileName() ) {
        system("$^X \"".$tw-&gt;FileName()."\" $params");
    }
}

# Pop up a dialog box for the user to select a file to save
sub saveDialog {
    my $filename;
    shift if UNIVERSAL::isa($_[0], 'TextHighlight');

    if ( $_[0] eq 's' &amp;&amp; $tw-&gt;FileName() ne 'Untitled' ) {
        $filename = $tw-&gt;FileName();
    }
    else {
        $filename = $mw-&gt;getSaveFile(-filetypes =&gt; \@filetypes,
                                     -initialfile =&gt; basename($tw-&gt;FileName()),
                                     -defaultextension =&gt; '.pl');
    }

    if ( defined $filename and $filename ne '' ) {
        if ( open(FILE, "&gt;$filename") ) {
            # Write file to disk (change cursor to reflect this operation)
            $mw-&gt;Busy(-recurse =&gt; 1);
            my ($e_line) = split(/\./, $tw-&gt;index('end - 1 char'));
            foreach ( 1 .. $e_line-1 ) {
                print FILE $tw-&gt;get($_.'.0', $_.'.0 + 1 lines');
            }
            print FILE $tw-&gt;get($e_line.'.0', 'end - 1 char');
            $mw-&gt;Unbusy;
            close(FILE) or print "$!";
            $tw-&gt;FileName($filename);
            $nb-&gt;pageconfigure($nb-&gt;raised(), -label =&gt; basename($filename));
            $tw-&gt;numberChangesExt($tw-&gt;numberChanges);
            # Ensure 'File-&gt;Properties' menu entry is active
            $misc-&gt;cget(-menu)-&gt;entryconfigure(0 + ($Tk::platform eq 'unix'),
                                               -state =&gt; 'active');
        }
        else {
            my $msg = "File may be ReadOnly, or open for write by ".
                      "another application! Use 'Save As' to save ".
                      "as a different name.";
            $mw-&gt;Dialog(-popover =&gt; $mw, -text =&gt; $msg,
                        -bitmap =&gt; 'warning',
                        -title =&gt; 'Cannot save file',
                        -buttons =&gt; ['OK'])-&gt;Show;
        }
    }
}

# Update clock (without seconds) every minute
sub updateClock {
    ($clk = scalar localtime) =~ s/(\d+:\d+):(\d+)\s/$1 /;
    $mw-&gt;after((60-$2)*1000, \&amp;updateClock);
}

# Update the statusbar
sub updateStatus {
    my ($cln, $ccol) = split(/\./, $tw-&gt;index('insert'));
    my ($lln) = split(/\./, $tw-&gt;index('end'));
    $st = "Line $cln (".($lln-1).'), Column '.($ccol+1);

    my $title = $nb-&gt;pagecget($nb-&gt;raised(), -label);
    # Check do we need to add/remove '*' from title
    if ( $tw-&gt;numberChanges != $tw-&gt;numberChangesExt() ) {
        if ( $title !~ /\*/ ) {
            $title .= '*';
            $nb-&gt;pageconfigure($nb-&gt;raised(), -label =&gt; $title);
        }
    }
    elsif ( $title =~ /\*/ ) {
        $title =~ s/\*//;
        $nb-&gt;pageconfigure($nb-&gt;raised(), -label =&gt; $title);
    }
}

# Write data to text widget via read buffer
sub writeData {
    my $filename = $tw-&gt;FileName();

    if ( -e $filename ) {
        open(FILE, $filename) or die "$!";
        my $read_buffer;
        while ( &lt;FILE&gt; ) {
            s/\x0D?\x0A/\n/ if ( $crlf );
            $read_buffer .= $_;
            if ( ($.%100) == 0 ) {
                $tw-&gt;insertWHL('end', $read_buffer);
                undef $read_buffer;
            }
        }
        if ( $read_buffer ) {
            $tw-&gt;insertWHL('end', $read_buffer);
        }
        close(FILE) or die "$!";
    }

    $tw-&gt;ResetUndo;
    # Set cursor to the first line of text widget
    $tw-&gt;insertWHL('0.0');
    $tw-&gt;backgroundHL(1);
}

__END__

=head1 NAME

T-Pad - A Perl/Tk GUI based Perl-script editor with syntax highlighting

=head1 SYNOPSIS

perl B&lt;t-pad.pl&gt; [I&lt;file(s)-to-edit&gt;]

=head1 DESCRIPTION

T-Pad is a Perl/Tk GUI based text editor with syntax highlight. T-Pad supports syntax highlight for *.pl, *.pm and *.cgi -files. It contains a command window to where a user can type commands to test for example a functionality of regular expression, evaluate Perl's predefined variables, look up documentation for built in functions etc.

=head1 README

A Perl/Tk GUI based Perl-script editor with syntax highlighting (*.pl, *.pm and *.cgi). T-Pad runs under Windows, Unix and Linux.

=head1 PREREQUISITES

This script requires the C&lt;Tk&gt; a graphical user interface toolkit module for Perl.

=head1 AUTHOR

Tomi Parviainen &lt;F&lt;tparviai@cpan.org&gt;&gt;

=head1 COPYRIGHT

Copyright (c) 2002-2003, Tomi Parviainen. All rights reserved.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

=pod SCRIPT CATEGORIES

Win32
Win32/Utilities

=cut
</pre></body></html>