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
|
package Markdown::Render;
use strict;
use warnings;
use Carp;
use Data::Dumper;
use English qw(-no_match_vars);
use HTTP::Request;
use IO::Scalar;
use JSON;
use LWP::UserAgent;
use List::Util qw(none);
our $VERSION = '1.60.4';
use parent qw(Class::Accessor::Fast);
__PACKAGE__->follow_best_practice;
__PACKAGE__->mk_accessors(
qw(
body
css
engine
git_email
git_user
html
infile
markdown
mode
no_title
raw
render
title
)
);
use Readonly;
Readonly our $GITHUB_API => 'https://api.github.com/markdown';
Readonly our $EMPTY => q{};
Readonly our $SPACE => q{ };
Readonly our $TOC_TITLE => 'Table of Contents';
Readonly our $TOC_BACK => 'Back to Table of Contents';
Readonly our $DEFAULT_CSS => 'https://cdn.simplecss.org/simple-v1.css';
caller or __PACKAGE__->main;
########################################################################
sub new {
########################################################################
my ( $class, @args ) = @_;
my %options = ref $args[0] ? %{ $args[0] } : @args;
$options{title} //= $TOC_TITLE;
$options{css} //= $options{nocss} ? $EMPTY : $DEFAULT_CSS;
$options{mode} //= 'markdown';
$options{engine} //= 'text_markdown';
my $self = $class->SUPER::new( \%options );
if ( $self->get_infile ) {
open my $fh, '<', $self->get_infile
or die 'could not open ' . $self->get_infile;
local $RS = undef;
$self->set_markdown(<$fh>);
close $fh;
}
return $self;
}
########################################################################
sub toc_back {
########################################################################
my ($self) = @_;
my $back_link = lc $self->get_title;
$back_link =~ s/\s/-/gxsm;
return $back_link;
}
########################################################################
sub back_to_toc {
########################################################################
my ( $self, $message ) = @_;
$message ||= $TOC_BACK;
$message =~ s/[(]\"?(.*?)\"?[)]/$1/xsm;
return sprintf '[%s](#%s)', $message, $self->toc_back;
}
########################################################################
sub finalize_markdown {
########################################################################
my ($self) = @_;
my $markdown = $self->get_markdown;
die "no markdown yet\n"
if !$markdown;
my $fh = IO::Scalar->new( \$markdown );
my $final_markdown;
my $in_code_block;
while ( my $line = <$fh> ) {
if ( $line =~ /\A\s*[`]{3}\s*\z/xsm ) {
$in_code_block ^= 1;
}
if ($in_code_block) {
$final_markdown .= $line;
next;
}
$line =~ s/^\!\#/\#/xsm; # ! used to prevent including header in TOC
if ( $line =~ /^\@TOC\@/xsm ) {
my $toc = $self->create_toc;
chomp $toc;
$line =~ s/\@TOC\@/$toc/xsm;
}
my $title = $self->get_title;
if ( $line =~ /\@TOC_TITLE\@/xsm ) {
$line =~ s/\@TOC_TITLE\@/$title/xsm;
}
my $git_user = $self->get_git_user // 'anonymouse';
my $git_email = $self->get_git_email // 'anonymouse@example.com';
if ( $line =~ /\@GIT_(USER|EMAIL)\@/xsm ) {
$line =~ s/\@GIT_USER\@/$git_user/xsm;
$line =~ s/\@GIT_EMAIL\@/$git_email/xsm;
}
my $date;
while ( $line =~ /\@DATE[(]?(.*?)[)]?\@/xsm ) {
my $format = $1 ? $1 : '%Y-%m-%d';
$date = $self->format_date($format);
$line =~ s /\@DATE[(]?(.*?)[)]?\@/$date/xsm;
}
if ( $line =~ /\@TOC_BACK[(]?(.*?)[)]?\@/xsm ) {
my $back = $self->back_to_toc($1);
$line =~ s/\@TOC_BACK[(]?(.*?)[)]?\@/$back/xsm;
}
$final_markdown .= $line;
}
close $fh;
$self->set_markdown($final_markdown);
return $self;
}
########################################################################
sub _render_with_text_markdown {
########################################################################
my ($self) = @_;
eval { require Text::Markdown::Discount; };
if ($EVAL_ERROR) {
carp "no Text::Markdown::Discount available...using GitHub API.\n$EVAL_ERROR";
return $self->_render_with_github;
}
my $markdown = $self->get_markdown;
my $html = Text::Markdown::Discount::markdown($markdown);
if ( $self->get_raw ) {
$self->set_html($html);
}
else {
$self->fix_anchors( Text::Markdown::Discount::markdown($markdown) );
}
return $self;
}
########################################################################
sub fix_anchors {
########################################################################
my ( $self, $html_raw ) = @_;
my $fh = IO::Scalar->new( \$html_raw );
my $html;
# sample:
# <div class="markdown-heading"><h1 class="heading-element">Table of Contents</h1><a id="table-of-contents" class="anchor" aria-label="Permalink: Table of Contents" href="#table-of-contents"><span aria-hidden="true" class="octicon octicon-link"></span></a></div>
while ( my $line = <$fh> ) {
# remove garbage if there...
if ( $line =~ m{<h(\d+)([^>]*?)>([^<]+?)</h\d+><a(.*?)/a>(.*?)}xsm ) {
$line = "<a$4$5/a><h$1$2>$3</h$1>\n";
}
$html .= _fix_header($line);
}
close $fh;
$self->set_html($html);
return $self;
}
########################################################################
sub _fix_header {
########################################################################
my ($line) = @_;
return $line if $line !~ /^\s*<h(\d+)>(.*?)<\/h\d>$/xsm;
my ( $hn, $anchor, $header ) = ( $1, $2, $2 ); ## no critic (ProhibitCaptureWithoutTest)
$anchor = lc $anchor;
$anchor =~ s/\s+/-/gxsm; # spaces become '-'
$anchor =~ s/[.:\?_.\@'(),\`]//xsmg; # known weird characters, but expect more
$anchor =~ s/\///xsmg;
$line
= sprintf qq{<a id="%s" class="anchor" href="#%s"></a><h%s>%s</h%d>\n},
$anchor, $anchor, $hn, $header, $hn;
return $line;
}
########################################################################
sub render_markdown {
########################################################################
my ($self) = @_;
if ( $self->get_engine eq 'github' ) {
return $self->_render_with_github;
}
elsif ( $self->get_engine eq 'text_markdown' ) {
return $self->_render_with_text_markdown;
}
else {
croak 'invalid engine: ' . $self->get_engine;
}
}
########################################################################
sub _render_with_github {
########################################################################
my ($self) = @_;
my $markdown = $self->get_markdown;
my $ua = LWP::UserAgent->new;
my $req = HTTP::Request->new( 'POST', $GITHUB_API );
my $mode = $self->get_mode;
if ( none { $mode eq $_ } qw(gfm markdown) ) {
$mode = 'markdown';
}
my $api_request = {
text => $markdown,
mode => $mode,
};
$req->content( to_json($api_request) );
my $rsp = $ua->request($req);
croak 'could not render using GitHub API: ' . $rsp->status_line
if !$rsp->is_success;
if ( $self->get_raw ) {
$self->set_html( $rsp->content );
return $self;
}
if ( $self->get_mode eq 'gfm' ) {
return $self->fix_anchors( $rsp->content );
}
else {
$self->fix_anchors( $rsp->content );
return $self->fix_github_html( $self->get_html );
}
}
########################################################################
sub fix_github_html {
########################################################################
my ( $self, $html_raw ) = @_;
my $fh = IO::Scalar->new( \$html_raw );
my $html = $EMPTY;
while ( my $line = <$fh> ) {
chomp $line;
$line =~ s/(href|id)=\"\#?user-content-/$1=\"/xsm;
$line =~ s/(href|id)=\"\#?\%60.*\%60/$1=\"#$2/xsm;
$html .= "$line\n";
}
close $fh;
$self->set_html($html);
return $self;
}
########################################################################
sub format_date {
########################################################################
my ( $self, $template ) = @_;
require Date::Format;
$template =~ s/[(]\"?(.*?)\"?[)]/$1/xsm;
my $val = eval { Date::Format::time2str( $template, time ); };
return $EVAL_ERROR ? '<undef>' : $val;
}
########################################################################
sub create_toc {
########################################################################
my ($self) = @_;
my $markdown = $self->get_markdown;
my $fh = IO::Scalar->new( \$markdown );
my $toc = $self->get_no_title ? $EMPTY : "# \@TOC_TITLE\@\n\n";
while (<$fh>) {
chomp;
/^(\#+)\s+(.*?)$/xsm && do {
my $level = $1;
my $indent = $SPACE x ( 2 * ( length($level) - 1 ) );
my $topic = $2;
my $link = $topic;
$link =~ s/^\s*(.*)\s*$/$1/xsm;
$link =~ s/\s+/-/gxsm; # spaces become '-'
$link =~ s/[\?\_:.\@'(),\`]//xsmg; # known weird characters, but expect more
$link =~ s/\///xsmg;
$link = lc $link;
# remove HTML entities
$link =~ s/&\#\d+;//xsmg;
# remove escaped entities and remaining noisy characters
$link =~ s/[{}&]//xsmg;
$toc .= sprintf "%s* [%s](#%s)\n", $indent, $topic, $link;
};
}
close $fh;
return $toc;
}
########################################################################
sub print_html {
########################################################################
my ( $self, %options ) = @_;
my $fh = $options{fh} // *STDOUT;
if ( !$options{body} ) {
print {$fh} $self->get_html;
return;
}
my $css = exists $options{css} ? $options{css} : $self->get_css;
my $title = exists $options{title} ? $options{title} : $self->get_infile;
my $title_section = $title ? "<title>$title</title>" : $EMPTY;
my $css_section
= $css
? qq{<link href="$css" rel="stylesheet" type="text/css" />}
: $EMPTY;
my @head = grep { $_ ? $_ : () } ( $title_section, $css_section );
my $head_section;
if (@head) {
unshift @head, '<head>';
push @head, '</head>';
$head_section = join "\n", @head;
}
my $body = $self->get_html;
print {$fh} <<"END_OF_TEXT";
<html>
$head_section
<body>
$body
</body>
</html>
END_OF_TEXT
return;
}
########################################################################
sub main {
########################################################################
my $md = Markdown::Render->new(
infile => shift @ARGV,
css => $DEFAULT_CSS
);
$md->finalize_markdown->render_markdown;
$md->print_html;
exit 0;
}
1;
## no critic (RequirePodSections)
__END__
=pod
=head1 NAME
Markdown::Render - Render markdown as HTML
=head1 SYNOPSIS
use Markdown::Render;
my $md = Markdown::Render->new( infile => 'README.md');
$md->render_markdown->print_html;
...or from the command line to create HTML
md-utils -r README.md > README.html
...or from the command line to replace render custom tags
md-utils README.md.in > README.md
=head1 DESCRIPTION
Renders markdown as HTML using either GitHub's API or
L<Text::Markdown::Discount>. Optionally adds additional metadata to markdown
document using custom tags.
See
L<README.md|https://github.com/rlauer6/markdown-utils/blob/master/README.md>
for more details.
I<Note: This module originally used L<Text::Markdown> as an
alternative to using the GitHub API however, there are too many bugs
and idiosyncracies in that module. This module will now use
L<Text::Markdown::Discount> which is not only faster, but seems to be
more compliant with GFM.>
I<Note: Text::Markdown::Discount relies on the text-markdown library
which did not actually support all of the markdown features (including
code fencing). You can find an updated version of
L<Text::Markdown::Discount> here:
L<https://github.com/rlauer6/text-markdown-discount>>
=head1 METHODS AND SUBROUTINES
=head2 new
new( options )
Any of the options passed to the C<new> method can also be set or
retrieved use the C<set_NAME> or C<get_NAME> methods.
=over 5
=item css
URL of a CSS file to add to head section of printed HTML.
=item engine
One of C<github> or C<text_markdown>.
default: text_markdown
=item git_user
Name of the git user that is used in the C<GIT_USER> tag.
=item git_email
Email address of the git user that is used in the C<GIT_EMAIL> tag.
=item infile
Path to a file in markdow format.
=item markdown
Text of the markdown to be rendered.
=item mode
If using the GitHub API, mode can be either C<gfm> or C<markdown>.
default: markdown
=item no_title
Boolean that indicates that no title should be added to the table of
contents.
default: false
=item title
Title to be used for the table of contents.
=back
=head2 finalize_markdown
Updates the markdown by interpolating the custom keywords. Invoking this
method will create a table of contents and replace keywords with their
values.
Invoke this method prior to invoking C<render_markdown>.
Returns the L<Markdown::Render> object.
=head2 render_markdown
Passes the markdown to GitHub's markdown rendering engine. After
invoking this method you can retrieve the processed html by invoking
C<get_html> or create a fully rendered HTML page using the C<print_html>
method.
Returns the L<Markdown::Render> object.
=head2 print_html
print_html(options)
Outputs the fully rendered HTML page.
=over 5
=item css
URL of a CSS style sheet to include in the head section. If no CSS
file option is passed a default CSS file will b used. If a CSS element
is passed but it is undefined or empty, then no CSS will be specified
in the final document.
=item title
Title to be added in the head section of the document. If no title
option is passed the name of the file will be use as the title. If an
title option is passed but is undefined or empty, no title element
will be added to the document.
=back
=head1 AUTHOR
Rob Lauer - rlauer6@comcast.net
=head1 SEE OTHER
L<GitHub Markdown API|https://docs.github.com/en/rest/markdown>
L<Text::Markdown::Discount>
=cut
|