forked from mackyle/markdown
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Markdown.pl
executable file
·5564 lines (4769 loc) · 173 KB
/
Markdown.pl
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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env perl
#
# Markdown -- A text-to-HTML conversion tool for web writers
#
# Copyright (C) 2004 John Gruber
# Copyright (C) 2015,2016,2017,2018,2019,2020,2021 Kyle J. McKay
# All rights reserved.
# License is Modified BSD (aka 3-clause BSD) License\n";
# See LICENSE file (or <https://opensource.org/licenses/BSD-3-Clause>)
#
package Markdown;
use 5.008;
use strict;
use warnings;
use Encode;
use vars qw($COPYRIGHT $DATE $VERSION @ISA @EXPORT_OK);
BEGIN {*COPYRIGHT =
\"Copyright (C) 2004 John Gruber
Copyright (C) 2015,2016,2017,2018,2019,2020,2021 Kyle J. McKay
All rights reserved.
";
*VERSION = \"1.1.15";
*DATE = \"2021-08-15";
}
use Exporter ();
use Digest::MD5 qw(md5 md5_hex);
use File::Basename qw(basename);
use Scalar::Util qw(refaddr looks_like_number);
my ($hasxml, $hasxml_err); BEGIN { ($hasxml, $hasxml_err) = (0, "") }
my ($hasxmlp, $hasxmlp_err); BEGIN { ($hasxmlp, $hasxmlp_err) = (0, "") }
BEGIN {
@ISA = qw(Exporter);
@EXPORT_OK = qw(Markdown ProcessRaw GenerateStyleSheet SetWikiOpts SplitURL
escapeXML unescapeXML ResolveFragment ConvertNamedCharacterEntities);
$INC{__PACKAGE__.'.pm'} = $INC{basename(__FILE__)} unless exists $INC{__PACKAGE__.'.pm'};
}
close(DATA) if fileno(DATA);
exit(&_main(@ARGV)||0) unless caller;
sub fauxdie($) {
my $msg = join(" ", @_);
$msg =~ s/\s+$//os;
printf STDERR "%s: fatal: %s\n", basename($0), $msg;
exit 1;
}
my $encoder;
BEGIN {
$encoder = Encode::find_encoding('Windows-1252') ||
Encode::find_encoding('ISO-8859-1') or
die "failed to load ISO-8859-1 encoder\n";
}
#
# Global default settings:
#
my ($g_style_prefix, $g_empty_element_suffix, $g_indent_width,
$g_start_p, $g_close_p);
BEGIN {
$g_style_prefix = "_markdown-"; # Prefix for markdown css class styles
$g_empty_element_suffix = " />"; # Change to ">" for HTML output
$g_indent_width = 4; # Number of spaces considered new level
$g_start_p = "<p>"; # _FormParagraphs open paragraph tag
$g_close_p = "</p>"; # _FormParagraphs close paragraph tag
}
#
# Globals:
#
# Style sheet template
my $g_style_sheet;
# Permanent block id table
my %g_perm_block_ids;
# Global hashes, used by various utility routines
my %g_urls;
my %g_titles;
my %g_anchors;
my %g_anchors_id;
my %g_block_ids;
my %g_code_block_ids;
my %g_html_blocks;
my %g_code_blocks;
my @g_xml_comments;
my %opt;
my @autonum;
# Return a "block id" to use to identify the block that does not contain
# any characters that could be misinterpreted by the rest of the code
# Originally this used md5_hex but that's unnecessarily slow
# Instead just use the refaddr of the scalar ref of the entry for that
# key in either the global or, if the optional second argument is true,
# permanent table. To avoid the result being confused with anything
# else, it's prefixed with a control character and suffixed with another
# both of which are not allowed by the XML standard or Unicode.
sub block_id {
$_[1] or return "\5".refaddr(\$g_block_ids{$_[0]})."\6";
$_[1] == 1 and return "\2".refaddr(\$g_perm_block_ids{$_[0]})."\3";
$_[1] == 2 and return "\25".refaddr(\$g_code_block_ids{$_[0]})."\26";
die "programmer error: bad block_id type $_[1]";
}
# Regex to match balanced [brackets]. See Friedl's
# "Mastering Regular Expressions", 2nd Ed., pp. 328-331.
my $g_nested_brackets;
BEGIN {
$g_nested_brackets = qr{
(?> # Atomic matching
[^\[\]]+ # Anything other than brackets
|
\[
(??{ $g_nested_brackets }) # Recursive set of nested brackets
\]
)*
}ox
}
# Regex to match balanced (parentheses)
my $g_nested_parens;
BEGIN {
$g_nested_parens = qr{
(?> # Atomic matching
[^\(\)]+ # Anything other than parentheses
|
\(
(??{ $g_nested_parens }) # Recursive set of nested parentheses
\)
)*
}ox
}
# Table of hash values for escaped characters:
my %g_escape_table;
BEGIN {
$g_escape_table{""} = "\2\3";
foreach my $char (split //, "\\\`*_~{}[]()>#+-.!|:<") {
$g_escape_table{$char} = block_id($char,1);
}
}
# Used to track when we're inside an ordered or unordered list
# (see _ProcessListItems() for details):
my $g_list_level;
BEGIN {
$g_list_level = 0;
}
# Entity conversion table
my %named_character_entity;
BEGIN { %named_character_entity = (
'Aacute' => '193',
'aacute' => '225',
'Acirc' => '194',
'acirc' => '226',
'acute' => '180',
'AElig' => '198',
'aelig' => '230',
'Agrave' => '192',
'agrave' => '224',
'alefsym' => 'x2135',
'Alpha' => '913',
'alpha' => '945',
'and' => 'x2227',
'ang' => 'x2220',
'apos' => '39',
'Aring' => '197',
'aring' => '229',
'asymp' => 'x2248',
'Atilde' => '195',
'atilde' => '227',
'Auml' => '196',
'auml' => '228',
'bdquo' => 'x201e',
'Beta' => '914',
'beta' => '946',
'brvbar' => '166',
'bull' => 'x2022',
'cap' => 'x2229',
'Ccedil' => '199',
'ccedil' => '231',
'cedil' => '184',
'cent' => '162',
'Chi' => '935',
'chi' => '967',
'circ' => '710',
'clubs' => 'x2663',
'cong' => 'x2245',
'copy' => '169',
'crarr' => 'x21b5',
'cup' => 'x222a',
'curren' => '164',
'Dagger' => 'x2021',
'dagger' => 'x2020',
'dArr' => 'x21d3',
'darr' => 'x2193',
'deg' => '176',
'Delta' => '916',
'delta' => '948',
'diams' => 'x2666',
'divide' => '247',
'Eacute' => '201',
'eacute' => '233',
'Ecirc' => '202',
'ecirc' => '234',
'Egrave' => '200',
'egrave' => '232',
'empty' => 'x2205',
'emsp' => 'x2003',
'ensp' => 'x2002',
'Epsilon' => '917',
'epsilon' => '949',
'equiv' => 'x2261',
'Eta' => '919',
'eta' => '951',
'ETH' => '208',
'eth' => '240',
'Euml' => '203',
'euml' => '235',
'euro' => 'x20ac',
'exist' => 'x2203',
'fnof' => '402',
'forall' => 'x2200',
'frac12' => '189',
'frac14' => '188',
'frac34' => '190',
'frasl' => 'x2044',
'Gamma' => '915',
'gamma' => '947',
'ge' => 'x2265',
'hArr' => 'x21d4',
'harr' => 'x2194',
'hearts' => 'x2665',
'hellip' => 'x2026',
'Iacute' => '205',
'iacute' => '237',
'Icirc' => '206',
'icirc' => '238',
'iexcl' => '161',
'Igrave' => '204',
'igrave' => '236',
'image' => 'x2111',
'infin' => 'x221e',
'int' => 'x222b',
'Iota' => '921',
'iota' => '953',
'iquest' => '191',
'isin' => 'x2208',
'Iuml' => '207',
'iuml' => '239',
'Kappa' => '922',
'kappa' => '954',
'Lambda' => '923',
'lambda' => '955',
'lang' => 'x2329',
'laquo' => '171',
'lArr' => 'x21d0',
'larr' => 'x2190',
'lceil' => 'x2308',
'ldquo' => 'x201c',
'le' => 'x2264',
'lfloor' => 'x230a',
'lowast' => 'x2217',
'loz' => 'x25ca',
'lrm' => 'x200e',
'lsaquo' => 'x2039',
'lsquo' => 'x2018',
'macr' => '175',
'mdash' => 'x2014',
'micro' => '181',
'middot' => '183',
'minus' => 'x2212',
'Mu' => '924',
'mu' => '956',
'nabla' => 'x2207',
'nbsp' => '160',
'ndash' => 'x2013',
'ne' => 'x2260',
'ni' => 'x220b',
'not' => '172',
'notin' => 'x2209',
'nsub' => 'x2284',
'Ntilde' => '209',
'ntilde' => '241',
'Nu' => '925',
'nu' => '957',
'Oacute' => '211',
'oacute' => '243',
'Ocirc' => '212',
'ocirc' => '244',
'OElig' => '338',
'oelig' => '339',
'Ograve' => '210',
'ograve' => '242',
'oline' => 'x203e',
'Omega' => '937',
'omega' => '969',
'Omicron' => '927',
'omicron' => '959',
'oplus' => 'x2295',
'or' => 'x2228',
'ordf' => '170',
'ordm' => '186',
'Oslash' => '216',
'oslash' => '248',
'Otilde' => '213',
'otilde' => '245',
'otimes' => 'x2297',
'Ouml' => '214',
'ouml' => '246',
'para' => '182',
'part' => 'x2202',
'permil' => 'x2030',
'perp' => 'x22a5',
'Phi' => '934',
'phi' => '966',
'Pi' => '928',
'pi' => '960',
'piv' => '982',
'plusmn' => '177',
'pound' => '163',
'Prime' => 'x2033',
'prime' => 'x2032',
'prod' => 'x220f',
'prop' => 'x221d',
'Psi' => '936',
'psi' => '968',
'radic' => 'x221a',
'rang' => 'x232a',
'raquo' => '187',
'rArr' => 'x21d2',
'rarr' => 'x2192',
'rceil' => 'x2309',
'rdquo' => 'x201d',
'real' => 'x211c',
'reg' => '174',
'rfloor' => 'x230b',
'Rho' => '929',
'rho' => '961',
'rlm' => 'x200f',
'rsaquo' => 'x203a',
'rsquo' => 'x2019',
'sbquo' => 'x201a',
'Scaron' => '352',
'scaron' => '353',
'sdot' => 'x22c5',
'sect' => '167',
'shy' => '173',
'Sigma' => '931',
'sigma' => '963',
'sigmaf' => '962',
'sim' => 'x223c',
'spades' => 'x2660',
'sub' => 'x2282',
'sube' => 'x2286',
'sum' => 'x2211',
'sup' => 'x2283',
'sup1' => '185',
'sup2' => '178',
'sup3' => '179',
'supe' => 'x2287',
'szlig' => '223',
'Tau' => '932',
'tau' => '964',
'there4' => 'x2234',
'Theta' => '920',
'theta' => '952',
'thetasym' => '977',
'thinsp' => 'x2009',
'THORN' => '222',
'thorn' => '254',
'tilde' => '732',
'times' => '215',
'trade' => 'x2122',
'Uacute' => '218',
'uacute' => '250',
'uArr' => 'x21d1',
'uarr' => 'x2191',
'Ucirc' => '219',
'ucirc' => '251',
'Ugrave' => '217',
'ugrave' => '249',
'uml' => '168',
'upsih' => '978',
'Upsilon' => '933',
'upsilon' => '965',
'Uuml' => '220',
'uuml' => '252',
'weierp' => 'x2118',
'Xi' => '926',
'xi' => '958',
'Yacute' => '221',
'yacute' => '253',
'yen' => '165',
'Yuml' => '376',
'yuml' => '255',
'Zeta' => '918',
'zeta' => '950',
'zwj' => 'x200d',
'zwnj' => 'x200c'
) }
#### Blosxom plug-in interface ##########################################
my $_haveBX;
BEGIN {
no warnings 'once';
$_haveBX = defined($blosxom::version);
}
# Set $g_blosxom_use_meta to 1 to use Blosxom's meta plug-in to determine
# which posts Markdown should process, using a "meta-markup: markdown"
# header. If it's set to 0 (the default), Markdown will process all
# entries.
my $g_blosxom_use_meta;
BEGIN {
$g_blosxom_use_meta = 0;
}
sub start { 1; }
sub story {
my($pkg, $path, $filename, $story_ref, $title_ref, $body_ref) = @_;
if ((! $g_blosxom_use_meta) or
(defined($meta::markup) and ($meta::markup =~ /^\s*markdown\s*$/i))
) {
$$body_ref = Markdown($$body_ref);
}
1;
}
#### Movable Type plug-in interface #####################################
my $_haveMT = eval {require MT; 1;}; # Test to see if we're running in MT
my $_haveMT3 = $_haveMT && eval {require MT::Plugin; 1;}; # and MT >= MT 3.0.
if ($_haveMT) {
require MT;
import MT;
require MT::Template::Context;
import MT::Template::Context;
if ($_haveMT3) {
require MT::Plugin;
import MT::Plugin;
my $plugin = new MT::Plugin({
name => "Markdown",
description => "A plain-text-to-HTML formatting plugin. (Version: $VERSION)",
doc_link => 'https://daringfireball.net/projects/markdown/'
});
MT->add_plugin( $plugin );
}
MT::Template::Context->add_container_tag(MarkdownOptions => sub {
my $ctx = shift;
my $args = shift;
my $builder = $ctx->stash('builder');
my $tokens = $ctx->stash('tokens');
if (defined ($args->{'output'}) ) {
$ctx->stash('markdown_output', lc $args->{'output'});
}
defined (my $str = $builder->build($ctx, $tokens) )
or return $ctx->error($builder->errstr);
$str; # return value
});
MT->add_text_filter('markdown' => {
label => 'Markdown',
docs => 'https://daringfireball.net/projects/markdown/',
on_format => sub {
my $text = shift;
my $ctx = shift;
my $raw = 0;
if (defined $ctx) {
my $output = $ctx->stash('markdown_output');
if (defined $output && $output =~ m/^html/i) {
$g_empty_element_suffix = ">";
$ctx->stash('markdown_output', '');
}
elsif (defined $output && $output eq 'raw') {
$raw = 1;
$ctx->stash('markdown_output', '');
}
else {
$raw = 0;
$g_empty_element_suffix = " />";
}
}
$text = $raw ? $text : Markdown($text);
$text;
},
});
# If SmartyPants is loaded, add a combo Markdown/SmartyPants text filter:
my $smartypants;
{
no warnings "once";
$smartypants = $MT::Template::Context::Global_filters{'smarty_pants'};
}
if ($smartypants) {
MT->add_text_filter('markdown_with_smartypants' => {
label => 'Markdown With SmartyPants',
docs => 'https://daringfireball.net/projects/markdown/',
on_format => sub {
my $text = shift;
my $ctx = shift;
if (defined $ctx) {
my $output = $ctx->stash('markdown_output');
if (defined $output && $output eq 'html') {
$g_empty_element_suffix = ">";
}
else {
$g_empty_element_suffix = " />";
}
}
$text = Markdown($text);
$text = $smartypants->($text, '1');
},
});
}
}
sub _tabDefault {
return $_haveBX || $_haveMT ? 4 : 8;
}
sub _strip {
my $str = shift;
defined($str) or return undef;
$str =~ s/^\s+//;
$str =~ s/\s+$//;
$str =~ s/\s+/ /g;
$str;
}
my %_yamlmode;
BEGIN {%_yamlmode = (
disable => 0,
reveal => 1,
enable => 1,
conceal => 1,
show => -1,
unknown => -1,
strip => -1
)}
my %_yamlvis;
BEGIN {%_yamlvis = (
disable => 0,
reveal => 1,
enable => -1,
conceal => 0,
show => 1,
unknown => -1,
strip => 0
)}
sub _require_pod_usage() {
require Pod::Usage;
eval 'require Pod::Text::Termcap; 1;' and
@Pod::Usage::ISA = (qw( Pod::Text::Termcap ));
defined($ENV{PERLDOC}) && $ENV{PERLDOC} ne "" or
$ENV{PERLDOC} = "-oterm -oman";
}
#### BBEdit/command-line text filter interface ##########################
sub _main {
local *ARGV = \@_;
#### Check for command-line switches: #################
my %options = ();
my %cli_opts;
my $raw = 0;
use Getopt::Long;
Getopt::Long::Configure(qw(bundling require_order pass_through));
GetOptions(
'help' => sub {
_require_pod_usage;
Pod::Usage::pod2usage(-verbose => 2, -exitval => 0)},
'h' => sub {
_require_pod_usage;
Pod::Usage::pod2usage(-verbose => 0, -exitval => 0)},
'version|V' => sub { # Version info
print "\nThis is Markdown, version $VERSION $DATE.\n", $COPYRIGHT;
print "License is Modified BSD (aka 3-clause BSD) License\n";
print "<https://opensource.org/licenses/BSD-3-Clause>\n";
exit 0},
'shortversion|short-version|s' => sub { # Just the version number string
print $VERSION;
exit 0},
'html4tags' => \$cli_opts{'html4tags'},
'deprecated' => \$cli_opts{'deprecated'},
'sanitize' => \$cli_opts{'sanitize'},
'no-sanitize' => sub {$cli_opts{'sanitize'} = 0},
'validate-xml' => sub {$cli_opts{'validate-xml'} = 1},
'validate-xml-internal' => sub {$cli_opts{'validate-xml'} = 2},
'no-validate-xml' => sub {$cli_opts{'validate-xml'} = 0},
'stripcommentsstrict|stripcomments-strict|strip-comments-strict' =>
sub {$cli_opts{'stripcomments'} = 1},
'stripcomments|stripcommentslax|stripcomments-lax|strip-comments|strip-comments-lax' =>
sub {$cli_opts{'stripcomments'} = 2},
'stripcommentslaxonly|stripcomments-laxonly|stripcomments-lax-only|strip-comments-lax-only' =>
sub {$cli_opts{'stripcomments'} = 3},
'nostripcomments|no-stripcomments|no-strip-comments' => sub {$cli_opts{'stripcomments'} = 0},
'keepabs|keep-abs|k' => \$cli_opts{'keepabs'},
'absroot|a=s' => \$cli_opts{'absroot'},
'base|b=s' => \$cli_opts{'base'},
'htmlroot|r=s' => \$cli_opts{'htmlroot'},
'imageroot|i=s' => \$cli_opts{'imageroot'},
'div:s' => \$cli_opts{'divname'},
'wiki|w:s' => \$cli_opts{'wiki'},
'tabwidth|tab-width=s' => \$cli_opts{'tabwidth'},
'autonumber|auto-number' => \$cli_opts{'autonumber'},
'raw' => sub { $cli_opts{'raw'} = 1 },
'raw-xml' => sub { $cli_opts{'raw'} = 1 },
'raw-html' => sub { $cli_opts{'raw'} = 2 },
'stylesheet|style-sheet' => \$cli_opts{'stylesheet'},
'no-stylesheet|no-style-sheet' => sub {$cli_opts{'stylesheet'} = 0},
'keep-named-character-entities' => \$cli_opts{'keepcharents'},
'no-keep-named-character-entities' => sub {$cli_opts{'keepcharents'} = 0},
'us-ascii|ascii' => \$cli_opts{'us_ascii'},
'no-us-ascii|no-ascii' => sub {$cli_opts{'us_ascii'} = 0},
'stub' => \$cli_opts{'stub'},
'yaml:s' => \$cli_opts{'yaml'},
);
defined($cli_opts{'raw'}) or $cli_opts{'raw'} = 0;
my $stub = 0;
if ($cli_opts{'stub'}) {
$stub = 1;
}
if ($cli_opts{'html4tags'}) { # Use HTML tag style instead of XHTML
$options{empty_element_suffix} = ">";
$stub = -$stub;
}
if ($cli_opts{'deprecated'}) { # Allow <dir> and <menu> tags to pass through
_SetAllowedTag("dir");
_SetAllowedTag("menu");
}
my $xmlcheck;
$options{'keep_named_character_entities'} = $cli_opts{'keepcharents'} ? "1" : 0;
$options{'us_ascii'} = $cli_opts{'us_ascii'} ? "1" : 0;
$options{divwrap} = defined($cli_opts{'divname'});
$options{divname} = defined($cli_opts{'divname'}) ? $cli_opts{'divname'} : "";
$options{sanitize} = 1; # sanitize by default
$options{sanitize} = $cli_opts{'sanitize'} if defined($cli_opts{'sanitize'});
$xmlcheck = $options{sanitize} ? 2 : 0;
$xmlcheck = $cli_opts{'validate-xml'} if defined($cli_opts{'validate-xml'});
$options{stripcomments} = $cli_opts{'stripcomments'} if defined($cli_opts{'stripcomments'});
die "--html4tags and --validate-xml are incompatible\n"
if $cli_opts{'html4tags'} && $xmlcheck == 1;
die "--no-sanitize and --validate-xml-internal are incompatible\n"
if !$options{'sanitize'} && $xmlcheck == 2;
die "--no-sanitize and --strip-comments are incompatible\n"
if !$options{'sanitize'} && $options{stripcomments};
die "--raw-html requires --validate-xml-internal\n"
if $cli_opts{'raw'} == 2 && $xmlcheck != 2;
if ($xmlcheck == 1) {
eval { require XML::Simple; 1 } and $hasxml = 1 or $hasxml_err = $@;
eval { require XML::Parser; 1 } and $hasxmlp = 1 or $hasxmlp_err = $@ unless $hasxml;
die "$hasxml_err$hasxmlp_err" unless $hasxml || $hasxmlp;
}
if ($cli_opts{'tabwidth'}) {
my $tw = $cli_opts{'tabwidth'};
die "invalid tab width (must be integer)\n" unless looks_like_number $tw;
die "invalid tab width (must be >= 2 and <= 32)\n" unless $tw >= 2 && $tw <= 32;
$options{tab_width} = int(0+$tw);
}
$options{auto_number} = 6 if $cli_opts{'autonumber'};
$options{keepabs} = $cli_opts{'keepabs'};
$options{abs_prefix} = ""; # no abs prefix by default
if ($cli_opts{'absroot'}) { # Use abs prefix for absolute path URLs
my $abs = $cli_opts{'absroot'};
$abs =~ s{/+$}{};
$options{abs_prefix} = $abs;
}
$options{base_prefix} = ""; # no base prefix by default
if ($cli_opts{'base'}) { # Use base prefix for fragment URLs
$options{base_prefix} = $cli_opts{'base'};
}
if ($cli_opts{'htmlroot'}) { # Use URL prefix
$options{url_prefix} = $cli_opts{'htmlroot'};
}
if ($cli_opts{'imageroot'}) { # Use image URL prefix
$options{img_prefix} = $cli_opts{'imageroot'};
}
SetWikiOpts(\%options, $cli_opts{'wiki'}); # Set wiki links options
if (ref($options{wikiopt}) eq 'HASH') {
my $o = $options{wikiopt};
$o->{"f"} && $o->{"%"} and
die "--wiki sub-options 'f' and '%' are mutually exclusive\n"
}
if ($cli_opts{'raw'}) {
$raw = 1;
$options{htmlauto} = 1 if $cli_opts{'raw'} == 2;
}
$options{show_styles} = $cli_opts{'stylesheet'} if defined($cli_opts{'stylesheet'});
$options{show_styles} = 1 if $stub && !defined($options{show_styles});
$options{tab_width} = 8 unless defined($options{tab_width});
my $ym = $cli_opts{'yaml'};
defined($ym) && $ym ne "" or $ym = "enable";
my $lcym = lc($ym);
exists($_yamlmode{$lcym}) or die "invalid --yaml= value '$ym'\n";
$options{yamlmode} = $_yamlmode{$lcym};
$options{yamlvis} = $_yamlvis{$lcym};
my $hdrf = sub {
my $out = "";
if ($stub > 0) {
$out .= <<'HTML5';
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
HTML5
} elsif ($stub < 0) {
$out .= <<'HTML4';
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
HTML4
}
if ($stub && ($options{title} || $options{h1})) {
my $title = $options{title};
defined($title) && $title ne "" or $title = $options{h1};
if (defined($title) && $title ne "") {
$title =~ s/&/&/g;
$title =~ s/</</g;
$out .= "<title>$title</title>\n";
}
}
$out .= GenerateStyleSheet($g_style_prefix) if $options{show_styles};
if ($stub) {
$out .= "</head>\n<body style=\"text-align:center\">\n" .
"<div style=\"display:inline-block;text-align:left;max-width:42pc\">\n";
}
$out;
};
#### Process incoming text: ###########################
my ($didhdr, $hdr, $result, $ftr) = (0, "", "", "");
@ARGV or push(@ARGV, "-");
foreach (@ARGV) {
my ($fh, $contents, $oneresult);
$_ eq "-" or open $fh, '<', $_ or fauxdie "could not open \"$_\": $!\n";
{
local $/; # Slurp the whole file
$_ eq "-" and $contents = <STDIN>;
$_ ne "-" and $contents = <$fh>;
}
defined($contents) or fauxdie "could not read \"$_\": $!\n";
$_ eq "-" or close($fh);
$options{xmlcheck} = ($xmlcheck == 2) ? 2 : 0;
$oneresult = $raw ? ProcessRaw($contents, \%options) : Markdown($contents, \%options);
$oneresult =~ s/\s+$//os;
if ($oneresult ne "") {
if (!$didhdr && !$raw) {
$hdr = &$hdrf();
$didhdr = 1;
}
$result .= $oneresult . "\n";
}
}
$hdr = &$hdrf() unless $didhdr || $raw;
$ftr = "</div>\n</body>\n</html>\n" if $stub && !$raw;
if ($xmlcheck == 1) {
my ($good, $errs);
if ($stub && !$raw) {
($good, $errs) = _xmlcheck($hdr.$result.$ftr);
} else {
($good, $errs) = _xmlcheck("<div>".$result."</div>");
}
$good or die $errs;
}
print $hdr, $result, $ftr;
exit 0;
}
# INPUT
# $1: HASH ref
# $2: value of --wiki= option (see docs) except
# that a value of undef turns off wiki links
# OUTPUT
# $1->{wikipat}
# $1->{wikiopt}
#
sub SetWikiOpts {
my ($o, $wpat) = @_;
ref($o) eq "HASH" or die "internal error: first arg to SetWikiOpts must be HASH ref";
delete $o->{wikipat};
delete $o->{wikiopt};
defined($wpat) or return;
# Parse wiki links option setting
my $wopt = "s(:md)";
if ($wpat =~ /^(.*?)%\{((?:[%0-9A-Za-z]|[Ss]\([^)]*\))*)\}(.*)$/) {
$o->{wikipat} = $1 . "%{}" . $3;
$wopt = $2;
} else {
$o->{wikipat} = $wpat . "%{}.html";
}
my $sval = 1;
while ($wopt =~ /^(.*?)s\(([^)]*)\)(.*)$/i) {
my $sarg = $2;
$wopt = $1 . "s" . $3;
$sarg =~ s/^\s+//; $sarg =~ s/\s+$//;
$sval = {} unless ref($sval) eq "HASH";
s/^\.//, $sval->{lc($_)}=1 foreach split(/(?:\s*,\s*)|(?:(?<!,)\s+(?!,))/, $sarg);
$sval = 1 unless scalar(keys(%$sval));
}
$o->{wikiopt} = { map({$_ => 1} split(//,lc($wopt))) };
if (ref($sval) eq "HASH" && $sval->{':md'}) {
delete $sval->{':md'};
$sval->{$_} = 1 foreach qw(md rmd mkd mkdn mdwn mdown markdown litcoffee);
}
$o->{wikiopt}->{'s'} = $sval if $o->{wikiopt}->{'s'};
}
# Return a copy of the fancy CSS style sheet that uses the
# passed in prefix as a prefix for the CSS style names.
# If no argument is passed in, use $g_style_prefix
# as the CSS style name prefix.
sub GenerateStyleSheet {
my $prefix = shift;
defined($prefix) or $prefix = $g_style_prefix;
my $stylesheet = $g_style_sheet;
$stylesheet =~ s/%\(base\)/$prefix/g;
return $stylesheet;
}
sub _xmlcheck {
my $text = shift;
my ($good, $errs);
($hasxml ? eval { XML::Simple::XMLin($text, KeepRoot => 1) && 1 } :
eval {
my $p = XML::Parser->new(Style => 'Tree', ErrorContext => 1);
$p->parse($text) && 1;
}) and $good = 1 or $errs = _trimerr($@);
($good, $errs);
}
sub _trimerr {
my $err = shift;
1 while $err =~ s{\s+at\s+\.?/[^,\s\n]+\sline\s+[0-9]+\.?(\n|$)}{$1}is;
$err =~ s/\s+$//os;
$err . "\n";
}
sub _PrepareInput {
my ($input,$parseyaml) = @_;
defined $input or $input = "";
{
use bytes;
$input =~ s/[\x00-\x08\x0B\x0E-\x1F\x7F]+//gso;
}
my $output;
if (Encode::is_utf8($input) || utf8::decode($input)) {
$output = $input;
} else {
$output = $encoder->decode($input, Encode::FB_DEFAULT);
}
# Standardize line endings:
$output =~ s{\r\n}{\n}g; # DOS to Unix
$output =~ s{\r}{\n}g; # Mac to Unix
# Extract YAML front matter if requested
my $yaml = undef;
if ($parseyaml) {
$yaml = {};
if ($output =~ /^---[ \t]*(?:\n|\z)/g) {
until ($output =~ /\G(?:(?:(?:---)|(?:\.\.\.))[ \t]*(?:\n|\z)|\z)/gc) {
next if $output =~ m"\G[ \t]*(?:#[^\n]*)?\n"gc; # skip comment lines
next if $output =~ m"\G[ \t]*(?:#[^\n]*)\z"gc; # skip final no EOL comment
last unless $output =~ /\G([^\n]+)(?:\n|\z)/gc;
my $yl = $1;
if ($yl =~ /^([A-Za-z_][A-Za-z_0-9.-]*):[ \t]+(.*)$/os) {
my ($k, $v) = ($1, $2);
$yaml->{lc($k)} = _YAMLvalue($2);
}
}
$output = substr($output, pos($output));
}
}
return wantarray ? ($output, $yaml) : $output;
}
sub _YAMLvalue {
my $v = shift;
$v =~ s/^\s+//;
if (substr($v, 0, 1) eq '"') {
# only $ and/or @ present issues, map them
$v =~ tr/\@\$/\036\037/;
eval '{$v='.$v."\n}1" or $v = undef;
$v =~ tr/\036\037/\@\$/ if defined($v);
} else {
$v =~ s"#.*$""os;
$v =~ s/\s+$//os;
$v ne "" or $v = undef;
}
return $v;
}
sub ProcessRaw {
my $text = _PrepareInput(shift);
# Any remaining arguments after the first are options; either a single
# hashref or a list of name, value pairs. See _SanitizeOpts comments.
%opt = (
empty_element_suffix => $g_empty_element_suffix,
);
my %args = ();
if (ref($_[0]) eq "HASH") {
%args = %{$_[0]};
} else {
%args = @_;
}
while (my ($k,$v) = each %args) {
$opt{$k} = $v;
}
_SanitizeOpts(\%opt);
# Sanitize all '<'...'>' tags if requested
$text = _SanitizeTags($text, $opt{xmlcheck}, $opt{htmlauto}) if $opt{sanitize};
# Eliminate known named character entities
$opt{keep_named_character_entities} or
$text = ConvertNamedCharacterEntities($text);
# Convert to US-ASCII only if requested
$opt{us_ascii} and
$text = ConvertToASCII($text);
utf8::encode($text);
if ($opt{divwrap}) {
my $id = $opt{divname};
defined($id) or $id = "";
$id eq "" or $id = ' id="'.escapeXML($id).'"';
chomp($text);
return "<div$id>\n".$text."\n</div>\n";
}
return $text;
}
# $1: HASH ref with the following key value semantics
#
# sanitize => any-false-value (no action), any-true-value (sanitize).
# note that a true value of xmlcheck or a true value of
# stripcomments or a urlfunc value that is a CODE ref
# always forces sanitize to activate.
# tag attributes are sanitized by removing all "questionable"
# attributes (such as script attributes, unknown attributes
# and so forth) and normalizing the remaining ones (i.e.
# adding missing quotes and/or values etc.).
# effective for both ProcessRaw and Markdown.
# xmlcheck => 0 (no check), any-true-value (internal check).
# note that the default if xmlcheck is not set/valid is 2.
# note that a true value is effective for both ProcessRaw
# and Markdown. note that a true value automatically inserts
# the closing tag for auto-closing tags and converts empty tags
# to the correct format converting empty tags that shouldn't be
# to an open and close pair; since xmlcheck is a function of the
# sanitizer, tag attributes are also always sanitized whenever
# xmlcheck has a true value.
# note that a true xmlcheck value WILL call "die" with a
# detailed indication of the error(s) if xml validation fails
# in which case any line/column numbers refer to the text that
# would be produced by a sanitize=>0, xmlcheck=>0 call to
# either ProcessRaw or Markdown, NOT the original input text.
# htmlauto => any-false-value (no auto close), any-true-value (auto-close)
# only effective for ProcessRaw; always enabled for Markdown.
# when xmlcheck is set to 2 provide html automatic closing tag
# and optional closing tag semantics where closing tags are
# automatically inserted when encountering an opening tag that
# auto closes a currently open tag and tags with an optional
# closing tag that's missing have that inserted as appropriate.
# a true value may result in some texts being rejected that