public
Created

html_fmt -- HTML Reformatter

  • Download Gist
marpa_r2_html_fmt
Perl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
#!/usr/bin/perl
# Copyright 2012 Jeffrey Kegler
# This file is part of Marpa::R2. Marpa::R2 is free software: you can
# redistribute it and/or modify it under the terms of the GNU Lesser
# General Public License as published by the Free Software Foundation,
# either version 3 of the License, or (at your option) any later version.
#
# Marpa::R2 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser
# General Public License along with Marpa::R2. If not, see
# http://www.gnu.org/licenses/.
 
use 5.010;
use strict;
use warnings;
use English qw( -no_match_vars );
use Marpa::R2::HTML;
use HTML::Tagset;
use Fatal qw(open close);
use Getopt::Long;
 
sub usage
{
say {*STDERR} "$PROGRAM_NAME html_fmt [uri|file]" or die "say failed: $ERRNO";
exit 1;
}
 
my $help_flag = 0;
my @avoid_whitespace_flags = qw(comment yes);
my $avoid_whitespace_flag = 'yes';
my $ws_ok_before_end_tag_flag = 0;
usage()
if not Getopt::Long::GetOptions(
'help' => \$help_flag,
'avoid-whitespace=s' => \$avoid_whitespace_flag,
'ws-ok-before-end-tag' => \$ws_ok_before_end_tag_flag,
);
usage() if $help_flag or scalar @ARGV > 1;
if ( not $avoid_whitespace_flag ~~ \@avoid_whitespace_flags ) {
die "Bad avoid-whitespace flag\n",
'avoid-whitespace must be one of the following: ', join q{ },
@avoid_whitespace_flags;
}
 
my $locator = shift;
my $document;
GET_DOCUMENT: {
if ( not defined $locator ) {
local $RS = undef;
## no critic(InputOutput::ProhibitExplicitStdin)
$document = <STDIN>;
last GET_DOCUMENT;
}
if ( $locator =~ /\A [[:alnum:]]+ [:] /xms ) {
require WWW::Mechanize;
my $mech = WWW::Mechanize->new( autocheck => 1 );
$mech->get($locator);
$document = $mech->content;
undef $mech;
last GET_DOCUMENT;
} ## end if ( $locator =~ /\A [[:alnum:]]+ [:] /xms )
{
local $RS = undef;
open my $fh, q{<}, $locator;
$document = <$fh>;
close $fh;
}
} ## end GET_DOCUMENT:
 
