[perl #41698] [PATCH] v5.8.8 pod2html -- Add <div>..</div> around the outputted INDEX...
[p5sagit/p5-mst-13.2.git] / lib / Pod / Html.pm
1 package Pod::Html;
2 use strict;
3 require Exporter;
4
5 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);
6 $VERSION = 1.07;
7 @ISA = qw(Exporter);
8 @EXPORT = qw(pod2html htmlify);
9 @EXPORT_OK = qw(anchorify);
10
11 use Carp;
12 use Config;
13 use Cwd;
14 use File::Spec;
15 use File::Spec::Unix;
16 use Getopt::Long;
17
18 use locale;     # make \w work right in non-ASCII lands
19
20 =head1 NAME
21
22 Pod::Html - module to convert pod files to HTML
23
24 =head1 SYNOPSIS
25
26     use Pod::Html;
27     pod2html([options]);
28
29 =head1 DESCRIPTION
30
31 Converts files from pod format (see L<perlpod>) to HTML format.  It
32 can automatically generate indexes and cross-references, and it keeps
33 a cache of things it knows how to cross-reference.
34
35 =head1 FUNCTIONS
36
37 =head2 pod2html
38
39     pod2html("pod2html",
40              "--podpath=lib:ext:pod:vms",
41              "--podroot=/usr/src/perl",
42              "--htmlroot=/perl/nmanual",
43              "--libpods=perlfunc:perlguts:perlvar:perlrun:perlop",
44              "--recurse",
45              "--infile=foo.pod",
46              "--outfile=/perl/nmanual/foo.html");
47
48 pod2html takes the following arguments:
49
50 =over 4
51
52 =item backlink
53
54     --backlink="Back to Top"
55
56 Adds "Back to Top" links in front of every C<head1> heading (except for
57 the first).  By default, no backlinks are generated.
58
59 =item cachedir
60
61     --cachedir=name
62
63 Creates the item and directory caches in the given directory.
64
65 =item css
66
67     --css=stylesheet
68
69 Specify the URL of a cascading style sheet.  Also disables all HTML/CSS
70 C<style> attributes that are output by default (to avoid conflicts).
71
72 =item flush
73
74     --flush
75
76 Flushes the item and directory caches.
77
78 =item header
79
80     --header
81     --noheader
82
83 Creates header and footer blocks containing the text of the C<NAME>
84 section.  By default, no headers are generated.
85
86 =item help
87
88     --help
89
90 Displays the usage message.
91
92 =item hiddendirs
93
94     --hiddendirs
95     --nohiddendirs
96
97 Include hidden directories in the search for POD's in podpath if recurse
98 is set.
99 The default is not to traverse any directory whose name begins with C<.>.
100 See L</"podpath"> and L</"recurse">.
101
102 [This option is for backward compatibility only.
103 It's hard to imagine that one would usefully create a module with a
104 name component beginning with C<.>.]
105
106 =item htmldir
107
108     --htmldir=name
109
110 Sets the directory in which the resulting HTML file is placed.  This
111 is used to generate relative links to other files. Not passing this
112 causes all links to be absolute, since this is the value that tells
113 Pod::Html the root of the documentation tree.
114
115 =item htmlroot
116
117     --htmlroot=name
118
119 Sets the base URL for the HTML files.  When cross-references are made,
120 the HTML root is prepended to the URL.
121
122 =item index
123
124     --index
125     --noindex
126
127 Generate an index at the top of the HTML file.  This is the default
128 behaviour.
129
130 =item infile
131
132     --infile=name
133
134 Specify the pod file to convert.  Input is taken from STDIN if no
135 infile is specified.
136
137 =item libpods
138
139     --libpods=name:...:name
140
141 List of page names (eg, "perlfunc") which contain linkable C<=item>s.
142
143 =item netscape
144
145     --netscape
146     --nonetscape
147
148 B<Deprecated>, has no effect. For backwards compatibility only.
149
150 =item outfile
151
152     --outfile=name
153
154 Specify the HTML file to create.  Output goes to STDOUT if no outfile
155 is specified.
156
157 =item podpath
158
159     --podpath=name:...:name
160
161 Specify which subdirectories of the podroot contain pod files whose
162 HTML converted forms can be linked to in cross references.
163
164 =item podroot
165
166     --podroot=name
167
168 Specify the base directory for finding library pods.
169
170 =item quiet
171
172     --quiet
173     --noquiet
174
175 Don't display I<mostly harmless> warning messages.  These messages
176 will be displayed by default.  But this is not the same as C<verbose>
177 mode.
178
179 =item recurse
180
181     --recurse
182     --norecurse
183
184 Recurse into subdirectories specified in podpath (default behaviour).
185
186 =item title
187
188     --title=title
189
190 Specify the title of the resulting HTML file.
191
192 =item verbose
193
194     --verbose
195     --noverbose
196
197 Display progress messages.  By default, they won't be displayed.
198
199 =back
200
201 =head2 htmlify
202
203     htmlify($heading);
204
205 Converts a pod section specification to a suitable section specification
206 for HTML. Note that we keep spaces and special characters except 
207 C<", ?> (Netscape problem) and the hyphen (writer's problem...).
208
209 =head2 anchorify
210
211     anchorify(@heading);
212
213 Similar to C<htmlify()>, but turns non-alphanumerics into underscores.  Note
214 that C<anchorify()> is not exported by default.
215
216 =head1 ENVIRONMENT
217
218 Uses C<$Config{pod2html}> to setup default options.
219
220 =head1 AUTHOR
221
222 Tom Christiansen, E<lt>tchrist@perl.comE<gt>.
223
224 =head1 SEE ALSO
225
226 L<perlpod>
227
228 =head1 COPYRIGHT
229
230 This program is distributed under the Artistic License.
231
232 =cut
233
234
235 my($Cachedir);
236 my($Dircache, $Itemcache);
237 my @Begin_Stack;
238 my @Libpods;
239 my($Htmlroot, $Htmldir, $Htmlfile, $Htmlfileurl);
240 my($Podfile, @Podpath, $Podroot);
241 my $Css;
242
243 my $Recurse;
244 my $Quiet;
245 my $HiddenDirs;
246 my $Verbose;
247 my $Doindex;
248
249 my $Backlink;
250 my($Listlevel, @Listend);
251 my $After_Lpar;
252 use vars qw($Ignore);  # need to localize it later.
253
254 my(%Items_Named, @Items_Seen);
255 my($Title, $Header);
256
257 my $Top;
258 my $Paragraph;
259
260 my %Sections;
261
262 # Caches
263 my %Pages = ();                 # associative array used to find the location
264                                 #   of pages referenced by L<> links.
265 my %Items = ();                 # associative array used to find the location
266                                 #   of =item directives referenced by C<> links
267
268 my %Local_Items;
269 my $Is83;
270
271 my $Curdir = File::Spec->curdir;
272
273 init_globals();
274
275 sub init_globals {
276     $Cachedir = ".";            # The directory to which item and directory
277                                 # caches will be written.
278
279     $Dircache = "pod2htmd.tmp";
280     $Itemcache = "pod2htmi.tmp";
281
282     @Begin_Stack = ();          # begin/end stack
283
284     @Libpods = ();              # files to search for links from C<> directives
285     $Htmlroot = "/";            # http-server base directory from which all
286                                 #   relative paths in $podpath stem.
287     $Htmldir = "";              # The directory to which the html pages
288                                 # will (eventually) be written.
289     $Htmlfile = "";             # write to stdout by default
290     $Htmlfileurl = "" ;         # The url that other files would use to
291                                 # refer to this file.  This is only used
292                                 # to make relative urls that point to
293                                 # other files.
294
295     $Podfile = "";              # read from stdin by default
296     @Podpath = ();              # list of directories containing library pods.
297     $Podroot = $Curdir;         # filesystem base directory from which all
298                                 #   relative paths in $podpath stem.
299     $Css = '';                  # Cascading style sheet
300     $Recurse = 1;               # recurse on subdirectories in $podpath.
301     $Quiet = 0;                 # not quiet by default
302     $Verbose = 0;               # not verbose by default
303     $Doindex = 1;               # non-zero if we should generate an index
304     $Backlink = '';             # text for "back to top" links
305     $Listlevel = 0;             # current list depth
306     @Listend = ();              # the text to use to end the list.
307     $After_Lpar = 0;            # set to true after a par in an =item
308     $Ignore = 1;                # whether or not to format text.  we don't
309                                 #   format text until we hit our first pod
310                                 #   directive.
311
312     @Items_Seen = ();           # for multiples of the same item in perlfunc
313     %Items_Named = ();
314     $Header = 0;                # produce block header/footer
315     $Title = '';                # title to give the pod(s)
316     $Top = 1;                   # true if we are at the top of the doc.  used
317                                 #   to prevent the first <hr /> directive.
318     $Paragraph = '';            # which paragraph we're processing (used
319                                 #   for error messages)
320     %Sections = ();             # sections within this page
321
322     %Local_Items = ();
323     $Is83 = $^O eq 'dos';       # Is it an 8.3 filesystem?
324 }
325
326 #
327 # clean_data: global clean-up of pod data
328 #
329 sub clean_data($){
330     my( $dataref ) = @_;
331     for my $i ( 0..$#{$dataref} ) {
332         ${$dataref}[$i] =~ s/\s+\Z//;
333
334         # have a look for all-space lines
335       if( ${$dataref}[$i] =~ /^\s+$/m and $dataref->[$i] !~ /^\s/ ){
336             my @chunks = split( /^\s+$/m, ${$dataref}[$i] );
337             splice( @$dataref, $i, 1, @chunks );
338         }
339     }
340 }
341
342
343 sub pod2html {
344     local(@ARGV) = @_;
345     local($/);
346     local $_;
347
348     init_globals();
349
350     $Is83 = 0 if (defined (&Dos::UseLFN) && Dos::UseLFN());
351
352     # cache of %Pages and %Items from last time we ran pod2html
353
354     #undef $opt_help if defined $opt_help;
355
356     # parse the command-line parameters
357     parse_command_line();
358
359     # escape the backlink argument (same goes for title but is done later...)
360     $Backlink = html_escape($Backlink) if defined $Backlink;
361
362     # set some variables to their default values if necessary
363     local *POD;
364     unless (@ARGV && $ARGV[0]) {
365         $Podfile  = "-" unless $Podfile;        # stdin
366         open(POD, "<$Podfile")
367                 || die "$0: cannot open $Podfile file for input: $!\n";
368     } else {
369         $Podfile = $ARGV[0];  # XXX: might be more filenames
370         *POD = *ARGV;
371     }
372     $Htmlfile = "-" unless $Htmlfile;   # stdout
373     $Htmlroot = "" if $Htmlroot eq "/"; # so we don't get a //
374     $Htmldir =~ s#/\z## ;               # so we don't get a //
375     if (  $Htmlroot eq ''
376        && defined( $Htmldir )
377        && $Htmldir ne ''
378        && substr( $Htmlfile, 0, length( $Htmldir ) ) eq $Htmldir
379        )
380     {
381         # Set the 'base' url for this file, so that we can use it
382         # as the location from which to calculate relative links
383         # to other files. If this is '', then absolute links will
384         # be used throughout.
385         $Htmlfileurl= "$Htmldir/" . substr( $Htmlfile, length( $Htmldir ) + 1);
386     }
387
388     # read the pod a paragraph at a time
389     warn "Scanning for sections in input file(s)\n" if $Verbose;
390     $/ = "";
391     my @poddata  = <POD>;
392     close(POD);
393
394     # be eol agnostic
395     for (@poddata) {
396         if (/\r/) {
397             if (/\r\n/) {
398                 @poddata = map { s/\r\n/\n/g;
399                                  /\n\n/ ?
400                                      map { "$_\n\n" } split /\n\n/ :
401                                      $_ } @poddata;
402             } else {
403                 @poddata = map { s/\r/\n/g;
404                                  /\n\n/ ?
405                                      map { "$_\n\n" } split /\n\n/ :
406                                      $_ } @poddata;
407             }
408             last;
409         }
410     }
411
412     clean_data( \@poddata );
413
414     # scan the pod for =head[1-6] directives and build an index
415     my $index = scan_headings(\%Sections, @poddata);
416
417     unless($index) {
418         warn "No headings in $Podfile\n" if $Verbose;
419     }
420
421     # open the output file
422     open(HTML, ">$Htmlfile")
423             || die "$0: cannot open $Htmlfile file for output: $!\n";
424
425     # put a title in the HTML file if one wasn't specified
426     if ($Title eq '') {
427         TITLE_SEARCH: {
428             for (my $i = 0; $i < @poddata; $i++) {
429                 if ($poddata[$i] =~ /^=head1\s*NAME\b/m) {
430                     for my $para ( @poddata[$i, $i+1] ) {
431                         last TITLE_SEARCH
432                             if ($Title) = $para =~ /(\S+\s+-+.*\S)/s;
433                     }
434                 }
435
436             }
437         }
438     }
439     if (!$Title and $Podfile =~ /\.pod\z/) {
440         # probably a split pod so take first =head[12] as title
441         for (my $i = 0; $i < @poddata; $i++) {
442             last if ($Title) = $poddata[$i] =~ /^=head[12]\s*(.*)/;
443         }
444         warn "adopted '$Title' as title for $Podfile\n"
445             if $Verbose and $Title;
446     }
447     if ($Title) {
448         $Title =~ s/\s*\(.*\)//;
449     } else {
450         warn "$0: no title for $Podfile.\n" unless $Quiet;
451         $Podfile =~ /^(.*)(\.[^.\/]+)?\z/s;
452         $Title = ($Podfile eq "-" ? 'No Title' : $1);
453         warn "using $Title" if $Verbose;
454     }
455     $Title = html_escape($Title);
456
457     my $csslink = '';
458     my $bodystyle = ' style="background-color: white"';
459     my $tdstyle = ' style="background-color: #cccccc"';
460
461     if ($Css) {
462       $csslink = qq(\n<link rel="stylesheet" href="$Css" type="text/css" />);
463       $csslink =~ s,\\,/,g;
464       $csslink =~ s,(/.):,$1|,;
465       $bodystyle = '';
466       $tdstyle = '';
467     }
468
469       my $block = $Header ? <<END_OF_BLOCK : '';
470 <table border="0" width="100%" cellspacing="0" cellpadding="3">
471 <tr><td class="block"$tdstyle valign="middle">
472 <big><strong><span class="block">&nbsp;$Title</span></strong></big>
473 </td></tr>
474 </table>
475 END_OF_BLOCK
476
477     print HTML <<END_OF_HEAD;
478 <?xml version="1.0" ?>
479 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
480 <html xmlns="http://www.w3.org/1999/xhtml">
481 <head>
482 <title>$Title</title>$csslink
483 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
484 <link rev="made" href="mailto:$Config{perladmin}" />
485 </head>
486
487 <body$bodystyle>
488 $block
489 END_OF_HEAD
490
491     # load/reload/validate/cache %Pages and %Items
492     get_cache($Dircache, $Itemcache, \@Podpath, $Podroot, $Recurse);
493
494     # scan the pod for =item directives
495     scan_items( \%Local_Items, "", @poddata);
496
497     # put an index at the top of the file.  note, if $Doindex is 0 we
498     # still generate an index, but surround it with an html comment.
499     # that way some other program can extract it if desired.
500     $index =~ s/--+/-/g;
501
502     my $hr = ($Doindex and $index) ? qq(<hr name="index" />) : "";
503
504     unless ($Doindex)
505     {
506         $index = qq(<!--\n$index\n-->\n);
507     }
508
509     print HTML << "END_OF_INDEX";
510
511 <!-- INDEX BEGIN -->
512 <div name="index">
513 <p><a name=\"__index__\"></a></p>
514 $index
515 $hr
516 </div>
517 <!-- INDEX END -->
518
519 END_OF_INDEX
520
521     # now convert this file
522     my $after_item;             # set to true after an =item
523     my $need_dd = 0;
524     warn "Converting input file $Podfile\n" if $Verbose;
525     foreach my $i (0..$#poddata){
526         $_ = $poddata[$i];
527         $Paragraph = $i+1;
528         if (/^(=.*)/s) {        # is it a pod directive?
529             $Ignore = 0;
530             $after_item = 0;
531             $need_dd = 0;
532             $_ = $1;
533             if (/^=begin\s+(\S+)\s*(.*)/si) {# =begin
534                 process_begin($1, $2);
535             } elsif (/^=end\s+(\S+)\s*(.*)/si) {# =end
536                 process_end($1, $2);
537             } elsif (/^=cut/) {                 # =cut
538                 process_cut();
539             } elsif (/^=pod/) {                 # =pod
540                 process_pod();
541             } else {
542                 next if @Begin_Stack && $Begin_Stack[-1] ne 'html';
543
544                 if (/^=(head[1-6])\s+(.*\S)/s) {        # =head[1-6] heading
545                     process_head( $1, $2, $Doindex && $index );
546                 } elsif (/^=item\s*(.*\S)?/sm) {        # =item text
547                     $need_dd = process_item( $1 );
548                     $after_item = 1;
549                 } elsif (/^=over\s*(.*)/) {             # =over N
550                     process_over();
551                 } elsif (/^=back/) {            # =back
552                     process_back($need_dd);
553                 } elsif (/^=for\s+(\S+)\s*(.*)/si) {# =for
554                     process_for($1,$2);
555                 } else {
556                     /^=(\S*)\s*/;
557                     warn "$0: $Podfile: unknown pod directive '$1' in "
558                        . "paragraph $Paragraph.  ignoring.\n" unless $Quiet;
559                 }
560             }
561             $Top = 0;
562         }
563         else {
564             next if $Ignore;
565             next if @Begin_Stack && $Begin_Stack[-1] ne 'html';
566             print HTML and next if @Begin_Stack && $Begin_Stack[-1] eq 'html';
567             print HTML "<dd>\n" if $need_dd;
568             my $text = $_;
569             if( $text =~ /\A\s+/ ){
570                 process_pre( \$text );
571                 print HTML "<pre>\n$text</pre>\n";
572
573             } else {
574                 process_text( \$text );
575
576                 # experimental: check for a paragraph where all lines
577                 # have some ...\t...\t...\n pattern
578                 if( $text =~ /\t/ ){
579                     my @lines = split( "\n", $text );
580                     if( @lines > 1 ){
581                         my $all = 2;
582                         foreach my $line ( @lines ){
583                             if( $line =~ /\S/ && $line !~ /\t/ ){
584                                 $all--;
585                                 last if $all == 0;
586                             }
587                         }
588                         if( $all > 0 ){
589                             $text =~ s/\t+/<td>/g;
590                             $text =~ s/^/<tr><td>/gm;
591                             $text = '<table cellspacing="0" cellpadding="0">' .
592                                     $text . '</table>';
593                         }
594                     }
595                 }
596                 ## end of experimental
597
598                 if( $after_item ){
599                     $After_Lpar = 1;
600                 }
601                 print HTML "<p>$text</p>\n";
602             }
603             print HTML "</dd>\n" if $need_dd;
604             $after_item = 0;
605         }
606     }
607
608     # finish off any pending directives
609     finish_list();
610
611     # link to page index
612     print HTML "<p><a href=\"#__index__\"><small>$Backlink</small></a></p>\n"
613         if $Doindex and $index and $Backlink;
614
615     print HTML <<END_OF_TAIL;
616 $block
617 </body>
618
619 </html>
620 END_OF_TAIL
621
622     # close the html file
623     close(HTML);
624
625     warn "Finished\n" if $Verbose;
626 }
627
628 ##############################################################################
629
630 sub usage {
631     my $podfile = shift;
632     warn "$0: $podfile: @_\n" if @_;
633     die <<END_OF_USAGE;
634 Usage:  $0 --help --htmlroot=<name> --infile=<name> --outfile=<name>
635            --podpath=<name>:...:<name> --podroot=<name>
636            --libpods=<name>:...:<name> --recurse --verbose --index
637            --netscape --norecurse --noindex --cachedir=<name>
638
639   --backlink     - set text for "back to top" links (default: none).
640   --cachedir     - directory for the item and directory cache files.
641   --css          - stylesheet URL
642   --flush        - flushes the item and directory caches.
643   --[no]header   - produce block header/footer (default is no headers).
644   --help         - prints this message.
645   --hiddendirs   - search hidden directories in podpath
646   --htmldir      - directory for resulting HTML files.
647   --htmlroot     - http-server base directory from which all relative paths
648                    in podpath stem (default is /).
649   --[no]index    - generate an index at the top of the resulting html
650                    (default behaviour).
651   --infile       - filename for the pod to convert (input taken from stdin
652                    by default).
653   --libpods      - colon-separated list of pages to search for =item pod
654                    directives in as targets of C<> and implicit links (empty
655                    by default).  note, these are not filenames, but rather
656                    page names like those that appear in L<> links.
657   --outfile      - filename for the resulting html file (output sent to
658                    stdout by default).
659   --podpath      - colon-separated list of directories containing library
660                    pods (empty by default).
661   --podroot      - filesystem base directory from which all relative paths
662                    in podpath stem (default is .).
663   --[no]quiet    - suppress some benign warning messages (default is off).
664   --[no]recurse  - recurse on those subdirectories listed in podpath
665                    (default behaviour).
666   --title        - title that will appear in resulting html file.
667   --[no]verbose  - self-explanatory (off by default).
668   --[no]netscape - deprecated, has no effect. for backwards compatibility only.
669
670 END_OF_USAGE
671
672 }
673
674 sub parse_command_line {
675     my ($opt_backlink,$opt_cachedir,$opt_css,$opt_flush,$opt_header,$opt_help,
676         $opt_htmldir,$opt_htmlroot,$opt_index,$opt_infile,$opt_libpods,
677         $opt_netscape,$opt_outfile,$opt_podpath,$opt_podroot,$opt_quiet,
678         $opt_recurse,$opt_title,$opt_verbose,$opt_hiddendirs);
679
680     unshift @ARGV, split ' ', $Config{pod2html} if $Config{pod2html};
681     my $result = GetOptions(
682                             'backlink=s' => \$opt_backlink,
683                             'cachedir=s' => \$opt_cachedir,
684                             'css=s'      => \$opt_css,
685                             'flush'      => \$opt_flush,
686                             'header!'    => \$opt_header,
687                             'help'       => \$opt_help,
688                             'hiddendirs!'=> \$opt_hiddendirs,
689                             'htmldir=s'  => \$opt_htmldir,
690                             'htmlroot=s' => \$opt_htmlroot,
691                             'index!'     => \$opt_index,
692                             'infile=s'   => \$opt_infile,
693                             'libpods=s'  => \$opt_libpods,
694                             'netscape!'  => \$opt_netscape,
695                             'outfile=s'  => \$opt_outfile,
696                             'podpath=s'  => \$opt_podpath,
697                             'podroot=s'  => \$opt_podroot,
698                             'quiet!'     => \$opt_quiet,
699                             'recurse!'   => \$opt_recurse,
700                             'title=s'    => \$opt_title,
701                             'verbose!'   => \$opt_verbose,
702                            );
703     usage("-", "invalid parameters") if not $result;
704
705     usage("-") if defined $opt_help;    # see if the user asked for help
706     $opt_help = "";                     # just to make -w shut-up.
707
708     @Podpath  = split(":", $opt_podpath) if defined $opt_podpath;
709     @Libpods  = split(":", $opt_libpods) if defined $opt_libpods;
710
711     $Backlink = $opt_backlink if defined $opt_backlink;
712     $Cachedir = $opt_cachedir if defined $opt_cachedir;
713     $Css      = $opt_css      if defined $opt_css;
714     $Header   = $opt_header   if defined $opt_header;
715     $Htmldir  = $opt_htmldir  if defined $opt_htmldir;
716     $Htmlroot = $opt_htmlroot if defined $opt_htmlroot;
717     $Doindex  = $opt_index    if defined $opt_index;
718     $Podfile  = $opt_infile   if defined $opt_infile;
719     $HiddenDirs = $opt_hiddendirs if defined $opt_hiddendirs;
720     $Htmlfile = $opt_outfile  if defined $opt_outfile;
721     $Podroot  = $opt_podroot  if defined $opt_podroot;
722     $Quiet    = $opt_quiet    if defined $opt_quiet;
723     $Recurse  = $opt_recurse  if defined $opt_recurse;
724     $Title    = $opt_title    if defined $opt_title;
725     $Verbose  = $opt_verbose  if defined $opt_verbose;
726
727     warn "Flushing item and directory caches\n"
728         if $opt_verbose && defined $opt_flush;
729     $Dircache = "$Cachedir/pod2htmd.tmp";
730     $Itemcache = "$Cachedir/pod2htmi.tmp";
731     if (defined $opt_flush) {
732         1 while unlink($Dircache, $Itemcache);
733     }
734 }
735
736
737 my $Saved_Cache_Key;
738
739 sub get_cache {
740     my($dircache, $itemcache, $podpath, $podroot, $recurse) = @_;
741     my @cache_key_args = @_;
742
743     # A first-level cache:
744     # Don't bother reading the cache files if they still apply
745     # and haven't changed since we last read them.
746
747     my $this_cache_key = cache_key(@cache_key_args);
748
749     return if $Saved_Cache_Key and $this_cache_key eq $Saved_Cache_Key;
750
751     # load the cache of %Pages and %Items if possible.  $tests will be
752     # non-zero if successful.
753     my $tests = 0;
754     if (-f $dircache && -f $itemcache) {
755         warn "scanning for item cache\n" if $Verbose;
756         $tests = load_cache($dircache, $itemcache, $podpath, $podroot);
757     }
758
759     # if we didn't succeed in loading the cache then we must (re)build
760     #  %Pages and %Items.
761     if (!$tests) {
762         warn "scanning directories in pod-path\n" if $Verbose;
763         scan_podpath($podroot, $recurse, 0);
764     }
765     $Saved_Cache_Key = cache_key(@cache_key_args);
766 }
767
768 sub cache_key {
769     my($dircache, $itemcache, $podpath, $podroot, $recurse) = @_;
770     return join('!', $dircache, $itemcache, $recurse,
771         @$podpath, $podroot, stat($dircache), stat($itemcache));
772 }
773
774 #
775 # load_cache - tries to find if the caches stored in $dircache and $itemcache
776 #  are valid caches of %Pages and %Items.  if they are valid then it loads
777 #  them and returns a non-zero value.
778 #
779 sub load_cache {
780     my($dircache, $itemcache, $podpath, $podroot) = @_;
781     my($tests);
782     local $_;
783
784     $tests = 0;
785
786     open(CACHE, "<$itemcache") ||
787         die "$0: error opening $itemcache for reading: $!\n";
788     $/ = "\n";
789
790     # is it the same podpath?
791     $_ = <CACHE>;
792     chomp($_);
793     $tests++ if (join(":", @$podpath) eq $_);
794
795     # is it the same podroot?
796     $_ = <CACHE>;
797     chomp($_);
798     $tests++ if ($podroot eq $_);
799
800     # load the cache if its good
801     if ($tests != 2) {
802         close(CACHE);
803         return 0;
804     }
805
806     warn "loading item cache\n" if $Verbose;
807     while (<CACHE>) {
808         /(.*?) (.*)$/;
809         $Items{$1} = $2;
810     }
811     close(CACHE);
812
813     warn "scanning for directory cache\n" if $Verbose;
814     open(CACHE, "<$dircache") ||
815         die "$0: error opening $dircache for reading: $!\n";
816     $/ = "\n";
817     $tests = 0;
818
819     # is it the same podpath?
820     $_ = <CACHE>;
821     chomp($_);
822     $tests++ if (join(":", @$podpath) eq $_);
823
824     # is it the same podroot?
825     $_ = <CACHE>;
826     chomp($_);
827     $tests++ if ($podroot eq $_);
828
829     # load the cache if its good
830     if ($tests != 2) {
831         close(CACHE);
832         return 0;
833     }
834
835     warn "loading directory cache\n" if $Verbose;
836     while (<CACHE>) {
837         /(.*?) (.*)$/;
838         $Pages{$1} = $2;
839     }
840
841     close(CACHE);
842
843     return 1;
844 }
845
846 #
847 # scan_podpath - scans the directories specified in @podpath for directories,
848 #  .pod files, and .pm files.  it also scans the pod files specified in
849 #  @Libpods for =item directives.
850 #
851 sub scan_podpath {
852     my($podroot, $recurse, $append) = @_;
853     my($pwd, $dir);
854     my($libpod, $dirname, $pod, @files, @poddata);
855
856     unless($append) {
857         %Items = ();
858         %Pages = ();
859     }
860
861     # scan each directory listed in @Podpath
862     $pwd = getcwd();
863     chdir($podroot)
864         || die "$0: error changing to directory $podroot: $!\n";
865     foreach $dir (@Podpath) {
866         scan_dir($dir, $recurse);
867     }
868
869     # scan the pods listed in @Libpods for =item directives
870     foreach $libpod (@Libpods) {
871         # if the page isn't defined then we won't know where to find it
872         # on the system.
873         next unless defined $Pages{$libpod} && $Pages{$libpod};
874
875         # if there is a directory then use the .pod and .pm files within it.
876         # NOTE: Only finds the first so-named directory in the tree.
877 #       if ($Pages{$libpod} =~ /([^:]*[^(\.pod|\.pm)]):/) {
878         if ($Pages{$libpod} =~ /([^:]*(?<!\.pod)(?<!\.pm)):/) {
879             #  find all the .pod and .pm files within the directory
880             $dirname = $1;
881             opendir(DIR, $dirname) ||
882                 die "$0: error opening directory $dirname: $!\n";
883             @files = grep(/(\.pod|\.pm)\z/ && ! -d $_, readdir(DIR));
884             closedir(DIR);
885
886             # scan each .pod and .pm file for =item directives
887             foreach $pod (@files) {
888                 open(POD, "<$dirname/$pod") ||
889                     die "$0: error opening $dirname/$pod for input: $!\n";
890                 @poddata = <POD>;
891                 close(POD);
892                 clean_data( \@poddata );
893
894                 scan_items( \%Items, "$dirname/$pod", @poddata);
895             }
896
897             # use the names of files as =item directives too.
898 ### Don't think this should be done this way - confuses issues.(WL)
899 ###         foreach $pod (@files) {
900 ###             $pod =~ /^(.*)(\.pod|\.pm)$/;
901 ###             $Items{$1} = "$dirname/$1.html" if $1;
902 ###         }
903         } elsif ($Pages{$libpod} =~ /([^:]*\.pod):/ ||
904                  $Pages{$libpod} =~ /([^:]*\.pm):/) {
905             # scan the .pod or .pm file for =item directives
906             $pod = $1;
907             open(POD, "<$pod") ||
908                 die "$0: error opening $pod for input: $!\n";
909             @poddata = <POD>;
910             close(POD);
911             clean_data( \@poddata );
912
913             scan_items( \%Items, "$pod", @poddata);
914         } else {
915             warn "$0: shouldn't be here (line ".__LINE__."\n" unless $Quiet;
916         }
917     }
918     @poddata = ();      # clean-up a bit
919
920     chdir($pwd)
921         || die "$0: error changing to directory $pwd: $!\n";
922
923     # cache the item list for later use
924     warn "caching items for later use\n" if $Verbose;
925     open(CACHE, ">$Itemcache") ||
926         die "$0: error open $Itemcache for writing: $!\n";
927
928     print CACHE join(":", @Podpath) . "\n$podroot\n";
929     foreach my $key (keys %Items) {
930         print CACHE "$key $Items{$key}\n";
931     }
932
933     close(CACHE);
934
935     # cache the directory list for later use
936     warn "caching directories for later use\n" if $Verbose;
937     open(CACHE, ">$Dircache") ||
938         die "$0: error open $Dircache for writing: $!\n";
939
940     print CACHE join(":", @Podpath) . "\n$podroot\n";
941     foreach my $key (keys %Pages) {
942         print CACHE "$key $Pages{$key}\n";
943     }
944
945     close(CACHE);
946 }
947
948 #
949 # scan_dir - scans the directory specified in $dir for subdirectories, .pod
950 #  files, and .pm files.  notes those that it finds.  this information will
951 #  be used later in order to figure out where the pages specified in L<>
952 #  links are on the filesystem.
953 #
954 sub scan_dir {
955     my($dir, $recurse) = @_;
956     my($t, @subdirs, @pods, $pod, $dirname, @dirs);
957     local $_;
958
959     @subdirs = ();
960     @pods = ();
961
962     opendir(DIR, $dir) ||
963         die "$0: error opening directory $dir: $!\n";
964     while (defined($_ = readdir(DIR))) {
965         if (-d "$dir/$_" && $_ ne "." && $_ ne ".."
966             && ($HiddenDirs || !/^\./)
967         ) {         # directory
968             $Pages{$_}  = "" unless defined $Pages{$_};
969             $Pages{$_} .= "$dir/$_:";
970             push(@subdirs, $_);
971         } elsif (/\.pod\z/) {                               # .pod
972             s/\.pod\z//;
973             $Pages{$_}  = "" unless defined $Pages{$_};
974             $Pages{$_} .= "$dir/$_.pod:";
975             push(@pods, "$dir/$_.pod");
976         } elsif (/\.html\z/) {                              # .html
977             s/\.html\z//;
978             $Pages{$_}  = "" unless defined $Pages{$_};
979             $Pages{$_} .= "$dir/$_.pod:";
980         } elsif (/\.pm\z/) {                                # .pm
981             s/\.pm\z//;
982             $Pages{$_}  = "" unless defined $Pages{$_};
983             $Pages{$_} .= "$dir/$_.pm:";
984             push(@pods, "$dir/$_.pm");
985         } elsif (-T "$dir/$_") {                            # script(?)
986             local *F;
987             if (open(F, "$dir/$_")) {
988                 my $line;
989                 while (defined($line = <F>)) {
990                     if ($line =~ /^=(?:pod|head1)/) {
991                         $Pages{$_}  = "" unless defined $Pages{$_};
992                         $Pages{$_} .= "$dir/$_.pod:";
993                         last;
994                     }
995                 }
996                 close(F);
997             }
998         }
999     }
1000     closedir(DIR);
1001
1002     # recurse on the subdirectories if necessary
1003     if ($recurse) {
1004         foreach my $subdir (@subdirs) {
1005             scan_dir("$dir/$subdir", $recurse);
1006         }
1007     }
1008 }
1009
1010 #
1011 # scan_headings - scan a pod file for head[1-6] tags, note the tags, and
1012 #  build an index.
1013 #
1014 sub scan_headings {
1015     my($sections, @data) = @_;
1016     my($tag, $which_head, $otitle, $listdepth, $index);
1017
1018     local $Ignore = 0;
1019
1020     $listdepth = 0;
1021     $index = "";
1022
1023     # scan for =head directives, note their name, and build an index
1024     #  pointing to each of them.
1025     foreach my $line (@data) {
1026       if ($line =~ /^=(head)([1-6])\s+(.*)/) {
1027         ($tag, $which_head, $otitle) = ($1,$2,$3);
1028
1029         my $title = depod( $otitle );
1030         my $name = anchorify( $title );
1031         $$sections{$name} = 1;
1032         $title = process_text( \$otitle );
1033
1034             while ($which_head != $listdepth) {
1035                 if ($which_head > $listdepth) {
1036                     $index .= "\n" . ("\t" x $listdepth) . "<ul>\n";
1037                     $listdepth++;
1038                 } elsif ($which_head < $listdepth) {
1039                     $listdepth--;
1040                     $index .= "\n" . ("\t" x $listdepth) . "</ul>\n";
1041                 }
1042             }
1043
1044             $index .= "\n" . ("\t" x $listdepth) . "<li>" .
1045                       "<a href=\"#" . $name . "\">" .
1046                       $title . "</a></li>";
1047         }
1048     }
1049
1050     # finish off the lists
1051     while ($listdepth--) {
1052         $index .= "\n" . ("\t" x $listdepth) . "</ul>\n";
1053     }
1054
1055     # get rid of bogus lists
1056     $index =~ s,\t*<ul>\s*</ul>\n,,g;
1057
1058     return $index;
1059 }
1060
1061 #
1062 # scan_items - scans the pod specified by $pod for =item directives.  we
1063 #  will use this information later on in resolving C<> links.
1064 #
1065 sub scan_items {
1066     my( $itemref, $pod, @poddata ) = @_;
1067     my($i, $item);
1068     local $_;
1069
1070     $pod =~ s/\.pod\z//;
1071     $pod .= ".html" if $pod;
1072
1073     foreach $i (0..$#poddata) {
1074         my $txt = depod( $poddata[$i] );
1075
1076         # figure out what kind of item it is.
1077         # Build string for referencing this item.
1078         if ( $txt =~ /\A=item\s+\*\s*(.*)\Z/s ) { # bullet
1079             next unless $1;
1080             $item = $1;
1081         } elsif( $txt =~ /\A=item\s+(?>\d+\.?)\s*(.*)\Z/s ) { # numbered list
1082             $item = $1;
1083         } elsif( $txt =~ /\A=item\s+(.*)\Z/s ) { # plain item
1084             $item = $1;
1085         } else {
1086             next;
1087         }
1088         my $fid = fragment_id( $item );
1089         $$itemref{$fid} = "$pod" if $fid;
1090     }
1091 }
1092
1093 #
1094 # process_head - convert a pod head[1-6] tag and convert it to HTML format.
1095 #
1096 sub process_head {
1097     my($tag, $heading, $hasindex) = @_;
1098
1099     # figure out the level of the =head
1100     $tag =~ /head([1-6])/;
1101     my $level = $1;
1102
1103     if( $Listlevel ){
1104         warn "$0: $Podfile: unterminated list at =head in paragraph $Paragraph.  ignoring.\n" unless $Quiet;
1105         while( $Listlevel ){
1106             process_back();
1107         }
1108     }
1109
1110     print HTML "<p>\n";
1111     if( $level == 1 && ! $Top ){
1112       print HTML "<a href=\"#__index__\"><small>$Backlink</small></a>\n"
1113         if $hasindex and $Backlink;
1114       print HTML "</p>\n<hr />\n"
1115     } else {
1116       print HTML "</p>\n";
1117     }
1118
1119     my $name = anchorify( depod( $heading ) );
1120     my $convert = process_text( \$heading );
1121     print HTML "<h$level><a name=\"$name\">$convert</a></h$level>\n";
1122 }
1123
1124
1125 #
1126 # emit_item_tag - print an =item's text
1127 # Note: The global $EmittedItem is used for inhibiting self-references.
1128 #
1129 my $EmittedItem;
1130
1131 sub emit_item_tag($$$){
1132     my( $otext, $text, $compact ) = @_;
1133     my $item = fragment_id( $text );
1134
1135     $EmittedItem = $item;
1136     ### print STDERR "emit_item_tag=$item ($text)\n";
1137
1138     print HTML '<strong>';
1139     if ($Items_Named{$item}++) {
1140         print HTML process_text( \$otext );
1141     } else {
1142         my $name = 'item_' . $item;
1143         $name = anchorify($name);
1144         print HTML qq{<a name="$name">}, process_text( \$otext ), '</a>';
1145     }
1146     print HTML "</strong>\n";
1147     undef( $EmittedItem );
1148 }
1149
1150 sub emit_li {
1151     my( $tag ) = @_;
1152     if( $Items_Seen[$Listlevel]++ == 0 ){
1153         push( @Listend, "</$tag>" );
1154         print HTML "<$tag>\n";
1155     }
1156     my $emitted = $tag eq 'dl' ? 'dt' : 'li';
1157     print HTML "<$emitted>";
1158     return $emitted;
1159 }
1160
1161 #
1162 # process_item - convert a pod item tag and convert it to HTML format.
1163 #
1164 sub process_item {
1165     my( $otext ) = @_;
1166     my $need_dd = 0; # set to 1 if we need a <dd></dd> after an item
1167
1168     # lots of documents start a list without doing an =over.  this is
1169     # bad!  but, the proper thing to do seems to be to just assume
1170     # they did do an =over.  so warn them once and then continue.
1171     if( $Listlevel == 0 ){
1172         warn "$0: $Podfile: unexpected =item directive in paragraph $Paragraph.  ignoring.\n" unless $Quiet;
1173         process_over();
1174     }
1175
1176     # formatting: insert a paragraph if preceding item has >1 paragraph
1177     if( $After_Lpar ){
1178         print HTML $need_dd ? "</dd>\n" : "</li>\n" if $After_Lpar;
1179         $After_Lpar = 0;
1180     }
1181
1182     # remove formatting instructions from the text
1183     my $text = depod( $otext );
1184
1185     my $emitted; # the tag actually emitted, used for closing
1186
1187     # all the list variants:
1188     if( $text =~ /\A\*/ ){ # bullet
1189         $emitted = emit_li( 'ul' );
1190         if ($text =~ /\A\*\s+(.+)\Z/s ) { # with additional text
1191             my $tag = $1;
1192             $otext =~ s/\A\*\s+//;
1193             emit_item_tag( $otext, $tag, 1 );
1194         }
1195
1196     } elsif( $text =~ /\A\d+/ ){ # numbered list
1197         $emitted = emit_li( 'ol' );
1198         if ($text =~ /\A(?>\d+\.?)\s*(.+)\Z/s ) { # with additional text
1199             my $tag = $1;
1200             $otext =~ s/\A\d+\.?\s*//;
1201             emit_item_tag( $otext, $tag, 1 );
1202         }
1203
1204     } else {                    # definition list
1205         $emitted = emit_li( 'dl' );
1206         if ($text =~ /\A(.+)\Z/s ){ # should have text
1207             emit_item_tag( $otext, $text, 1 );
1208         }
1209         $need_dd = 1;
1210     }
1211     print HTML "\n";
1212     return $need_dd;
1213 }
1214
1215 #
1216 # process_over - process a pod over tag and start a corresponding HTML list.
1217 #
1218 sub process_over {
1219     # start a new list
1220     $Listlevel++;
1221     push( @Items_Seen, 0 );
1222     $After_Lpar = 0;
1223 }
1224
1225 #
1226 # process_back - process a pod back tag and convert it to HTML format.
1227 #
1228 sub process_back {
1229     my $need_dd = shift;
1230     if( $Listlevel == 0 ){
1231         warn "$0: $Podfile: unexpected =back directive in paragraph $Paragraph.  ignoring.\n" unless $Quiet;
1232         return;
1233     }
1234
1235     # close off the list.  note, I check to see if $Listend[$Listlevel] is
1236     # defined because an =item directive may have never appeared and thus
1237     # $Listend[$Listlevel] may have never been initialized.
1238     $Listlevel--;
1239     if( defined $Listend[$Listlevel] ){
1240         print HTML $need_dd ? "</dd>\n" : "</li>\n" if $After_Lpar;
1241         print HTML $Listend[$Listlevel];
1242         print HTML "\n";
1243         pop( @Listend );
1244     }
1245     $After_Lpar = 0;
1246
1247     # clean up item count
1248     pop( @Items_Seen );
1249 }
1250
1251 #
1252 # process_cut - process a pod cut tag, thus start ignoring pod directives.
1253 #
1254 sub process_cut {
1255     $Ignore = 1;
1256 }
1257
1258 #
1259 # process_pod - process a pod tag, thus stop ignoring pod directives
1260 # until we see a corresponding cut.
1261 #
1262 sub process_pod {
1263     # no need to set $Ignore to 0 cause the main loop did it
1264 }
1265
1266 #
1267 # process_for - process a =for pod tag.  if it's for html, spit
1268 # it out verbatim, if illustration, center it, otherwise ignore it.
1269 #
1270 sub process_for {
1271     my($whom, $text) = @_;
1272     if ( $whom =~ /^(pod2)?html$/i) {
1273         print HTML $text;
1274     } elsif ($whom =~ /^illustration$/i) {
1275         1 while chomp $text;
1276         for my $ext (qw[.png .gif .jpeg .jpg .tga .pcl .bmp]) {
1277           $text .= $ext, last if -r "$text$ext";
1278         }
1279         print HTML qq{<p align="center"><img src="$text" alt="$text illustration" /></p>};
1280     }
1281 }
1282
1283 #
1284 # process_begin - process a =begin pod tag.  this pushes
1285 # whom we're beginning on the begin stack.  if there's a
1286 # begin stack, we only print if it us.
1287 #
1288 sub process_begin {
1289     my($whom, $text) = @_;
1290     $whom = lc($whom);
1291     push (@Begin_Stack, $whom);
1292     if ( $whom =~ /^(pod2)?html$/) {
1293         print HTML $text if $text;
1294     }
1295 }
1296
1297 #
1298 # process_end - process a =end pod tag.  pop the
1299 # begin stack.  die if we're mismatched.
1300 #
1301 sub process_end {
1302     my($whom, $text) = @_;
1303     $whom = lc($whom);
1304     if ($Begin_Stack[-1] ne $whom ) {
1305         die "Unmatched begin/end at chunk $Paragraph\n"
1306     }
1307     pop( @Begin_Stack );
1308 }
1309
1310 #
1311 # process_pre - indented paragraph, made into <pre></pre>
1312 #
1313 sub process_pre {
1314     my( $text ) = @_;
1315     my( $rest );
1316     return if $Ignore;
1317
1318     $rest = $$text;
1319
1320     # insert spaces in place of tabs
1321     $rest =~ s#(.+)#
1322             my $line = $1;
1323             1 while $line =~ s/(\t+)/' ' x ((length($1) * 8) - $-[0] % 8)/e;
1324             $line;
1325         #eg;
1326
1327     # convert some special chars to HTML escapes
1328     $rest = html_escape($rest);
1329
1330     # try and create links for all occurrences of perl.* within
1331     # the preformatted text.
1332     $rest =~ s{
1333                  (\s*)(perl\w+)
1334               }{
1335                  if ( defined $Pages{$2} ){     # is a link
1336                      qq($1<a href="$Htmlroot/$Pages{$2}">$2</a>);
1337                  } elsif (defined $Pages{dosify($2)}) { # is a link
1338                      qq($1<a href="$Htmlroot/$Pages{dosify($2)}">$2</a>);
1339                  } else {
1340                      "$1$2";
1341                  }
1342               }xeg;
1343      $rest =~ s{
1344                  (<a\ href="?) ([^>:]*:)? ([^>:]*) \.pod: ([^>:]*:)?
1345                }{
1346                   my $url ;
1347                   if ( $Htmlfileurl ne '' ){
1348                      # Here, we take advantage of the knowledge
1349                      # that $Htmlfileurl ne '' implies $Htmlroot eq ''.
1350                      # Since $Htmlroot eq '', we need to prepend $Htmldir
1351                      # on the fron of the link to get the absolute path
1352                      # of the link's target. We check for a leading '/'
1353                      # to avoid corrupting links that are #, file:, etc.
1354                      my $old_url = $3 ;
1355                      $old_url = "$Htmldir$old_url" if $old_url =~ m{^\/};
1356                      $url = relativize_url( "$old_url.html", $Htmlfileurl );
1357                   } else {
1358                      $url = "$3.html" ;
1359                   }
1360                   "$1$url" ;
1361                }xeg;
1362
1363     # Look for embedded URLs and make them into links.  We don't
1364     # relativize them since they are best left as the author intended.
1365
1366     my $urls = '(' . join ('|', qw{
1367                 http
1368                 telnet
1369                 mailto
1370                 news
1371                 gopher
1372                 file
1373                 wais
1374                 ftp
1375             } )
1376         . ')';
1377
1378     my $ltrs = '\w';
1379     my $gunk = '/#~:.?+=&%@!\-';
1380     my $punc = '.:!?\-;';
1381     my $any  = "${ltrs}${gunk}${punc}";
1382
1383     $rest =~ s{
1384         \b                      # start at word boundary
1385         (                       # begin $1  {
1386             $urls :             # need resource and a colon
1387             (?!:)               # Ignore File::, among others.
1388             [$any] +?           # followed by one or more of any valid
1389                                 #   character, but be conservative and
1390                                 #   take only what you need to....
1391         )                       # end   $1  }
1392         (?=
1393             &quot; &gt;         # maybe pre-quoted '<a href="...">'
1394         |                       # or:
1395             [$punc]*            # 0 or more punctuation
1396             (?:                 #   followed
1397                 [^$any]         #   by a non-url char
1398             |                   #   or
1399                 $               #   end of the string
1400             )                   #
1401         |                       # or else
1402             $                   #   then end of the string
1403         )
1404       }{<a href="$1">$1</a>}igox;
1405
1406     # text should be as it is (verbatim)
1407     $$text = $rest;
1408 }
1409
1410
1411 #
1412 # pure text processing
1413 #
1414 # pure_text/inIS_text: differ with respect to automatic C<> recognition.
1415 # we don't want this to happen within IS
1416 #
1417 sub pure_text($){
1418     my $text = shift();
1419     process_puretext( $text, 1 );
1420 }
1421
1422 sub inIS_text($){
1423     my $text = shift();
1424     process_puretext( $text, 0 );
1425 }
1426
1427 #
1428 # process_puretext - process pure text (without pod-escapes) converting
1429 #  double-quotes and handling implicit C<> links.
1430 #
1431 sub process_puretext {
1432     my($text, $notinIS) = @_;
1433
1434     ## Guessing at func() or [\$\@%&]*var references in plain text is destined
1435     ## to produce some strange looking ref's. uncomment to disable:
1436     ## $notinIS = 0;
1437
1438     my(@words, $lead, $trail);
1439
1440     # keep track of leading and trailing white-space
1441     $lead  = ($text =~ s/\A(\s+)//s ? $1 : "");
1442     $trail = ($text =~ s/(\s+)\Z//s ? $1 : "");
1443
1444     # split at space/non-space boundaries
1445     @words = split( /(?<=\s)(?=\S)|(?<=\S)(?=\s)/, $text );
1446
1447     # process each word individually
1448     foreach my $word (@words) {
1449         # skip space runs
1450         next if $word =~ /^\s*$/;
1451         # see if we can infer a link
1452         if( $notinIS && $word =~ /^(\w+)\((.*)\)$/ ) {
1453             # has parenthesis so should have been a C<> ref
1454             ## try for a pagename (perlXXX(1))?
1455             my( $func, $args ) = ( $1, $2 );
1456             if( $args =~ /^\d+$/ ){
1457                 my $url = page_sect( $word, '' );
1458                 if( defined $url ){
1459                     $word = "<a href=\"$url\">the $word manpage</a>";
1460                     next;
1461                 }
1462             }
1463             ## try function name for a link, append tt'ed argument list
1464             $word = emit_C( $func, '', "($args)");
1465
1466 #### disabled. either all (including $\W, $\w+{.*} etc.) or nothing.
1467 ##      } elsif( $notinIS && $word =~ /^[\$\@%&*]+\w+$/) {
1468 ##          # perl variables, should be a C<> ref
1469 ##          $word = emit_C( $word );
1470
1471         } elsif ($word =~ m,^\w+://\w,) {
1472             # looks like a URL
1473             # Don't relativize it: leave it as the author intended
1474             $word = qq(<a href="$word">$word</a>);
1475         } elsif ($word =~ /[\w.-]+\@[\w-]+\.\w/) {
1476             # looks like an e-mail address
1477             my ($w1, $w2, $w3) = ("", $word, "");
1478             ($w1, $w2, $w3) = ("(", $1, ")$2") if $word =~ /^\((.*?)\)(,?)/;
1479             ($w1, $w2, $w3) = ("&lt;", $1, "&gt;$2") if $word =~ /^<(.*?)>(,?)/;
1480             $word = qq($w1<a href="mailto:$w2">$w2</a>$w3);
1481         } else {
1482             $word = html_escape($word) if $word =~ /["&<>]/;
1483         }
1484     }
1485
1486     # put everything back together
1487     return $lead . join( '', @words ) . $trail;
1488 }
1489
1490
1491 #
1492 # process_text - handles plaintext that appears in the input pod file.
1493 # there may be pod commands embedded within the text so those must be
1494 # converted to html commands.
1495 #
1496
1497 sub process_text1($$;$$);
1498 sub pattern ($) { $_[0] ? '[^\S\n]+'.('>' x ($_[0] + 1)) : '>' }
1499 sub closing ($) { local($_) = shift; (defined && s/\s+$//) ? length : 0 }
1500
1501 sub process_text {
1502     return if $Ignore;
1503     my( $tref ) = @_;
1504     my $res = process_text1( 0, $tref );
1505     $res =~ s/\s+$//s;
1506     $$tref = $res;
1507 }
1508
1509 sub process_text1($$;$$){
1510     my( $lev, $rstr, $func, $closing ) = @_;
1511     my $res = '';
1512
1513     unless (defined $func) {
1514         $func = '';
1515         $lev++;
1516     }
1517
1518     if( $func eq 'B' ){
1519         # B<text> - boldface
1520         $res = '<strong>' . process_text1( $lev, $rstr ) . '</strong>';
1521
1522     } elsif( $func eq 'C' ){
1523         # C<code> - can be a ref or <code></code>
1524         # need to extract text
1525         my $par = go_ahead( $rstr, 'C', $closing );
1526
1527         ## clean-up of the link target
1528         my $text = depod( $par );
1529
1530         ### my $x = $par =~ /[BI]</ ? 'yes' : 'no' ;
1531         ### print STDERR "-->call emit_C($par) lev=$lev, par with BI=$x\n";
1532
1533         $res = emit_C( $text, $lev > 1 || ($par =~ /[BI]</) );
1534
1535     } elsif( $func eq 'E' ){
1536         # E<x> - convert to character
1537         $$rstr =~ s/^([^>]*)>//;
1538         my $escape = $1;
1539         $escape =~ s/^(\d+|X[\dA-F]+)$/#$1/i;
1540         $res = "&$escape;";
1541
1542     } elsif( $func eq 'F' ){
1543         # F<filename> - italicize
1544         $res = '<em class="file">' . process_text1( $lev, $rstr ) . '</em>';
1545
1546     } elsif( $func eq 'I' ){
1547         # I<text> - italicize
1548         $res = '<em>' . process_text1( $lev, $rstr ) . '</em>';
1549
1550     } elsif( $func eq 'L' ){
1551         # L<link> - link
1552         ## L<text|cross-ref> => produce text, use cross-ref for linking
1553         ## L<cross-ref> => make text from cross-ref
1554         ## need to extract text
1555         my $par = go_ahead( $rstr, 'L', $closing );
1556
1557         # some L<>'s that shouldn't be:
1558         # a) full-blown URL's are emitted as-is
1559         if( $par =~ m{^\w+://}s ){
1560             return make_URL_href( $par );
1561         }
1562         # b) C<...> is stripped and treated as C<>
1563         if( $par =~ /^C<(.*)>$/ ){
1564             my $text = depod( $1 );
1565             return emit_C( $text, $lev > 1 || ($par =~ /[BI]</) );
1566         }
1567
1568         # analyze the contents
1569         $par =~ s/\n/ /g;   # undo word-wrapped tags
1570         my $opar = $par;
1571         my $linktext;
1572         if( $par =~ s{^([^|]+)\|}{} ){
1573             $linktext = $1;
1574         }
1575
1576         # make sure sections start with a /
1577         $par =~ s{^"}{/"};
1578
1579         my( $page, $section, $ident );
1580
1581         # check for link patterns
1582         if( $par =~ m{^([^/]+?)/(?!")(.*?)$} ){     # name/ident
1583             # we've got a name/ident (no quotes)
1584             ( $page, $ident ) = ( $1, $2 );
1585             ### print STDERR "--> L<$par> to page $page, ident $ident\n";
1586
1587         } elsif( $par =~ m{^(.*?)/"?(.*?)"?$} ){ # [name]/"section"
1588             # even though this should be a "section", we go for ident first
1589             ( $page, $ident ) = ( $1, $2 );
1590             ### print STDERR "--> L<$par> to page $page, section $section\n";
1591
1592         } elsif( $par =~ /\s/ ){  # this must be a section with missing quotes
1593             ( $page, $section ) = ( '', $par );
1594             ### print STDERR "--> L<$par> to void page, section $section\n";
1595
1596         } else {
1597             ( $page, $section ) = ( $par, '' );
1598             ### print STDERR "--> L<$par> to page $par, void section\n";
1599         }
1600
1601         # now, either $section or $ident is defined. the convoluted logic
1602         # below tries to resolve L<> according to what the user specified.
1603         # failing this, we try to find the next best thing...
1604         my( $url, $ltext, $fid );
1605
1606         RESOLVE: {
1607             if( defined $ident ){
1608                 ## try to resolve $ident as an item
1609                 ( $url, $fid ) = coderef( $page, $ident );
1610                 if( $url ){
1611                     if( ! defined( $linktext ) ){
1612                         $linktext = $ident;
1613                         $linktext .= " in " if $ident && $page;
1614                         $linktext .= "the $page manpage" if $page;
1615                     }
1616                     ###  print STDERR "got coderef url=$url\n";
1617                     last RESOLVE;
1618                 }
1619                 ## no luck: go for a section (auto-quoting!)
1620                 $section = $ident;
1621             }
1622             ## now go for a section
1623             my $htmlsection = htmlify( $section );
1624             $url = page_sect( $page, $htmlsection );
1625             if( $url ){
1626                 if( ! defined( $linktext ) ){
1627                     $linktext = $section;
1628                     $linktext .= " in " if $section && $page;
1629                     $linktext .= "the $page manpage" if $page;
1630                 }
1631                 ### print STDERR "got page/section url=$url\n";
1632                 last RESOLVE;
1633             }
1634             ## no luck: go for an ident
1635             if( $section ){
1636                 $ident = $section;
1637             } else {
1638                 $ident = $page;
1639                 $page  = undef();
1640             }
1641             ( $url, $fid ) = coderef( $page, $ident );
1642             if( $url ){
1643                 if( ! defined( $linktext ) ){
1644                     $linktext = $ident;
1645                     $linktext .= " in " if $ident && $page;
1646                     $linktext .= "the $page manpage" if $page;
1647                 }
1648                 ### print STDERR "got section=>coderef url=$url\n";
1649                 last RESOLVE;
1650             }
1651
1652             # warning; show some text.
1653             $linktext = $opar unless defined $linktext;
1654             warn "$0: $Podfile: cannot resolve L<$opar> in paragraph $Paragraph.\n" unless $Quiet;
1655         }
1656
1657         # now we have a URL or just plain code
1658         $$rstr = $linktext . '>' . $$rstr;
1659         if( defined( $url ) ){
1660             $res = "<a href=\"$url\">" . process_text1( $lev, $rstr ) . '</a>';
1661         } else {
1662             $res = '<em>' . process_text1( $lev, $rstr ) . '</em>';
1663         }
1664
1665     } elsif( $func eq 'S' ){
1666         # S<text> - non-breaking spaces
1667         $res = process_text1( $lev, $rstr );
1668         $res =~ s/ /&nbsp;/g;
1669
1670     } elsif( $func eq 'X' ){
1671         # X<> - ignore
1672         $$rstr =~ s/^[^>]*>//;
1673
1674     } elsif( $func eq 'Z' ){
1675         # Z<> - empty
1676         warn "$0: $Podfile: invalid X<> in paragraph $Paragraph.\n"
1677             unless $$rstr =~ s/^>// or $Quiet;
1678
1679     } else {
1680         my $term = pattern $closing;
1681         while( $$rstr =~ s/\A(.*?)(([BCEFILSXZ])<(<+[^\S\n]+)?|$term)//s ){
1682             # all others: either recurse into new function or
1683             # terminate at closing angle bracket(s)
1684             my $pt = $1;
1685             $pt .= $2 if !$3 &&  $lev == 1;
1686             $res .= $lev == 1 ? pure_text( $pt ) : inIS_text( $pt );
1687             return $res if !$3 && $lev > 1;
1688             if( $3 ){
1689                 $res .= process_text1( $lev, $rstr, $3, closing $4 );
1690             }
1691         }
1692         if( $lev == 1 ){
1693             $res .= pure_text( $$rstr );
1694         } else {
1695             warn "$0: $Podfile: undelimited $func<> in paragraph $Paragraph.\n" unless $Quiet;
1696         }
1697     }
1698     return $res;
1699 }
1700
1701 #
1702 # go_ahead: extract text of an IS (can be nested)
1703 #
1704 sub go_ahead($$$){
1705     my( $rstr, $func, $closing ) = @_;
1706     my $res = '';
1707     my @closing = ($closing);
1708     while( $$rstr =~
1709       s/\A(.*?)(([BCEFILSXZ])<(<+[^\S\n]+)?|@{[pattern $closing[0]]})//s ){
1710         $res .= $1;
1711         unless( $3 ){
1712             shift @closing;
1713             return $res unless @closing;
1714         } else {
1715             unshift @closing, closing $4;
1716         }
1717         $res .= $2;
1718     }
1719     warn "$0: $Podfile: undelimited $func<> in paragraph $Paragraph.\n" unless $Quiet;
1720     return $res;
1721 }
1722
1723 #
1724 # emit_C - output result of C<text>
1725 #    $text is the depod-ed text
1726 #
1727 sub emit_C($;$$){
1728     my( $text, $nocode, $args ) = @_;
1729     $args = '' unless defined $args;
1730     my $res;
1731     my( $url, $fid ) = coderef( undef(), $text );
1732
1733     # need HTML-safe text
1734     my $linktext = html_escape( "$text$args" );
1735
1736     if( defined( $url ) &&
1737         (!defined( $EmittedItem ) || $EmittedItem ne $fid ) ){
1738         $res = "<a href=\"$url\"><code>$linktext</code></a>";
1739     } elsif( 0 && $nocode ){
1740         $res = $linktext;
1741     } else {
1742         $res = "<code>$linktext</code>";
1743     }
1744     return $res;
1745 }
1746
1747 #
1748 # html_escape: make text safe for HTML
1749 #
1750 sub html_escape {
1751     my $rest = $_[0];
1752     $rest   =~ s/&/&amp;/g;
1753     $rest   =~ s/</&lt;/g;
1754     $rest   =~ s/>/&gt;/g;
1755     $rest   =~ s/"/&quot;/g;
1756     # &apos; is only in XHTML, not HTML4.  Be conservative
1757     #$rest   =~ s/'/&apos;/g;
1758     return $rest;
1759 }
1760
1761
1762 #
1763 # dosify - convert filenames to 8.3
1764 #
1765 sub dosify {
1766     my($str) = @_;
1767     return lc($str) if $^O eq 'VMS';     # VMS just needs casing
1768     if ($Is83) {
1769         $str = lc $str;
1770         $str =~ s/(\.\w+)/substr ($1,0,4)/ge;
1771         $str =~ s/(\w+)/substr ($1,0,8)/ge;
1772     }
1773     return $str;
1774 }
1775
1776 #
1777 # page_sect - make a URL from the text of a L<>
1778 #
1779 sub page_sect($$) {
1780     my( $page, $section ) = @_;
1781     my( $linktext, $page83, $link);     # work strings
1782
1783     # check if we know that this is a section in this page
1784     if (!defined $Pages{$page} && defined $Sections{$page}) {
1785         $section = $page;
1786         $page = "";
1787         ### print STDERR "reset page='', section=$section\n";
1788     }
1789
1790     $page83=dosify($page);
1791     $page=$page83 if (defined $Pages{$page83});
1792     if ($page eq "") {
1793         $link = "#" . anchorify( $section );
1794     } elsif ( $page =~ /::/ ) {
1795         $page =~ s,::,/,g;
1796         # Search page cache for an entry keyed under the html page name,
1797         # then look to see what directory that page might be in.  NOTE:
1798         # this will only find one page. A better solution might be to produce
1799         # an intermediate page that is an index to all such pages.
1800         my $page_name = $page ;
1801         $page_name =~ s,^.*/,,s ;
1802         if ( defined( $Pages{ $page_name } ) &&
1803              $Pages{ $page_name } =~ /([^:]*$page)\.(?:pod|pm):/
1804            ) {
1805             $page = $1 ;
1806         }
1807         else {
1808             # NOTE: This branch assumes that all A::B pages are located in
1809             # $Htmlroot/A/B.html . This is often incorrect, since they are
1810             # often in $Htmlroot/lib/A/B.html or such like. Perhaps we could
1811             # analyze the contents of %Pages and figure out where any
1812             # cousins of A::B are, then assume that.  So, if A::B isn't found,
1813             # but A::C is found in lib/A/C.pm, then A::B is assumed to be in
1814             # lib/A/B.pm. This is also limited, but it's an improvement.
1815             # Maybe a hints file so that the links point to the correct places
1816             # nonetheless?
1817
1818         }
1819         $link = "$Htmlroot/$page.html";
1820         $link .= "#" . anchorify( $section ) if ($section);
1821     } elsif (!defined $Pages{$page}) {
1822         $link = "";
1823     } else {
1824         $section = anchorify( $section ) if $section ne "";
1825         ### print STDERR "...section=$section\n";
1826
1827         # if there is a directory by the name of the page, then assume that an
1828         # appropriate section will exist in the subdirectory
1829 #       if ($section ne "" && $Pages{$page} =~ /([^:]*[^(\.pod|\.pm)]):/) {
1830         if ($section ne "" && $Pages{$page} =~ /([^:]*(?<!\.pod)(?<!\.pm)):/) {
1831             $link = "$Htmlroot/$1/$section.html";
1832             ### print STDERR "...link=$link\n";
1833
1834         # since there is no directory by the name of the page, the section will
1835         # have to exist within a .html of the same name.  thus, make sure there
1836         # is a .pod or .pm that might become that .html
1837         } else {
1838             $section = "#$section" if $section;
1839             ### print STDERR "...section=$section\n";
1840
1841             # check if there is a .pod with the page name.
1842             # for L<Foo>, Foo.(pod|pm) is preferred to A/Foo.(pod|pm)
1843             if ($Pages{$page} =~ /([^:]*)\.(?:pod|pm):/) {
1844                 $link = "$Htmlroot/$1.html$section";
1845             } else {
1846                 $link = "";
1847             }
1848         }
1849     }
1850
1851     if ($link) {
1852         # Here, we take advantage of the knowledge that $Htmlfileurl ne ''
1853         # implies $Htmlroot eq ''. This means that the link in question
1854         # needs a prefix of $Htmldir if it begins with '/'. The test for
1855         # the initial '/' is done to avoid '#'-only links, and to allow
1856         # for other kinds of links, like file:, ftp:, etc.
1857         my $url ;
1858         if (  $Htmlfileurl ne '' ) {
1859             $link = "$Htmldir$link" if $link =~ m{^/}s;
1860             $url = relativize_url( $link, $Htmlfileurl );
1861 # print( "  b: [$link,$Htmlfileurl,$url]\n" );
1862         }
1863         else {
1864             $url = $link ;
1865         }
1866         return $url;
1867
1868     } else {
1869         return undef();
1870     }
1871 }
1872
1873 #
1874 # relativize_url - convert an absolute URL to one relative to a base URL.
1875 # Assumes both end in a filename.
1876 #
1877 sub relativize_url {
1878     my ($dest,$source) = @_ ;
1879
1880     my ($dest_volume,$dest_directory,$dest_file) =
1881         File::Spec::Unix->splitpath( $dest ) ;
1882     $dest = File::Spec::Unix->catpath( $dest_volume, $dest_directory, '' ) ;
1883
1884     my ($source_volume,$source_directory,$source_file) =
1885         File::Spec::Unix->splitpath( $source ) ;
1886     $source = File::Spec::Unix->catpath( $source_volume, $source_directory, '' ) ;
1887
1888     my $rel_path = '' ;
1889     if ( $dest ne '' ) {
1890        $rel_path = File::Spec::Unix->abs2rel( $dest, $source ) ;
1891     }
1892
1893     if ( $rel_path ne ''                &&
1894          substr( $rel_path, -1 ) ne '/' &&
1895          substr( $dest_file, 0, 1 ) ne '#'
1896         ) {
1897         $rel_path .= "/$dest_file" ;
1898     }
1899     else {
1900         $rel_path .= "$dest_file" ;
1901     }
1902
1903     return $rel_path ;
1904 }
1905
1906
1907 #
1908 # coderef - make URL from the text of a C<>
1909 #
1910 sub coderef($$){
1911     my( $page, $item ) = @_;
1912     my( $url );
1913
1914     my $fid = fragment_id( $item );
1915     if( defined( $page ) && $page ne "" ){
1916         # we have been given a $page...
1917         $page =~ s{::}{/}g;
1918
1919         # Do we take it? Item could be a section!
1920         my $base = $Items{$fid} || "";
1921         $base =~ s{[^/]*/}{};
1922         if( $base ne "$page.html" ){
1923             ###   print STDERR "coderef( $page, $item ): items{$fid} = $Items{$fid} = $base => discard page!\n";
1924             $page = undef();
1925         }
1926
1927     } else {
1928         # no page - local items precede cached items
1929         if( defined( $fid ) ){
1930             if(  exists $Local_Items{$fid} ){
1931                 $page = $Local_Items{$fid};
1932             } else {
1933                 $page = $Items{$fid};
1934             }
1935         }
1936     }
1937
1938     # if there was a pod file that we found earlier with an appropriate
1939     # =item directive, then create a link to that page.
1940     if( defined $page ){
1941         if( $page ){
1942             if( exists $Pages{$page} and $Pages{$page} =~ /([^:.]*)\.[^:]*:/){
1943                 $page = $1 . '.html';
1944             }
1945             my $link = "$Htmlroot/$page#item_" . anchorify($fid);
1946
1947             # Here, we take advantage of the knowledge that $Htmlfileurl
1948             # ne '' implies $Htmlroot eq ''.
1949             if (  $Htmlfileurl ne '' ) {
1950                 $link = "$Htmldir$link" ;
1951                 $url = relativize_url( $link, $Htmlfileurl ) ;
1952             } else {
1953                 $url = $link ;
1954             }
1955         } else {
1956             $url = "#item_" . anchorify($fid);
1957         }
1958
1959         confess "url has space: $url" if $url =~ /"[^"]*\s[^"]*"/;
1960     }
1961     return( $url, $fid );
1962 }
1963
1964
1965
1966 #
1967 # Adapted from Nick Ing-Simmons' PodToHtml package.
1968 sub relative_url {
1969     my $source_file = shift ;
1970     my $destination_file = shift;
1971
1972     my $source = URI::file->new_abs($source_file);
1973     my $uo = URI::file->new($destination_file,$source)->abs;
1974     return $uo->rel->as_string;
1975 }
1976
1977
1978 #
1979 # finish_list - finish off any pending HTML lists.  this should be called
1980 # after the entire pod file has been read and converted.
1981 #
1982 sub finish_list {
1983     while ($Listlevel > 0) {
1984         print HTML "</dl>\n";
1985         $Listlevel--;
1986     }
1987 }
1988
1989 #
1990 # htmlify - converts a pod section specification to a suitable section
1991 # specification for HTML. Note that we keep spaces and special characters
1992 # except ", ? (Netscape problem) and the hyphen (writer's problem...).
1993 #
1994 sub htmlify {
1995     my( $heading) = @_;
1996     $heading =~ s/(\s+)/ /g;
1997     $heading =~ s/\s+\Z//;
1998     $heading =~ s/\A\s+//;
1999     # The hyphen is a disgrace to the English language.
2000     $heading =~ s/[-"?]//g;
2001     $heading = lc( $heading );
2002     return $heading;
2003 }
2004
2005 #
2006 # similar to htmlify, but turns non-alphanumerics into underscores
2007 #
2008 sub anchorify {
2009     my ($anchor) = @_;
2010     $anchor = htmlify($anchor);
2011     $anchor =~ s/\W/_/g;
2012     return $anchor;
2013 }
2014
2015 #
2016 # depod - convert text by eliminating all interior sequences
2017 # Note: can be called with copy or modify semantics
2018 #
2019 my %E2c;
2020 $E2c{lt}     = '<';
2021 $E2c{gt}     = '>';
2022 $E2c{sol}    = '/';
2023 $E2c{verbar} = '|';
2024 $E2c{amp}    = '&'; # in Tk's pods
2025
2026 sub depod1($;$$);
2027
2028 sub depod($){
2029     my $string;
2030     if( ref( $_[0] ) ){
2031         $string =  ${$_[0]};
2032         ${$_[0]} = depod1( \$string );
2033     } else {
2034         $string =  $_[0];
2035         depod1( \$string );
2036     }
2037 }
2038
2039 sub depod1($;$$){
2040   my( $rstr, $func, $closing ) = @_;
2041   my $res = '';
2042   return $res unless defined $$rstr;
2043   if( ! defined( $func ) ){
2044       # skip to next begin of an interior sequence
2045       while( $$rstr =~ s/\A(.*?)([BCEFILSXZ])<(<+[^\S\n]+)?//s ){
2046          # recurse into its text
2047           $res .= $1 . depod1( $rstr, $2, closing $3);
2048       }
2049       $res .= $$rstr;
2050   } elsif( $func eq 'E' ){
2051       # E<x> - convert to character
2052       $$rstr =~ s/^([^>]*)>//;
2053       $res .= $E2c{$1} || "";
2054   } elsif( $func eq 'X' ){
2055       # X<> - ignore
2056       $$rstr =~ s/^[^>]*>//;
2057   } elsif( $func eq 'Z' ){
2058       # Z<> - empty
2059       $$rstr =~ s/^>//;
2060   } else {
2061       # all others: either recurse into new function or
2062       # terminate at closing angle bracket
2063       my $term = pattern $closing;
2064       while( $$rstr =~ s/\A(.*?)(([BCEFILSXZ])<(<+[^\S\n]+)?|$term)//s ){
2065           $res .= $1;
2066           last unless $3;
2067           $res .= depod1( $rstr, $3, closing $4 );
2068       }
2069       ## If we're here and $2 ne '>': undelimited interior sequence.
2070       ## Ignored, as this is called without proper indication of where we are.
2071       ## Rely on process_text to produce diagnostics.
2072   }
2073   return $res;
2074 }
2075
2076 #
2077 # fragment_id - construct a fragment identifier from:
2078 #   a) =item text
2079 #   b) contents of C<...>
2080 #
2081 my @HC;
2082 sub fragment_id {
2083     my $text = shift();
2084     $text =~ s/\s+\Z//s;
2085     if( $text ){
2086         # a method or function?
2087         return $1 if $text =~ /(\w+)\s*\(/;
2088         return $1 if $text =~ /->\s*(\w+)\s*\(?/;
2089
2090         # a variable name?
2091         return $1 if $text =~ /^([\$\@%*]\S+)/;
2092
2093         # some pattern matching operator?
2094         return $1 if $text =~ m|^(\w+/).*/\w*$|;
2095
2096         # fancy stuff... like "do { }"
2097         return $1 if $text =~ m|^(\w+)\s*{.*}$|;
2098
2099         # honour the perlfunc manpage: func [PAR[,[ ]PAR]...]
2100         # and some funnies with ... Module ...
2101         return $1 if $text =~ m{^([a-z\d_]+)(\s+[A-Z,/& ][A-Z\d,/& ]*)?$};
2102         return $1 if $text =~ m{^([a-z\d]+)\s+Module(\s+[A-Z\d,/& ]+)?$};
2103
2104         # text? normalize!
2105         $text =~ s/\s+/_/sg;
2106         $text =~ s{(\W)}{
2107          defined( $HC[ord($1)] ) ? $HC[ord($1)]
2108                  : ( $HC[ord($1)] = sprintf( "%%%02X", ord($1) ) ) }gxe;
2109         $text = substr( $text, 0, 50 );
2110     } else {
2111         return undef();
2112     }
2113 }
2114
2115 #
2116 # make_URL_href - generate HTML href from URL
2117 # Special treatment for CGI queries.
2118 #
2119 sub make_URL_href($){
2120     my( $url ) = @_;
2121     if( $url !~
2122         s{^(http:[-\w/#~:.+=&%@!]+)(\?.*)$}{<a href="$1$2">$1</a>}i ){
2123         $url = "<a href=\"$url\">$url</a>";
2124     }
2125     return $url;
2126 }
2127
2128 1;