1 #####################################################################
3 # The Perl::Tidy::HtmlWriter class writes a copy of the input stream in html
5 #####################################################################
7 package Perl::Tidy::HtmlWriter;
10 our $VERSION = '20210717';
24 $missing_html_entities
28 # replace unsafe characters with HTML entity representation if HTML::Entities
30 #{ eval "use HTML::Entities"; $missing_html_entities = $@; }
33 if ( !eval { require HTML::Entities; 1 } ) {
34 $missing_html_entities = $@ ? $@ : 1;
36 if ( !eval { require Pod::Html; 1 } ) {
37 $missing_pod_html = $@ ? $@ : 1;
43 # Catch any undefined sub calls so that we are sure to get
44 # some diagnostic information. This sub should never be called
45 # except for a programming error.
47 return if ( $AUTOLOAD =~ /\bDESTROY$/ );
48 my ( $pkg, $fname, $lno ) = caller();
49 my $my_package = __PACKAGE__;
51 ======================================================================
52 Error detected in package '$my_package', version $VERSION
53 Received unexpected AUTOLOAD call for sub '$AUTOLOAD'
54 Called from package: '$pkg'
55 Called from File '$fname' at line '$lno'
56 This error is probably due to a recent programming change
57 ======================================================================
64 # required to avoid call to AUTOLOAD in some versions of perl
69 my ( $class, @args ) = @_;
75 html_toc_extension => undef,
76 html_src_extension => undef,
78 my %args = ( %defaults, @args );
80 my $input_file = $args{input_file};
81 my $html_file = $args{html_file};
82 my $extension = $args{extension};
83 my $html_toc_extension = $args{html_toc_extension};
84 my $html_src_extension = $args{html_src_extension};
86 my $html_file_opened = 0;
88 ( $html_fh, my $html_filename ) =
89 Perl::Tidy::streamhandle( $html_file, 'w' );
91 Perl::Tidy::Warn("can't open $html_file: $!\n");
94 $html_file_opened = 1;
96 if ( !$input_file || $input_file eq '-' || ref($input_file) ) {
97 $input_file = "NONAME";
100 # write the table of contents to a string
102 my $html_toc_fh = Perl::Tidy::IOScalar->new( \$toc_string, 'w' );
105 my @pre_string_stack;
106 if ( $rOpts->{'html-pre-only'} ) {
108 # pre section goes directly to the output stream
109 $html_pre_fh = $html_fh;
110 $html_pre_fh->print( <<"PRE_END");
116 # pre section go out to a temporary string
118 $html_pre_fh = Perl::Tidy::IOScalar->new( \$pre_string, 'w' );
119 push @pre_string_stack, \$pre_string;
122 # pod text gets diverted if the 'pod2html' is used
125 if ( $rOpts->{'pod2html'} ) {
126 if ( $rOpts->{'html-pre-only'} ) {
127 undef $rOpts->{'pod2html'};
130 ##eval "use Pod::Html";
132 if ($missing_pod_html) {
134 "unable to find Pod::Html; cannot use pod2html\n-npod disables this message\n"
136 undef $rOpts->{'pod2html'};
139 $html_pod_fh = Perl::Tidy::IOScalar->new( \$pod_string, 'w' );
146 if ( $rOpts->{'frames'} ) {
147 unless ($extension) {
149 "cannot use frames without a specified output extension; ignoring -frm\n"
151 undef $rOpts->{'frames'};
154 $toc_filename = $input_file . $html_toc_extension . $extension;
155 $src_filename = $input_file . $html_src_extension . $extension;
159 # ----------------------------------------------------------
160 # Output is now directed as follows:
161 # html_toc_fh <-- table of contents items
162 # html_pre_fh <-- the <pre> section of formatted code, except:
163 # html_pod_fh <-- pod goes here with the pod2html option
164 # ----------------------------------------------------------
166 my $title = $rOpts->{'title'};
168 ( $title, my $path ) = fileparse($input_file);
170 my $toc_item_count = 0;
171 my $in_toc_package = "";
174 _input_file => $input_file, # name of input file
175 _title => $title, # title, unescaped
176 _html_file => $html_file, # name of .html output file
177 _toc_filename => $toc_filename, # for frames option
178 _src_filename => $src_filename, # for frames option
179 _html_file_opened => $html_file_opened, # a flag
180 _html_fh => $html_fh, # the output stream
181 _html_pre_fh => $html_pre_fh, # pre section goes here
182 _rpre_string_stack => \@pre_string_stack, # stack of pre sections
183 _html_pod_fh => $html_pod_fh, # pod goes here if pod2html
184 _rpod_string => \$pod_string, # string holding pod
185 _pod_cut_count => 0, # how many =cut's?
186 _html_toc_fh => $html_toc_fh, # fh for table of contents
187 _rtoc_string => \$toc_string, # string holding toc
188 _rtoc_item_count => \$toc_item_count, # how many toc items
189 _rin_toc_package => \$in_toc_package, # package name
190 _rtoc_name_count => {}, # hash to track unique names
191 _rpackage_stack => [], # stack to check for package
193 _rlast_level => \$last_level, # brace indentation level
200 # returns true if close works, false if not
201 # failure probably means there is no close method
202 return eval { $object->close(); 1 };
207 # Add an item to the html table of contents.
208 # This is called even if no table of contents is written,
209 # because we still want to put the anchors in the <pre> text.
210 # We are given an anchor name and its type; types are:
211 # 'package', 'sub', '__END__', '__DATA__', 'EOF'
212 # There must be an 'EOF' call at the end to wrap things up.
213 my ( $self, $name, $type ) = @_;
214 my $html_toc_fh = $self->{_html_toc_fh};
215 my $html_pre_fh = $self->{_html_pre_fh};
216 my $rtoc_name_count = $self->{_rtoc_name_count};
217 my $rtoc_item_count = $self->{_rtoc_item_count};
218 my $rlast_level = $self->{_rlast_level};
219 my $rin_toc_package = $self->{_rin_toc_package};
220 my $rpackage_stack = $self->{_rpackage_stack};
222 # packages contain sublists of subs, so to avoid errors all package
223 # items are written and finished with the following routines
224 my $end_package_list = sub {
225 if ( ${$rin_toc_package} ) {
226 $html_toc_fh->print("</ul>\n</li>\n");
227 ${$rin_toc_package} = "";
231 my $start_package_list = sub {
232 my ( $unique_name, $package ) = @_;
233 if ( ${$rin_toc_package} ) { $end_package_list->() }
234 $html_toc_fh->print(<<EOM);
235 <li><a href=\"#$unique_name\">package $package</a>
238 ${$rin_toc_package} = $package;
241 # start the table of contents on the first item
242 unless ( ${$rtoc_item_count} ) {
244 # but just quit if we hit EOF without any other entries
245 # in this case, there will be no toc
246 return if ( $type eq 'EOF' );
247 $html_toc_fh->print( <<"TOC_END");
248 <!-- BEGIN CODE INDEX --><a name="code-index"></a>
252 ${$rtoc_item_count}++;
254 # make a unique anchor name for this location:
255 # - packages get a 'package-' prefix
256 # - subs use their names
257 my $unique_name = $name;
258 if ( $type eq 'package' ) { $unique_name = "package-$name" }
260 # append '-1', '-2', etc if necessary to make unique; this will
261 # be unique because subs and packages cannot have a '-'
262 if ( my $count = $rtoc_name_count->{ lc $unique_name }++ ) {
263 $unique_name .= "-$count";
266 # - all names get terminal '-' if pod2html is used, to avoid
267 # conflicts with anchor names created by pod2html
268 if ( $rOpts->{'pod2html'} ) { $unique_name .= '-' }
270 # start/stop lists of subs
271 if ( $type eq 'sub' ) {
272 my $package = $rpackage_stack->[ ${$rlast_level} ];
273 unless ($package) { $package = 'main' }
275 # if we're already in a package/sub list, be sure its the right
276 # package or else close it
277 if ( ${$rin_toc_package} && ${$rin_toc_package} ne $package ) {
278 $end_package_list->();
281 # start a package/sub list if necessary
282 unless ( ${$rin_toc_package} ) {
283 $start_package_list->( $unique_name, $package );
287 # now write an entry in the toc for this item
288 if ( $type eq 'package' ) {
289 $start_package_list->( $unique_name, $name );
291 elsif ( $type eq 'sub' ) {
292 $html_toc_fh->print("<li><a href=\"#$unique_name\">$name</a></li>\n");
295 $end_package_list->();
296 $html_toc_fh->print("<li><a href=\"#$unique_name\">$name</a></li>\n");
299 # write the anchor in the <pre> section
300 $html_pre_fh->print("<a name=\"$unique_name\"></a>");
302 # end the table of contents, if any, on the end of file
303 if ( $type eq 'EOF' ) {
304 $html_toc_fh->print( <<"TOC_END");
306 <!-- END CODE INDEX -->
314 # This is the official list of tokens which may be identified by the
315 # user. Long names are used as getopt keys. Short names are
316 # convenient short abbreviations for specifying input. Short names
317 # somewhat resemble token type characters, but are often different
318 # because they may only be alphanumeric, to allow command line
319 # input. Also, note that because of case insensitivity of html,
320 # this table must be in a single case only (I've chosen to use all
322 # When adding NEW_TOKENS: update this hash table
323 # short names => long names
324 %short_to_long_names = (
334 'pu' => 'punctuation',
337 'h' => 'here-doc-target',
338 'hh' => 'here-doc-text',
345 # Now we have to map actual token types into one of the above short
346 # names; any token types not mapped will get 'punctuation'
349 # The values of this hash table correspond to the keys of the
350 # previous hash table.
351 # The keys of this hash table are token types and can be seen
352 # by running with --dump-token-types (-dtt).
354 # When adding NEW_TOKENS: update this hash table
355 # $type => $short_name
356 %token_short_names = (
381 # These token types will all be called identifiers for now
382 # FIXME: could separate user defined modules as separate type
383 my @identifier = qw< i t U C Y Z G :: CORE::>;
384 @token_short_names{@identifier} = ('i') x scalar(@identifier);
386 # These token types will be called 'structure'
387 my @structure = qw< { } >;
388 @token_short_names{@structure} = ('s') x scalar(@structure);
390 # OLD NOTES: save for reference
391 # Any of these could be added later if it would be useful.
392 # For now, they will by default become punctuation
393 # my @list = qw< L R [ ] >;
394 # @token_long_names{@list} = ('non-structure') x scalar(@list);
397 # / /= * *= ** **= + += - -= % %= = ++ -- << <<= >> >>= pp p m mm
399 # @token_long_names{@list} = ('math') x scalar(@list);
401 # my @list = qw" & &= ~ ~= ^ ^= | |= ";
402 # @token_long_names{@list} = ('bit') x scalar(@list);
404 # my @list = qw" == != < > <= <=> ";
405 # @token_long_names{@list} = ('numerical-comparison') x scalar(@list);
407 # my @list = qw" && || ! &&= ||= //= ";
408 # @token_long_names{@list} = ('logical') x scalar(@list);
410 # my @list = qw" . .= =~ !~ x x= ";
411 # @token_long_names{@list} = ('string-operators') x scalar(@list);
414 # my @list = qw" .. -> <> ... \ ? ";
415 # @token_long_names{@list} = ('misc-operators') x scalar(@list);
419 sub make_getopt_long_names {
420 my ( $class, $rgetopt_names ) = @_;
421 while ( my ( $short_name, $name ) = each %short_to_long_names ) {
422 push @{$rgetopt_names}, "html-color-$name=s";
423 push @{$rgetopt_names}, "html-italic-$name!";
424 push @{$rgetopt_names}, "html-bold-$name!";
426 push @{$rgetopt_names}, "html-color-background=s";
427 push @{$rgetopt_names}, "html-linked-style-sheet=s";
428 push @{$rgetopt_names}, "nohtml-style-sheets";
429 push @{$rgetopt_names}, "html-pre-only";
430 push @{$rgetopt_names}, "html-line-numbers";
431 push @{$rgetopt_names}, "html-entities!";
432 push @{$rgetopt_names}, "stylesheet";
433 push @{$rgetopt_names}, "html-table-of-contents!";
434 push @{$rgetopt_names}, "pod2html!";
435 push @{$rgetopt_names}, "frames!";
436 push @{$rgetopt_names}, "html-toc-extension=s";
437 push @{$rgetopt_names}, "html-src-extension=s";
439 # Pod::Html parameters:
440 push @{$rgetopt_names}, "backlink=s";
441 push @{$rgetopt_names}, "cachedir=s";
442 push @{$rgetopt_names}, "htmlroot=s";
443 push @{$rgetopt_names}, "libpods=s";
444 push @{$rgetopt_names}, "podpath=s";
445 push @{$rgetopt_names}, "podroot=s";
446 push @{$rgetopt_names}, "title=s";
448 # Pod::Html parameters with leading 'pod' which will be removed
449 # before the call to Pod::Html
450 push @{$rgetopt_names}, "podquiet!";
451 push @{$rgetopt_names}, "podverbose!";
452 push @{$rgetopt_names}, "podrecurse!";
453 push @{$rgetopt_names}, "podflush";
454 push @{$rgetopt_names}, "podheader!";
455 push @{$rgetopt_names}, "podindex!";
459 sub make_abbreviated_names {
461 # We're appending things like this to the expansion list:
462 # 'hcc' => [qw(html-color-comment)],
463 # 'hck' => [qw(html-color-keyword)],
465 my ( $class, $rexpansion ) = @_;
467 # abbreviations for color/bold/italic properties
468 while ( my ( $short_name, $long_name ) = each %short_to_long_names ) {
469 ${$rexpansion}{"hc$short_name"} = ["html-color-$long_name"];
470 ${$rexpansion}{"hb$short_name"} = ["html-bold-$long_name"];
471 ${$rexpansion}{"hi$short_name"} = ["html-italic-$long_name"];
472 ${$rexpansion}{"nhb$short_name"} = ["nohtml-bold-$long_name"];
473 ${$rexpansion}{"nhi$short_name"} = ["nohtml-italic-$long_name"];
476 # abbreviations for all other html options
477 ${$rexpansion}{"hcbg"} = ["html-color-background"];
478 ${$rexpansion}{"pre"} = ["html-pre-only"];
479 ${$rexpansion}{"toc"} = ["html-table-of-contents"];
480 ${$rexpansion}{"ntoc"} = ["nohtml-table-of-contents"];
481 ${$rexpansion}{"nnn"} = ["html-line-numbers"];
482 ${$rexpansion}{"hent"} = ["html-entities"];
483 ${$rexpansion}{"nhent"} = ["nohtml-entities"];
484 ${$rexpansion}{"css"} = ["html-linked-style-sheet"];
485 ${$rexpansion}{"nss"} = ["nohtml-style-sheets"];
486 ${$rexpansion}{"ss"} = ["stylesheet"];
487 ${$rexpansion}{"pod"} = ["pod2html"];
488 ${$rexpansion}{"npod"} = ["nopod2html"];
489 ${$rexpansion}{"frm"} = ["frames"];
490 ${$rexpansion}{"nfrm"} = ["noframes"];
491 ${$rexpansion}{"text"} = ["html-toc-extension"];
492 ${$rexpansion}{"sext"} = ["html-src-extension"];
498 # This will be called once after options have been parsed
499 # Note that we are defining the package variable $rOpts here:
500 ( my $class, $rOpts ) = @_;
502 # X11 color names for default settings that seemed to look ok
503 # (these color names are only used for programming clarity; the hex
504 # numbers are actually written)
505 use constant ForestGreen => "#228B22";
506 use constant SaddleBrown => "#8B4513";
507 use constant magenta4 => "#8B008B";
508 use constant IndianRed3 => "#CD5555";
509 use constant DeepSkyBlue4 => "#00688B";
510 use constant MediumOrchid3 => "#B452CD";
511 use constant black => "#000000";
512 use constant white => "#FFFFFF";
513 use constant red => "#FF0000";
515 # set default color, bold, italic properties
516 # anything not listed here will be given the default (punctuation) color --
517 # these types currently not listed and get default: ws pu s sc cm co p
518 # When adding NEW_TOKENS: add an entry here if you don't want defaults
520 # set_default_properties( $short_name, default_color, bold?, italic? );
521 set_default_properties( 'c', ForestGreen, 0, 0 );
522 set_default_properties( 'pd', ForestGreen, 0, 1 );
523 set_default_properties( 'k', magenta4, 1, 0 ); # was SaddleBrown
524 set_default_properties( 'q', IndianRed3, 0, 0 );
525 set_default_properties( 'hh', IndianRed3, 0, 1 );
526 set_default_properties( 'h', IndianRed3, 1, 0 );
527 set_default_properties( 'i', DeepSkyBlue4, 0, 0 );
528 set_default_properties( 'w', black, 0, 0 );
529 set_default_properties( 'n', MediumOrchid3, 0, 0 );
530 set_default_properties( 'v', MediumOrchid3, 0, 0 );
531 set_default_properties( 'j', IndianRed3, 1, 0 );
532 set_default_properties( 'm', red, 1, 0 );
534 set_default_color( 'html-color-background', white );
535 set_default_color( 'html-color-punctuation', black );
537 # setup property lookup tables for tokens based on their short names
538 # every token type has a short name, and will use these tables
539 # to do the html markup
540 while ( my ( $short_name, $long_name ) = each %short_to_long_names ) {
541 $html_color{$short_name} = $rOpts->{"html-color-$long_name"};
542 $html_bold{$short_name} = $rOpts->{"html-bold-$long_name"};
543 $html_italic{$short_name} = $rOpts->{"html-italic-$long_name"};
546 # write style sheet to STDOUT and die if requested
547 if ( defined( $rOpts->{'stylesheet'} ) ) {
548 write_style_sheet_file('-');
552 # make sure user gives a file name after -css
553 if ( defined( $rOpts->{'html-linked-style-sheet'} ) ) {
554 $css_linkname = $rOpts->{'html-linked-style-sheet'};
555 if ( $css_linkname =~ /^-/ ) {
556 Perl::Tidy::Die("You must specify a valid filename after -css\n");
561 if ( $css_linkname && $rOpts->{'nohtml-style-sheets'} ) {
562 $rOpts->{'nohtml-style-sheets'} = 0;
564 "You can't specify both -css and -nss; -nss ignored\n");
567 # write a style sheet file if necessary
570 # if the selected filename exists, don't write, because user may
571 # have done some work by hand to create it; use backup name instead
572 # Also, this will avoid a potential disaster in which the user
573 # forgets to specify the style sheet, like this:
574 # perltidy -html -css myfile1.pl myfile2.pl
575 # This would cause myfile1.pl to parsed as the style sheet by GetOpts
576 my $css_filename = $css_linkname;
577 unless ( -e $css_filename ) {
578 write_style_sheet_file($css_filename);
581 $missing_html_entities = 1 unless $rOpts->{'html-entities'};
585 sub write_style_sheet_file {
587 my $css_filename = shift;
589 unless ( $fh = IO::File->new("> $css_filename") ) {
590 Perl::Tidy::Die("can't open $css_filename: $!\n");
592 write_style_sheet_data($fh);
597 sub write_style_sheet_data {
599 # write the style sheet data to an open file handle
602 my $bg_color = $rOpts->{'html-color-background'};
603 my $text_color = $rOpts->{'html-color-punctuation'};
605 # pre-bgcolor is new, and may not be defined
606 my $pre_bg_color = $rOpts->{'html-pre-color-background'};
607 $pre_bg_color = $bg_color unless $pre_bg_color;
610 /* default style sheet generated by perltidy */
611 body {background: $bg_color; color: $text_color}
612 pre { color: $text_color;
613 background: $pre_bg_color;
614 font-family: courier;
619 foreach my $short_name ( sort keys %short_to_long_names ) {
620 my $long_name = $short_to_long_names{$short_name};
622 my $abbrev = '.' . $short_name;
623 if ( length($short_name) == 1 ) { $abbrev .= ' ' } # for alignment
624 my $color = $html_color{$short_name};
625 if ( !defined($color) ) { $color = $text_color }
626 $fh->print("$abbrev \{ color: $color;");
628 if ( $html_bold{$short_name} ) {
629 $fh->print(" font-weight:bold;");
632 if ( $html_italic{$short_name} ) {
633 $fh->print(" font-style:italic;");
635 $fh->print("} /* $long_name */\n");
640 sub set_default_color {
642 # make sure that options hash $rOpts->{$key} contains a valid color
643 my ( $key, $color ) = @_;
644 if ( $rOpts->{$key} ) { $color = $rOpts->{$key} }
645 $rOpts->{$key} = check_RGB($color);
651 # if color is a 6 digit hex RGB value, prepend a #, otherwise
652 # assume that it is a valid ascii color name
654 if ( $color =~ /^[0-9a-fA-F]{6,6}$/ ) { $color = "#$color" }
658 sub set_default_properties {
659 my ( $short_name, $color, $bold, $italic ) = @_;
661 set_default_color( "html-color-$short_to_long_names{$short_name}", $color );
663 $key = "html-bold-$short_to_long_names{$short_name}";
664 $rOpts->{$key} = ( defined $rOpts->{$key} ) ? $rOpts->{$key} : $bold;
665 $key = "html-italic-$short_to_long_names{$short_name}";
666 $rOpts->{$key} = ( defined $rOpts->{$key} ) ? $rOpts->{$key} : $italic;
672 # Use Pod::Html to process the pod and make the page
673 # then merge the perltidy code sections into it.
674 # return 1 if success, 0 otherwise
675 my ( $self, $pod_string, $css_string, $toc_string, $rpre_string_stack ) =
677 my $input_file = $self->{_input_file};
678 my $title = $self->{_title};
679 my $success_flag = 0;
681 # don't try to use pod2html if no pod
682 unless ($pod_string) {
683 return $success_flag;
686 # Pod::Html requires a real temporary filename
687 my ( $fh_tmp, $tmpfile ) = File::Temp::tempfile();
690 "unable to open temporary file $tmpfile; cannot use pod2html\n");
691 return $success_flag;
694 #------------------------------------------------------------------
695 # Warning: a temporary file is open; we have to clean up if
696 # things go bad. From here on all returns should be by going to
697 # RETURN so that the temporary file gets unlinked.
698 #------------------------------------------------------------------
700 # write the pod text to the temporary file
701 $fh_tmp->print($pod_string);
704 # Hand off the pod to pod2html.
705 # Note that we can use the same temporary filename for input and output
706 # because of the way pod2html works.
710 push @args, "--infile=$tmpfile", "--outfile=$tmpfile", "--title=$title";
712 # Flags with string args:
713 # "backlink=s", "cachedir=s", "htmlroot=s", "libpods=s",
714 # "podpath=s", "podroot=s"
715 # Note: -css=s is handled by perltidy itself
716 foreach my $kw (qw(backlink cachedir htmlroot libpods podpath podroot))
718 if ( $rOpts->{$kw} ) { push @args, "--$kw=$rOpts->{$kw}" }
721 # Toggle switches; these have extra leading 'pod'
722 # "header!", "index!", "recurse!", "quiet!", "verbose!"
723 foreach my $kw (qw(podheader podindex podrecurse podquiet podverbose)) {
724 my $kwd = $kw; # allows us to strip 'pod'
725 if ( $rOpts->{$kw} ) { $kwd =~ s/^pod//; push @args, "--$kwd" }
726 elsif ( defined( $rOpts->{$kw} ) ) {
728 push @args, "--no$kwd";
734 if ( $rOpts->{$kw} ) { $kw =~ s/^pod//; push @args, "--$kw" }
736 # Must clean up if pod2html dies (it can);
737 # Be careful not to overwrite callers __DIE__ routine
738 local $SIG{__DIE__} = sub {
739 unlink $tmpfile if -e $tmpfile;
740 Perl::Tidy::Die( $_[0] );
743 Pod::Html::pod2html(@args);
745 $fh_tmp = IO::File->new( $tmpfile, 'r' );
748 # this error shouldn't happen ... we just used this filename
750 "unable to open temporary file $tmpfile; cannot use pod2html\n");
754 my $html_fh = $self->{_html_fh};
760 # This routine will write the html selectively and store the toc
761 my $html_print = sub {
763 $html_fh->print($_) unless ($no_print);
764 if ($in_toc) { push @toc, $_ }
768 # loop over lines of html output from pod2html and merge in
769 # the necessary perltidy html sections
770 my ( $saw_body, $saw_index, $saw_body_end );
773 if ( $rOpts->{'timestamp'} ) {
774 my $date = localtime;
775 $timestamp = "on $date";
777 while ( my $line = $fh_tmp->getline() ) {
779 if ( $line =~ /^\s*<html>\s*$/i ) {
780 ##my $date = localtime;
781 ##$html_print->("<!-- Generated by perltidy on $date -->\n");
782 $html_print->("<!-- Generated by perltidy $timestamp -->\n");
783 $html_print->($line);
786 # Copy the perltidy css, if any, after <body> tag
787 elsif ( $line =~ /^\s*<body.*>\s*$/i ) {
789 $html_print->($css_string) if $css_string;
790 $html_print->($line);
792 # add a top anchor and heading
793 $html_print->("<a name=\"-top-\"></a>\n");
794 $title = escape_html($title);
795 $html_print->("<h1>$title</h1>\n");
798 # check for start of index, old pod2html
799 # before Pod::Html VERSION 1.15_02 it is delimited by comments as:
800 # <!-- INDEX BEGIN -->
806 elsif ( $line =~ /^\s*<!-- INDEX BEGIN -->\s*$/i ) {
809 # when frames are used, an extra table of contents in the
810 # contents panel is confusing, so don't print it
811 $no_print = $rOpts->{'frames'}
812 || !$rOpts->{'html-table-of-contents'};
813 $html_print->("<h2>Doc Index:</h2>\n") if $rOpts->{'frames'};
814 $html_print->($line);
817 # check for start of index, new pod2html
818 # After Pod::Html VERSION 1.15_02 it is delimited as:
822 elsif ( $line =~ /^\s*<ul\s+id="index">/i ) {
826 # when frames are used, an extra table of contents in the
827 # contents panel is confusing, so don't print it
828 $no_print = $rOpts->{'frames'}
829 || !$rOpts->{'html-table-of-contents'};
830 $html_print->("<h2>Doc Index:</h2>\n") if $rOpts->{'frames'};
831 $html_print->($line);
834 # Check for end of index, old pod2html
835 elsif ( $line =~ /^\s*<!-- INDEX END -->\s*$/i ) {
837 $html_print->($line);
839 # Copy the perltidy toc, if any, after the Pod::Html toc
841 $html_print->("<hr />\n") if $rOpts->{'frames'};
842 $html_print->("<h2>Code Index:</h2>\n");
843 ##my @toc = map { $_ .= "\n" } split /\n/, $toc_string;
844 my @toc = map { $_ . "\n" } split /\n/, $toc_string;
851 # must track <ul> depth level for new pod2html
852 elsif ( $line =~ /\s*<ul>\s*$/i && $in_toc eq 'UL' ) {
854 $html_print->($line);
857 # Check for end of index, for new pod2html
858 elsif ( $line =~ /\s*<\/ul>/i && $in_toc eq 'UL' ) {
860 $html_print->($line);
862 # Copy the perltidy toc, if any, after the Pod::Html toc
863 if ( $ul_level <= 0 ) {
866 $html_print->("<hr />\n") if $rOpts->{'frames'};
867 $html_print->("<h2>Code Index:</h2>\n");
868 ##my @toc = map { $_ .= "\n" } split /\n/, $toc_string;
869 my @toc = map { $_ . "\n" } split /\n/, $toc_string;
878 # Copy one perltidy section after each marker
879 elsif ( $line =~ /^(.*)<!-- pERLTIDY sECTION -->(.*)$/ ) {
881 $html_print->($1) if $1;
883 # Intermingle code and pod sections if we saw multiple =cut's.
884 if ( $self->{_pod_cut_count} > 1 ) {
885 my $rpre_string = shift( @{$rpre_string_stack} );
886 if ( ${$rpre_string} ) {
887 $html_print->('<pre>');
888 $html_print->( ${$rpre_string} );
889 $html_print->('</pre>');
893 # shouldn't happen: we stored a string before writing
896 "Problem merging html stream with pod2html; order may be wrong\n"
899 $html_print->($line);
902 # If didn't see multiple =cut lines, we'll put the pod out first
903 # and then the code, because it's less confusing.
906 # since we are not intermixing code and pod, we don't need
907 # or want any <hr> lines which separated pod and code
908 $html_print->($line) unless ( $line =~ /^\s*<hr>\s*$/i );
912 # Copy any remaining code section before the </body> tag
913 elsif ( $line =~ /^\s*<\/body>\s*$/i ) {
915 if ( @{$rpre_string_stack} ) {
916 unless ( $self->{_pod_cut_count} > 1 ) {
917 $html_print->('<hr />');
919 while ( my $rpre_string = shift( @{$rpre_string_stack} ) ) {
920 $html_print->('<pre>');
921 $html_print->( ${$rpre_string} );
922 $html_print->('</pre>');
925 $html_print->($line);
928 $html_print->($line);
934 Perl::Tidy::Warn("Did not see <body> in pod2html output\n");
937 unless ($saw_body_end) {
938 Perl::Tidy::Warn("Did not see </body> in pod2html output\n");
941 unless ($saw_index) {
942 Perl::Tidy::Warn("Did not find INDEX END in pod2html output\n");
947 close_object($html_fh);
949 # note that we have to unlink tmpfile before making frames
950 # because the tmpfile may be one of the names used for frames
952 unless ( unlink($tmpfile) ) {
953 Perl::Tidy::Warn("couldn't unlink temporary file $tmpfile: $!\n");
958 if ( $success_flag && $rOpts->{'frames'} ) {
959 $self->make_frame( \@toc );
961 return $success_flag;
966 # Make a frame with table of contents in the left panel
967 # and the text in the right panel.
969 # $html_filename contains the no-frames html output
970 # $rtoc is a reference to an array with the table of contents
971 my ( $self, $rtoc ) = @_;
972 my $input_file = $self->{_input_file};
973 my $html_filename = $self->{_html_file};
974 my $toc_filename = $self->{_toc_filename};
975 my $src_filename = $self->{_src_filename};
976 my $title = $self->{_title};
977 $title = escape_html($title);
979 # FUTURE input parameter:
980 my $top_basename = "";
982 # We need to produce 3 html files:
983 # 1. - the table of contents
984 # 2. - the contents (source code) itself
985 # 3. - the frame which contains them
987 # get basenames for relative links
988 my ( $toc_basename, $toc_path ) = fileparse($toc_filename);
989 my ( $src_basename, $src_path ) = fileparse($src_filename);
991 # 1. Make the table of contents panel, with appropriate changes
992 # to the anchor names
993 my $src_frame_name = 'SRC';
995 write_toc_html( $title, $toc_filename, $src_basename, $rtoc,
998 # 2. The current .html filename is renamed to be the contents panel
999 rename( $html_filename, $src_filename )
1000 or Perl::Tidy::Die("Cannot rename $html_filename to $src_filename:$!\n");
1002 # 3. Then use the original html filename for the frame
1004 $title, $html_filename, $top_basename,
1005 $toc_basename, $src_basename, $src_frame_name
1010 sub write_toc_html {
1012 # write a separate html table of contents file for frames
1013 my ( $title, $toc_filename, $src_basename, $rtoc, $src_frame_name ) = @_;
1014 my $fh = IO::File->new( $toc_filename, 'w' )
1015 or Perl::Tidy::Die("Cannot open $toc_filename:$!\n");
1019 <title>$title</title>
1022 <h1><a href=\"$src_basename#-top-" target="$src_frame_name">$title</a></h1>
1026 change_anchor_names( $rtoc, $src_basename, "$src_frame_name" );
1027 $fh->print( join "", @{$rtoc} );
1037 sub write_frame_html {
1039 # write an html file to be the table of contents frame
1041 $title, $frame_filename, $top_basename,
1042 $toc_basename, $src_basename, $src_frame_name
1045 my $fh = IO::File->new( $frame_filename, 'w' )
1046 or Perl::Tidy::Die("Cannot open $toc_basename:$!\n");
1049 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
1050 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
1051 <?xml version="1.0" encoding="iso-8859-1" ?>
1052 <html xmlns="http://www.w3.org/1999/xhtml">
1054 <title>$title</title>
1058 # two left panels, one right, if master index file
1059 if ($top_basename) {
1061 <frameset cols="20%,80%">
1062 <frameset rows="30%,70%">
1063 <frame src = "$top_basename" />
1064 <frame src = "$toc_basename" />
1069 # one left panels, one right, if no master index file
1072 <frameset cols="20%,*">
1073 <frame src = "$toc_basename" />
1077 <frame src = "$src_basename" name = "$src_frame_name" />
1080 <p>If you see this message, you are using a non-frame-capable web client.</p>
1081 <p>This document contains:</p>
1083 <li><a href="$toc_basename">A table of contents</a></li>
1084 <li><a href="$src_basename">The source code</a></li>
1094 sub change_anchor_names {
1096 # add a filename and target to anchors
1097 # also return the first anchor
1098 my ( $rlines, $filename, $target ) = @_;
1100 foreach my $line ( @{$rlines} ) {
1102 # We're looking for lines like this:
1103 # <LI><A HREF="#synopsis">SYNOPSIS</A></LI>
1104 # ---- - -------- -----------------
1106 if ( $line =~ /^(.*)<a(.*)href\s*=\s*"([^#]*)#([^"]+)"[^>]*>(.*)$/i ) {
1110 my $href = "$filename#$name";
1111 $line = "$pre<a href=\"$href\" target=\"$target\">$post\n";
1112 unless ($first_anchor) { $first_anchor = $href }
1115 return $first_anchor;
1118 sub close_html_file {
1120 return unless $self->{_html_file_opened};
1122 my $html_fh = $self->{_html_fh};
1123 my $rtoc_string = $self->{_rtoc_string};
1125 # There are 3 basic paths to html output...
1127 # ---------------------------------
1128 # Path 1: finish up if in -pre mode
1129 # ---------------------------------
1130 if ( $rOpts->{'html-pre-only'} ) {
1131 $html_fh->print( <<"PRE_END");
1134 close_object($html_fh);
1139 $self->add_toc_item( 'EOF', 'EOF' );
1141 my $rpre_string_stack = $self->{_rpre_string_stack};
1143 # Patch to darken the <pre> background color in case of pod2html and
1144 # interleaved code/documentation. Otherwise, the distinction
1145 # between code and documentation is blurred.
1146 if ( $rOpts->{pod2html}
1147 && $self->{_pod_cut_count} >= 1
1148 && $rOpts->{'html-color-background'} eq '#FFFFFF' )
1150 $rOpts->{'html-pre-color-background'} = '#F0F0F0';
1153 # put the css or its link into a string, if used
1155 my $fh_css = Perl::Tidy::IOScalar->new( \$css_string, 'w' );
1157 # use css linked to another file
1158 if ( $rOpts->{'html-linked-style-sheet'} ) {
1160 qq(<link rel="stylesheet" href="$css_linkname" type="text/css" />));
1163 # use css embedded in this file
1164 elsif ( !$rOpts->{'nohtml-style-sheets'} ) {
1165 $fh_css->print( <<'ENDCSS');
1166 <style type="text/css">
1169 write_style_sheet_data($fh_css);
1170 $fh_css->print( <<"ENDCSS");
1176 # -----------------------------------------------------------
1177 # path 2: use pod2html if requested
1178 # If we fail for some reason, continue on to path 3
1179 # -----------------------------------------------------------
1180 if ( $rOpts->{'pod2html'} ) {
1181 my $rpod_string = $self->{_rpod_string};
1183 ${$rpod_string}, $css_string,
1184 ${$rtoc_string}, $rpre_string_stack
1188 # --------------------------------------------------
1189 # path 3: write code in html, with pod only in italics
1190 # --------------------------------------------------
1191 my $input_file = $self->{_input_file};
1192 my $title = escape_html($input_file);
1194 if ( $rOpts->{'timestamp'} ) {
1195 my $date = localtime;
1196 $timestamp = "on $date";
1198 $html_fh->print( <<"HTML_START");
1199 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1200 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1201 <!-- Generated by perltidy $timestamp -->
1202 <html xmlns="http://www.w3.org/1999/xhtml">
1204 <title>$title</title>
1207 # output the css, if used
1209 $html_fh->print($css_string);
1210 $html_fh->print( <<"ENDCSS");
1217 $html_fh->print( <<"HTML_START");
1219 <body bgcolor=\"$rOpts->{'html-color-background'}\" text=\"$rOpts->{'html-color-punctuation'}\">
1223 $html_fh->print("<a name=\"-top-\"></a>\n");
1224 $html_fh->print( <<"EOM");
1228 # copy the table of contents
1229 if ( ${$rtoc_string}
1230 && !$rOpts->{'frames'}
1231 && $rOpts->{'html-table-of-contents'} )
1233 $html_fh->print( ${$rtoc_string} );
1236 # copy the pre section(s)
1237 my $fname_comment = $input_file;
1238 $fname_comment =~ s/--+/-/g; # protect HTML comment tags
1239 $html_fh->print( <<"END_PRE");
1241 <!-- contents of filename: $fname_comment -->
1245 foreach my $rpre_string ( @{$rpre_string_stack} ) {
1246 $html_fh->print( ${$rpre_string} );
1249 # and finish the html page
1250 $html_fh->print( <<"HTML_END");
1255 close_object($html_fh);
1257 if ( $rOpts->{'frames'} ) {
1258 ##my @toc = map { $_ .= "\n" } split /\n/, ${$rtoc_string};
1259 my @toc = map { $_ . "\n" } split /\n/, ${$rtoc_string};
1260 $self->make_frame( \@toc );
1266 my ( $self, $rtokens, $rtoken_type, $rlevels ) = @_;
1267 my ( @colored_tokens, $type, $token, $level );
1268 my $rlast_level = $self->{_rlast_level};
1269 my $rpackage_stack = $self->{_rpackage_stack};
1271 for ( my $j = 0 ; $j < @{$rtoken_type} ; $j++ ) {
1272 $type = $rtoken_type->[$j];
1273 $token = $rtokens->[$j];
1274 $level = $rlevels->[$j];
1275 $level = 0 if ( $level < 0 );
1277 #-------------------------------------------------------
1278 # Update the package stack. The package stack is needed to keep
1279 # the toc correct because some packages may be declared within
1280 # blocks and go out of scope when we leave the block.
1281 #-------------------------------------------------------
1282 if ( $level > ${$rlast_level} ) {
1283 unless ( $rpackage_stack->[ $level - 1 ] ) {
1284 $rpackage_stack->[ $level - 1 ] = 'main';
1286 $rpackage_stack->[$level] = $rpackage_stack->[ $level - 1 ];
1288 elsif ( $level < ${$rlast_level} ) {
1289 my $package = $rpackage_stack->[$level];
1290 unless ($package) { $package = 'main' }
1292 # if we change packages due to a nesting change, we
1293 # have to make an entry in the toc
1294 if ( $package ne $rpackage_stack->[ $level + 1 ] ) {
1295 $self->add_toc_item( $package, 'package' );
1298 ${$rlast_level} = $level;
1300 #-------------------------------------------------------
1301 # Intercept a sub name here; split it
1302 # into keyword 'sub' and sub name; and add an
1304 #-------------------------------------------------------
1305 if ( $type eq 'i' && $token =~ /^(sub\s+)(\w.*)$/ ) {
1306 $token = $self->markup_html_element( $1, 'k' );
1307 push @colored_tokens, $token;
1311 # but don't include sub declarations in the toc;
1312 # these wlll have leading token types 'i;'
1313 my $signature = join "", @{$rtoken_type};
1314 unless ( $signature =~ /^i;/ ) {
1315 my $subname = $token;
1316 $subname =~ s/[\s\(].*$//; # remove any attributes and prototype
1317 $self->add_toc_item( $subname, 'sub' );
1321 #-------------------------------------------------------
1322 # Intercept a package name here; split it
1323 # into keyword 'package' and name; add to the toc,
1324 # and update the package stack
1325 #-------------------------------------------------------
1326 if ( $type eq 'i' && $token =~ /^(package\s+)(\w.*)$/ ) {
1327 $token = $self->markup_html_element( $1, 'k' );
1328 push @colored_tokens, $token;
1331 $self->add_toc_item( "$token", 'package' );
1332 $rpackage_stack->[$level] = $token;
1335 $token = $self->markup_html_element( $token, $type );
1336 push @colored_tokens, $token;
1338 return ( \@colored_tokens );
1341 sub markup_html_element {
1342 my ( $self, $token, $type ) = @_;
1344 return $token if ( $type eq 'b' ); # skip a blank token
1345 return $token if ( $token =~ /^\s*$/ ); # skip a blank line
1346 $token = escape_html($token);
1348 # get the short abbreviation for this token type
1349 my $short_name = $token_short_names{$type};
1350 if ( !defined($short_name) ) {
1351 $short_name = "pu"; # punctuation is default
1354 # handle style sheets..
1355 if ( !$rOpts->{'nohtml-style-sheets'} ) {
1356 if ( $short_name ne 'pu' ) {
1357 $token = qq(<span class="$short_name">) . $token . "</span>";
1361 # handle no style sheets..
1363 my $color = $html_color{$short_name};
1365 if ( $color && ( $color ne $rOpts->{'html-color-punctuation'} ) ) {
1366 $token = qq(<font color="$color">) . $token . "</font>";
1368 if ( $html_italic{$short_name} ) { $token = "<i>$token</i>" }
1369 if ( $html_bold{$short_name} ) { $token = "<b>$token</b>" }
1377 if ($missing_html_entities) {
1378 $token =~ s/\&/&/g;
1379 $token =~ s/\</</g;
1380 $token =~ s/\>/>/g;
1381 $token =~ s/\"/"/g;
1384 HTML::Entities::encode_entities($token);
1389 sub finish_formatting {
1391 # called after last line
1393 $self->close_html_file();
1399 my ( $self, $line_of_tokens ) = @_;
1400 return unless $self->{_html_file_opened};
1401 my $html_pre_fh = $self->{_html_pre_fh};
1402 my $line_type = $line_of_tokens->{_line_type};
1403 my $input_line = $line_of_tokens->{_line_text};
1404 my $line_number = $line_of_tokens->{_line_number};
1407 # markup line of code..
1409 if ( $line_type eq 'CODE' ) {
1410 my $rtoken_type = $line_of_tokens->{_rtoken_type};
1411 my $rtokens = $line_of_tokens->{_rtokens};
1412 my $rlevels = $line_of_tokens->{_rlevels};
1414 if ( $input_line =~ /(^\s*)/ ) {
1420 my ($rcolored_tokens) =
1421 $self->markup_tokens( $rtokens, $rtoken_type, $rlevels );
1422 $html_line .= join '', @{$rcolored_tokens};
1425 # markup line of non-code..
1428 if ( $line_type eq 'HERE' ) { $line_character = 'H' }
1429 elsif ( $line_type eq 'HERE_END' ) { $line_character = 'h' }
1430 elsif ( $line_type eq 'FORMAT' ) { $line_character = 'H' }
1431 elsif ( $line_type eq 'FORMAT_END' ) { $line_character = 'h' }
1432 elsif ( $line_type eq 'SYSTEM' ) { $line_character = 'c' }
1433 elsif ( $line_type eq 'END_START' ) {
1434 $line_character = 'k';
1435 $self->add_toc_item( '__END__', '__END__' );
1437 elsif ( $line_type eq 'DATA_START' ) {
1438 $line_character = 'k';
1439 $self->add_toc_item( '__DATA__', '__DATA__' );
1441 elsif ( $line_type =~ /^POD/ ) {
1442 $line_character = 'P';
1443 if ( $rOpts->{'pod2html'} ) {
1444 my $html_pod_fh = $self->{_html_pod_fh};
1445 if ( $line_type eq 'POD_START' ) {
1447 my $rpre_string_stack = $self->{_rpre_string_stack};
1448 my $rpre_string = $rpre_string_stack->[-1];
1450 # if we have written any non-blank lines to the
1451 # current pre section, start writing to a new output
1453 if ( ${$rpre_string} =~ /\S/ ) {
1456 Perl::Tidy::IOScalar->new( \$pre_string, 'w' );
1457 $self->{_html_pre_fh} = $html_pre_fh;
1458 push @{$rpre_string_stack}, \$pre_string;
1460 # leave a marker in the pod stream so we know
1461 # where to put the pre section we just
1463 my $for_html = '=for html'; # don't confuse pod utils
1464 $html_pod_fh->print(<<EOM);
1467 <!-- pERLTIDY sECTION -->
1472 # otherwise, just clear the current string and start
1475 ${$rpre_string} = "";
1476 $html_pod_fh->print("\n");
1479 $html_pod_fh->print( $input_line . "\n" );
1480 if ( $line_type eq 'POD_END' ) {
1481 $self->{_pod_cut_count}++;
1482 $html_pod_fh->print("\n");
1487 else { $line_character = 'Q' }
1488 $html_line = $self->markup_html_element( $input_line, $line_character );
1491 # add the line number if requested
1492 if ( $rOpts->{'html-line-numbers'} ) {
1494 ( $line_number < 10 ) ? " "
1495 : ( $line_number < 100 ) ? " "
1496 : ( $line_number < 1000 ) ? " "
1498 $html_line = $extra_space . $line_number . " " . $html_line;
1502 $html_pre_fh->print("$html_line\n");