sub post_process {
my ($value) = @_;
my @text_pieces = ();
DATUM: for my $line_data ( @{ $value->[0] } ) {
my ( $type, $indent ) = @{$line_data};
if ( $type eq 'text' ) {
my $text = $line_data->[2];
my $has_trailing_ws = $text =~ s/ \s+ \z//xms;
if ( $text =~ s/ \A \s+ //xms ) {
push @text_pieces, [ 'whitespace', $indent ];
}
my @lines = grep { $_ =~ /\S/xms } split /\n/xms, $text;
for my $line_no ( 0 .. $#lines ) {
my $line = $lines[$line_no];
$line =~ s/\A[ \t]+//xms;
$line =~ s/[ \t]+\z//xms;
$line =~ s/[ \t]+/ /xms;
push @text_pieces, [ 'whitespace', $indent ] if $line_no;
push @text_pieces, [ 'text', $indent, $line ];
} ## end for my $line_no ( 0 .. $#lines )
push @text_pieces, [ 'whitespace', $indent ] if $has_trailing_ws;
next DATUM;
} ## end if ( $type eq 'text' )
if ( $type eq 'msg: missing start tag' ) {
my $location = $line_data->[2];
my $tagname = $line_data->[3];
given ($location) {
when ('preceeding') {
push @text_pieces,
[
'html_fmt comment',
$indent + 1,
'Preceeding start tag is replacement for a missing one'
];
} ## end when ('preceeding')
when ('following pre') {
push @text_pieces,
[
'html_fmt comment', $indent,
"Inside following <pre>, a start tag is missing: <$tagname>"
];
} ## end when ('following pre')
default {
Carp::croak(
"Internal error: unprovided-for missing start tag location: $_"
);
}
} ## end given
next DATUM;
} ## end if ( $type eq 'msg: missing start tag' )
if ( $type eq 'msg: missing end tag' ) {
my $location = $line_data->[2];
my $tagname = $line_data->[3];
given ($location) {
when ('following') {
push @text_pieces,
[
'html_fmt comment',
$indent + 1,
'Following end tag is replacement for a missing one'
];
} ## end when ('following')
when ('following pre') {
push @text_pieces,
[
'html_fmt comment', $indent,
"Inside following <pre>, an end tag is missing: <$tagname>"
];
} ## end when ('following pre')
default {
Carp::croak(
"Internal error: unprovided-for missing end tag location: $_"
);
}
} ## end given
next DATUM;
} ## end if ( $type eq 'msg: missing end tag' )
if ( $type eq 'msg: cruft' ) {
my $location = $line_data->[2];
my $cruft = $line_data->[3];
given ($location) {
when ('following') {
push @text_pieces,
[ 'html_fmt comment', $indent, 'Next line is cruft' ];
}
when ('following pre') {
 
# Make sure the cruft quoted inside
# the HTML comment does not
# disrupt the comment.
( my $safe_cruft = $cruft ) =~ s/--/- -/xms;
push @text_pieces,
[
'html_fmt comment', $indent,
qq{Inside the following <pre>, there is this cruft:\n$safe_cruft}
];
} ## end when ('following pre')
default {
Carp::croak(
"Internal error: unprovided-for cruft location: $_");
}
} ## end given
next DATUM;
} ## end if ( $type eq 'msg: cruft' )
push @text_pieces, [ $type, $indent, $line_data->[2] ];
} ## end DATUM: for my $line_data ( @{ $value->[0] } )
my @ws_unsafe;
$ws_unsafe[scalar @text_pieces] = 0; # size the array
$ws_unsafe[0] = 0;
my $last_non_comment_ix = scalar @text_pieces;
my $safe_after_piece = 0;
TEXT_PIECE: for my $text_piece_ix ( 0 .. $#text_pieces ) {
my ( $type, $indent, $text ) = @{ $text_pieces[$text_piece_ix] };
my $safe_before_piece = 0;
WHITESPACE_BY_TYPE: {
 
# If a comment, after-piece is whatever current value
# of $safe_after_piece,
# leave before as-is
last WHITESPACE_BY_TYPE if $type eq 'html_fmt comment';
last WHITESPACE_BY_TYPE if $type eq 'comment';
if ( $type eq 'whitespace' ) {
 
# Safe before and after other whitespace
$safe_before_piece = $safe_after_piece = 1;
last WHITESPACE_BY_TYPE;
} ## end if ( $type eq 'whitespace' )
if ( $type eq 'end tag' ) {
 
# Unsafe after an end tag, but safe before it
$safe_before_piece = $ws_ok_before_end_tag_flag;
$safe_after_piece = 0;
last WHITESPACE_BY_TYPE;
} ## end if ( $type eq 'end tag' )
if ( $type eq 'start tag' ) {
 
# Leave safe status as-is before start tag
# Whitespace safe after a start tag
$safe_after_piece = 1;
last WHITESPACE_BY_TYPE;
} ## end if ( $type eq 'start tag' )
if ( $type eq 'text' ) {
 
# Leave safe status as-is before text
# Whitespace not safe after a start tag
$safe_after_piece = 0;
last WHITESPACE_BY_TYPE;
} ## end if ( $type eq 'text' )
# Blocks can occur inline, etc.
# So with everything else, be conservative.
# Whitespace is unsafe after, and left as-is before.
$safe_after_piece = 0;
} ## end WHITESPACE_BY_TYPE:
$ws_unsafe[ $text_piece_ix + 1 ] = $safe_after_piece ? 0 : 1;
if ($safe_before_piece) {
for my $ix ( $last_non_comment_ix + 1 .. $text_piece_ix ) {
$ws_unsafe[$ix] = 0;
}
}
if ( $type ne 'comment' and $type ne 'html_fmt comment' ) {
$last_non_comment_ix = $text_piece_ix;
}
} ## end TEXT_PIECE: for my $text_piece_ix ( 0 .. $#text_pieces )
$ws_unsafe[scalar @text_pieces] = 0; # EOF is whitespace safe
my @output = ();
CREATE_OUTPUT: {
if ( $avoid_whitespace_flag eq 'comment' ) {
TEXT_PIECE: for my $text_piece_ix ( 0 .. $#text_pieces ) {
my ( $type, $indent, $text ) =
@{ $text_pieces[$text_piece_ix] };
next TEXT_PIECE if $type eq 'whitespace';
my $suffix = $ws_unsafe[ $text_piece_ix + 1 ] ? '<!--' : q{};
my $indentation = q{ } x $indent;
if ( $ws_unsafe[$text_piece_ix] ) {
$indentation =
$indentation
. ' html_fmt: this comment is to avoid introducing whitespace'
. "\n"
. $indentation . '-->';
} ## end if ( $ws_unsafe[$text_piece_ix] )
if ( $type eq 'text' and $text =~ /\S/xms ) {
push @output, $indentation . $text . $suffix;
next TEXT_PIECE;
}
if ( $type eq 'html_fmt comment' ) {
push @output,
$indentation
. '<!-- html_fmt: '
. $text . ' -->'
. $suffix;
next TEXT_PIECE;
} ## end if ( $type eq 'html_fmt comment' )
push @output, $indentation . $text . $suffix;
} ## end TEXT_PIECE: for my $text_piece_ix ( 0 .. $#text_pieces )
last CREATE_OUTPUT;
} ## end if ( $avoid_whitespace_flag eq 'comment' )
if ( $avoid_whitespace_flag eq 'yes' ) {
TEXT_PIECE: for my $text_piece_ix ( 0 .. $#text_pieces ) {
my ( $type, $indent, $text ) =
@{ $text_pieces[$text_piece_ix] };
next TEXT_PIECE if $type eq 'whitespace';
if ( $ws_unsafe[$text_piece_ix] ) {
if ( $type eq 'html_fmt comment' ) {
$text = '<!-- html_fmt: ' . $text . ' -->';
}
$output[-1] .= $text;
next TEXT_PIECE;
} ## end if ( $ws_unsafe[$text_piece_ix] )
my $indentation = q{ } x $indent;
if ( $type eq 'text' and $text =~ /\S/xms ) {
push @output, $indentation . $text;
next TEXT_PIECE;
}
if ( $type eq 'html_fmt comment' ) {
push @output,
$indentation
. '<!-- html_fmt: '
. $text . ' -->';
next TEXT_PIECE;
} ## end if ( $type eq 'html_fmt comment' )
push @output, $indentation . $text;
} ## end TEXT_PIECE: for my $text_piece_ix ( 0 .. $#text_pieces )
last CREATE_OUTPUT;
}
} ## end CREATE_OUTPUT:
return join "\n", @output, q{};
} ## end sub post_process
 
sub do_pre {
my @new_line_data = ();
CHILD:
for my $value ( @{ Marpa::R2::HTML::values() } ) {
for my $line_data ( @{$value} ) {
if ( $line_data->[0] =~ /\A msg [:] /xms ) {
push @new_line_data,
[
$line_data->[0], 0,
'following pre',
@{$line_data}[ 3 .. $#{$line_data} ]
];
} ## end if ( $line_data->[0] =~ /^msg:/ )
} ## end for my $line_data ( @{$value} )
} ## end CHILD: for my $value ( @{ Marpa::R2::HTML::values() } )
my $original = Marpa::R2::HTML::original();
push @new_line_data, [ 'pre', 0, $original ];
return \@new_line_data;
} ## end sub do_pre
 
sub do_cruft {
my $literal = Marpa::R2::HTML::literal();
my @new_line_data = ( [ 'msg: cruft', 0, 'following', $literal ] );
push @new_line_data, [ 'cruft', 0, $literal ];
return \@new_line_data;
} ## end sub do_cruft
 
sub do_comment {
my $literal = Marpa::R2::HTML::literal();
return [ [ 'comment', 0, $literal ] ];
}
 
sub do_default {
my $tagname = Marpa::R2::HTML::tagname();
my @new_line_data = ();
my @descendant_data =
@{ Marpa::R2::HTML::descendants('token_type,value,original') };
my $first_child = $descendant_data[0];
my $first_content_child = 0;
 
{
## no critic(Variables::ProhibitPackageVars)
my $tag_type =
$HTML::Tagset::emptyElement{$tagname}
? 'empty element'
: 'start tag';
##use critic
if ( defined $first_child->[0] and $first_child->[0] eq 'S' ) {
push @new_line_data, [ $tag_type, 0, $first_child->[2] ];
$first_content_child = 1;
}
else {
push @new_line_data, [ $tag_type, 0, '<' . $tagname . '>' ];
push @new_line_data,
[ 'msg: missing start tag', 0, 'preceeding', $tagname ];
}
}
 
my $last_child = $descendant_data[-1];
my $last_content_child = $#descendant_data;
my $end_tag_child;
if ( defined $last_child->[0] and $last_child->[0] eq 'E' ) {
$end_tag_child = $last_child;
$last_content_child -= 1;
}
 
CHILD:
for my $descendant_data_ix ( $first_content_child .. $last_content_child )
{
my ( $token_type, $value, $original ) =
@{ $descendant_data[$descendant_data_ix] };
if ( defined $value ) {
for my $line_data ( @{$value} ) {
my ( $type, $indent, @data ) = @{$line_data};
push @new_line_data, [ $type, $indent + 1, @data ];
}
next CHILD;
} ## end if ( defined $value )
push @new_line_data, [ 'text', 1, $original ];
} ## end CHILD: for my $descendant_data_ix ( $first_content_child .. ...)
 
END_TAG_PROCESSING: {
my $tag_type = 'end tag';
if ( defined $end_tag_child ) {
push @new_line_data, [ $tag_type, 0, $end_tag_child->[2] ];
last END_TAG_PROCESSING;
}
## no critic(Variables::ProhibitPackageVars)
last END_TAG_PROCESSING if $HTML::Tagset::emptyElement{$tagname};
## use critic
push @new_line_data,
[ 'msg: missing end tag', 0, 'following', $tagname ];
push @new_line_data, [ $tag_type, 0, '</' . $tagname . '>' ];
} ## end END_TAG_PROCESSING:
 
return \@new_line_data;
} ## end sub do_default
 
my $html_args = {
'script' => sub {
return [ [ 'script', 0, Marpa::R2::HTML::original() ] ];
},
':CRUFT' => \&do_cruft,
':COMMENT' => \&do_comment,
'pre' => \&do_pre,
q{*} => \&do_default,
':TOP' => sub { return Marpa::R2::HTML::values(); }
};
 
my $value_ref = Marpa::R2::HTML::html( \$document, $html_args );
die 'Internal error: no parse' if not defined $value_ref;
require Data::Dumper;
print post_process($value_ref) or die "print failed: $ERRNO";
 
exit 0;
 
__END__
 
=head1 NAME
 
html_fmt - Reformat HTML, indented according to structure
 
=head1 Synopsis
 
html_fmt [--avoid-whitespace=[yes|comment]]
[--ws-ok-before-end-tag|--no-ws-ok-before-end-tag] [uri|file]
 
=head1 Description
 
Writes its input to C<STDOUT>,
reformatted and
indented according to the HTML structure.
With no arguments,
C<html_fmt> looks for its input
on C<STDIN>.
If it has an argument that looks like a URI,
C<html_fmt> treats that argument
as a URI.
If it has an argument that does not
look like a URI,
C<html_fmt> uses that argument
as the name
of its input file.
C<html_fmt> considers its argument to
"look like a URI",
if it
starts with alphanumerics followed by a colon.
 
When reformatting and indenting,
C<html_fmt> takes measures
to avoid introducing
whitespace that will affect the way in which the HTML
displays.
The standards differ on whitespace treatment;
when the standards agree
they often allow considerable
latitude to the browsers;
and specific implementions will
exploit the allowed latitude in different ways,
or exceed it.
All of which is to say that
C<html_fmt>'s attempts to avoid introducing
whitespace are not always successful.
 
C<html_fmt> supplies missing start and end tags.
If C<html_fmt> cannot find required start and end tags,
it supplies them.
C<html_fmt>'s grammar is very liberal in its interpretation
of what is valid HTML.
Finally, if this is not sufficient to turn the input
into valid HTML,
C<html_fmt>
will treat problem sections of the input
as noise or "cruft",
ignoring them in determining
the structure of the document.
C<html_fmt> never rejects its input,
whatever its contents.
 
When
C<html_fmt> adds
a missing start tag,
it follows the new start tag with a comment.
When
C<html_fmt> adds
a missing end tag,
it preceeds the new end tag with a comment.
When C<html_fmt> classifies characters
as "cruft",
it adds a comment to that effect before the "cruft".
 
C<pre> and C<script>
elements receive special treatment.
The contents of
C<pre> and C<script> elements are not reformatted.
When missing tags or cruft occur inside a C<pre> element,
the comments to that effect are placed
before the C<< <pre> >> start tag.
The contents of C<script> elements are not
examined.
 
=head1 Options
 
No single set of reformatting choices is anywhere
near adequate to the variety of standards,
renderers and application requirements out there.
Ideally,
C<html_fmt> would have many options customizing its behavior.
As of this writing, there are only two.
 
=head2 avoid-whitespace
 
The C<--avoid-whitespace> option
may take one of two values:
C<yes> and C<comment>.
If the value is C<yes>,
C<html_fmt> does not try to add indentation
in whitespace-sensitive places.
This avoids clutter but,
because of the missed indentation,
the structure of the
document becomes harder to follow.
C<yes> is the default value.
 
If the value is C<comment>,
HTML (SGML) comments are used to achieve proper
indentation without introducing whitespace.
This works, but does get a bit cluttered.
 
=head2 ws-ok-before-end-tag
 
The C<--ws-ok-before-end-tag> option is a Boolean.
If set, C<html_fmt> will add whitespace before an end tag when
that is useful.
If the SGML standards
are adhered to, the added whitespace will not
be rendered.
However, the HTML standards, while they allow SGML-adherent behavior
for whitespace before end tags,
do not require it.
In practice,
many browsers will render whitespace found before
end tags.
 
If C<--ws-ok-before-end-tag> is false,
C<html_fmt> will not add whitespace before
end tags.
C<--ws-ok-before-end-tag> is false by default.
This is always safe,
in the sense that it will not change
what is there to be rendered.
But it limits the ability of
C<html_fmt> to make its output readable.
 
=head1 Example
 
Given this input:
 
<title>Test page<tr>x<head attr="I am cruft"><p>Final graf
 
to this command:
 
html_fmt --avoid-whitespace=comment --ws-ok-before-end-tag
 
the output is
 
<html>
<!-- html_fmt: Preceeding start tag is replacement for a missing one -->
<head>
<!-- html_fmt: Preceeding start tag is replacement for a missing one -->
<title>
Test page
<!-- html_fmt: Following end tag is replacement for a missing one -->
</title>
<!-- html_fmt: Following end tag is replacement for a missing one -->
</head><!--
html_fmt: this comment is to avoid introducing whitespace
--><body>
<!-- html_fmt: Preceeding start tag is replacement for a missing one -->
<table>
<!-- html_fmt: Preceeding start tag is replacement for a missing one -->
<tbody>
<!-- html_fmt: Preceeding start tag is replacement for a missing one -->
<tr>
<td>
<!-- html_fmt: Preceeding start tag is replacement for a missing one -->
x<!--
html_fmt: this comment is to avoid introducing whitespace
--><!-- html_fmt: Next line is cruft --><!--
html_fmt: this comment is to avoid introducing whitespace
--><head attr="I am cruft"><!--
html_fmt: this comment is to avoid introducing whitespace
--><p>
Final graf
<!-- html_fmt: Following end tag is replacement for a missing one -->
</p>
<!-- html_fmt: Following end tag is replacement for a missing one -->
</td>
<!-- html_fmt: Following end tag is replacement for a missing one -->
</tr>
<!-- html_fmt: Following end tag is replacement for a missing one -->
</tbody>
<!-- html_fmt: Following end tag is replacement for a missing one -->
</table>
<!-- html_fmt: Following end tag is replacement for a missing one -->
</body>
<!-- html_fmt: Following end tag is replacement for a missing one -->
</html>
 
=head1 Acknowledgements
 
The starting template for this code was
L<HTML::TokeParser|HTML::TokeParser>, by Gisle Aas.
 
=head1 LICENSE AND COPYRIGHT
 
Copyright 2007-2012 Jeffrey Kegler, all rights reserved.
Marpa is free software under the Perl license.
For details see the LICENSE file in the Marpa distribution.
 
=cut

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.