4 # Markdown -- A text-to-HTML conversion tool for web writers
6 # Copyright (C) 2004 John Gruber
7 # Copyright (C) 2015,2016 Kyle J. McKay
15 close(DATA
) if fileno(DATA
);
18 use Digest
::MD5
qw(md5_hex);
19 use File
::Basename
qw(basename);
20 use vars
qw($VERSION @ISA @EXPORT_OK);
22 @EXPORT_OK = qw(Markdown);
23 $INC{__PACKAGE__
.'.pm'} = $INC{basename
(__FILE__
)} unless exists $INC{__PACKAGE__
.'.pm'};
29 ## Disabled; causes problems under Perl 5.6.1:
31 # binmode( STDOUT, ":utf8" ); # c.f.: http://acis.openlib.org/dev/perl-unicode-struggle.html
35 # Global default settings:
37 my $g_empty_element_suffix = " />"; # Change to ">" for HTML output
38 my $g_tab_width = 4; # Legacy even though it's wrong
45 # Regex to match balanced [brackets]. See Friedl's
46 # "Mastering Regular Expressions", 2nd Ed., pp. 328-331.
47 my $g_nested_brackets;
48 $g_nested_brackets = qr{
50 [^\
[\
]]+ # Anything other than brackets
53 (??
{ $g_nested_brackets }) # Recursive set of nested brackets
59 # Table of hash values for escaped characters:
61 foreach my $char (split //, "\\\`*_{}[]()>#+-.!~") {
62 $g_escape_table{$char} = md5_hex
($char);
66 # Global hashes, used by various utility routines
72 # Used to track when we're inside an ordered or unordered list
73 # (see _ProcessListItems() for details):
77 #### Blosxom plug-in interface ##########################################
79 # Set $g_blosxom_use_meta to 1 to use Blosxom's meta plug-in to determine
80 # which posts Markdown should process, using a "meta-markup: markdown"
81 # header. If it's set to 0 (the default), Markdown will process all
83 my $g_blosxom_use_meta = 0;
87 my($pkg, $path, $filename, $story_ref, $title_ref, $body_ref) = @_;
89 if ( (! $g_blosxom_use_meta) or
90 (defined($meta::markup
) and ($meta::markup
=~ /^\s*markdown\s*$/i))
92 $$body_ref = Markdown
($$body_ref);
98 #### Movable Type plug-in interface #####################################
99 eval {require MT
}; # Test to see if we're running in MT.
103 require MT
::Template
::Context
;
104 import MT
::Template
::Context
;
106 eval {require MT
::Plugin
}; # Test to see if we're running >= MT 3.0.
110 my $plugin = new MT
::Plugin
({
112 description
=> "A plain-text-to-HTML formatting plugin. (Version: $VERSION)",
113 doc_link
=> 'http://daringfireball.net/projects/markdown/'
115 MT
->add_plugin( $plugin );
118 MT
::Template
::Context
->add_container_tag(MarkdownOptions
=> sub {
121 my $builder = $ctx->stash('builder');
122 my $tokens = $ctx->stash('tokens');
124 if (defined ($args->{'output'}) ) {
125 $ctx->stash('markdown_output', lc $args->{'output'});
128 defined (my $str = $builder->build($ctx, $tokens) )
129 or return $ctx->error($builder->errstr);
133 MT
->add_text_filter('markdown' => {
135 docs
=> 'http://daringfireball.net/projects/markdown/',
141 my $output = $ctx->stash('markdown_output');
142 if (defined $output && $output =~ m/^html/i) {
143 $g_empty_element_suffix = ">";
144 $ctx->stash('markdown_output', '');
146 elsif (defined $output && $output eq 'raw') {
148 $ctx->stash('markdown_output', '');
152 $g_empty_element_suffix = " />";
155 $text = $raw ?
$text : Markdown
($text);
160 # If SmartyPants is loaded, add a combo Markdown/SmartyPants text filter:
165 $smartypants = $MT::Template
::Context
::Global_filters
{'smarty_pants'};
169 MT
->add_text_filter('markdown_with_smartypants' => {
170 label
=> 'Markdown With SmartyPants',
171 docs
=> 'http://daringfireball.net/projects/markdown/',
176 my $output = $ctx->stash('markdown_output');
177 if (defined $output && $output eq 'html') {
178 $g_empty_element_suffix = ">";
181 $g_empty_element_suffix = " />";
184 $text = Markdown
($text);
185 $text = $smartypants->($text, '1');
191 #### BBEdit/command-line text filter interface ##########################
192 # Needs to be hidden from MT (and Blosxom when running in static mode).
194 # We're only using $blosxom::version once; tell Perl not to warn us:
196 unless ( defined($blosxom::version
) ) {
199 #### Check for command-line switches: #################
203 Getopt
::Long
::Configure
('pass_through');
204 GetOptions
(\
%cli_opts,
207 'shortversion|short-version|s',
212 if ($cli_opts{'help'}) {
215 if ($cli_opts{'version'}) { # Version info
216 print "\nThis is Markdown, version $VERSION.\n";
217 print "Copyright (C) 2004 John Gruber\n";
218 print "Copyright (C) 2015 Kyle J. McKay\n";
221 if ($cli_opts{'shortversion'}) { # Just the version number string.
225 if ($cli_opts{'html4tags'}) { # Use HTML tag style instead of XHTML
226 $options{empty_element_suffix
} = ">";
228 if ($cli_opts{'htmlroot'}) { # Use URL prefix
229 $options{url_prefix
} = $cli_opts{'htmlroot'};
231 if ($cli_opts{'imageroot'}) { # Use image URL prefix
232 $options{img_prefix
} = $cli_opts{'imageroot'};
236 #### Process incoming text: ###########################
239 local $/; # Slurp the whole file
242 print Markdown
($text, \
%options);
250 # Main function. The order in which other subs are called here is
251 # essential. Link and image substitutions need to happen before
252 # _EscapeSpecialChars(), so that any *'s or _'s in the <a>
253 # and <img> tags get encoded.
256 defined $text or $text='';
258 # Any remaining arguments after the first are options; either a single
259 # hashref or a list of name, value paurs.
261 # set initial defaults
262 empty_element_suffix
=> $g_empty_element_suffix,
263 tab_width
=> $g_tab_width,
264 url_prefix
=> "", # Prefixed to non-absolute URLs
265 img_prefix
=> "", # Prefixed to non-absolute image URLs
268 if (ref($_[0]) eq "HASH") {
273 while (my ($k,$v) = each %args) {
277 # Clear the globals. If we don't clear these, you get conflicts
278 # from other articles when generating a page which contains more than
279 # one article (e.g. an index page that shows the N most recent
286 # Standardize line endings:
287 $text =~ s{\r\n}{\n}g; # DOS to Unix
288 $text =~ s{\r}{\n}g; # Mac to Unix
290 # Make sure $text ends with a couple of newlines:
293 # Handle backticks-delimited code blocks
294 $text = _HashBTCodeBlocks
($text);
296 # Convert all tabs to spaces.
297 $text = _Detab
($text);
299 # Strip any lines consisting only of spaces and tabs.
300 # This makes subsequent regexen easier to write, because we can
301 # match consecutive blank lines with /\n+/ instead of something
302 # contorted like /[ \t]*\n+/ .
303 $text =~ s/^[ \t]+$//mg;
305 # Turn block-level HTML blocks into hash entries
306 $text = _HashHTMLBlocks
($text);
308 # Strip link definitions, store in hashes.
309 $text = _StripLinkDefinitions
($text);
311 $text = _RunBlockGamut
($text);
313 $text = _UnescapeSpecialChars
($text);
319 sub _HashBTCodeBlocks
{
321 # Process Markdown backticks (```) delimited code blocks
327 ``(`+)[ \t]*(?:([\w.+-]+)[ \t]*)?\n
328 ( # $3 = the code block -- one or more lines, starting with ```
333 (?
:(?
:``\
1[ \t]*(?
:\n|\Z
))|\Z
) # and ending with ``` or end of document
335 # $2 contains syntax highlighting to use if defined
337 $codeblock =~ s/[ \t]+$//mg; # trim trailing spaces on lines
338 $codeblock = _Detab
($codeblock, 8); # physical tab stops are always 8
339 $codeblock =~ s/\A\n+//; # trim leading newlines
340 $codeblock =~ s/\s+\z//; # trim trailing whitespace
341 $codeblock = _EncodeCode
($codeblock); # or run highlighter here
342 $codeblock = "<pre><code>" . $codeblock . "\n</code></pre>";
344 my $key = md5_hex
($codeblock);
345 $g_html_blocks{$key} = $codeblock;
346 "\n\n" . $key . "\n\n";
353 sub _StripLinkDefinitions
{
355 # Strips link definitions from text, stores the URLs and titles in
359 my $less_than_tab = $opt{tab_width
} - 1;
361 # Link defs are in the form: ^[id]: url "optional title"
363 ^[ ]{0,$less_than_tab}\
[(.+)\
]: # id = $1
365 \n?
# maybe *one* newline
367 <?
(\S
+?
)>?
# url = $2
369 \n?
# maybe one newline
372 (?
<=\s
) # lookbehind for whitespace
377 )?
# title is optional
381 $g_urls{lc $1} = _EncodeAmpsAndAngles
( $2 ); # Link IDs are case-insensitive
383 $g_titles{lc $1} = $3;
384 $g_titles{lc $1} =~ s/\042/"/g;
392 sub _HashHTMLBlocks
{
394 my $less_than_tab = $opt{tab_width
} - 1;
396 # Hashify HTML blocks:
397 # We only want to do this for block-level HTML tags, such as headers,
398 # lists, and tables. That's because we still want to wrap <p>s around
399 # "paragraphs" that are wrapped in non-block-level tags, such as anchors,
400 # phrase emphasis, and spans. The list of tags we're looking for is
402 my $block_tags_a = qr/p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del/;
403 my $block_tags_b = qr/p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math/;
405 # First, look for nested blocks, e.g.:
408 # tags for inner block must be indented.
412 # The outermost tags must start at the left margin for this to match, and
413 # the inner nested divs must be indented.
414 # We need to do this before the next, more liberal match, because the next
415 # match will start at the first `<div>` and stop at the first `</div>`.
418 ^ # start of line (with /m)
419 <($block_tags_a) # start tag = $2
421 (.*\n)*?
# any number of lines, minimally matching
422 </\
2> # the matching end tag
423 [ \t]* # trailing spaces/tabs
424 (?
=\n+|\Z
) # followed by a newline or end of document
427 my $key = md5_hex
($1);
428 $g_html_blocks{$key} = $1;
429 "\n\n" . $key . "\n\n";
434 # Now match more liberally, simply from `\n<tag>` to `</tag>\n`
438 ^ # start of line (with /m)
439 <($block_tags_b) # start tag = $2
441 (.*\n)*?
# any number of lines, minimally matching
442 .*</\
2> # the matching end tag
443 [ \t]* # trailing spaces/tabs
444 (?
=\n+|\Z
) # followed by a newline or end of document
447 my $key = md5_hex
($1);
448 $g_html_blocks{$key} = $1;
449 "\n\n" . $key . "\n\n";
451 # Special case just for <hr />. It was easier to make a special case than
452 # to make the other regex more complicated.
455 (?
<=\n\n) # Starting after a blank line
457 \A
\n?
# the beginning of the doc
460 [ ]{0,$less_than_tab}
461 <(hr
) # start tag = $2
464 /?
> # the matching end tag
466 (?
=\n{2,}|\Z
) # followed by a blank line or end of document
469 my $key = md5_hex
($1);
470 $g_html_blocks{$key} = $1;
471 "\n\n" . $key . "\n\n";
474 # Special case for standalone HTML comments:
477 (?
<=\n\n) # Starting after a blank line
479 \A
\n?
# the beginning of the doc
482 [ ]{0,$less_than_tab}
489 (?
=\n{2,}|\Z
) # followed by a blank line or end of document
492 my $key = md5_hex
($1);
493 $g_html_blocks{$key} = $1;
494 "\n\n" . $key . "\n\n";
504 # These are all the transformations that form block-level
505 # tags like paragraphs, headers, and list items.
509 $text = _DoHeaders
($text);
511 # Do Horizontal Rules:
512 $text =~ s{^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$}{\n<hr$opt{empty_element_suffix}\n}gmx
;
513 $text =~ s{^[ ]{0,2}([ ]? -[ ]?){3,}[ \t]*$}{\n<hr$opt{empty_element_suffix}\n}gmx
;
514 $text =~ s{^[ ]{0,2}([ ]? _[ ]?){3,}[ \t]*$}{\n<hr$opt{empty_element_suffix}\n}gmx
;
516 $text = _DoLists
($text);
518 $text = _DoCodeBlocks
($text);
520 $text = _DoBlockQuotes
($text);
522 # We already ran _HashHTMLBlocks() before, in Markdown(), but that
523 # was to escape raw HTML in the original Markdown source. This time,
524 # we're escaping the markup we've just created, so that we don't wrap
525 # <p> tags around block-level tags.
526 $text = _HashHTMLBlocks
($text);
528 $text = _FormParagraphs
($text);
536 # These are all the transformations that occur *within* block-level
537 # tags like paragraphs, headers, and list items.
541 $text = _DoCodeSpans
($text);
543 $text = _EscapeSpecialChars
($text);
545 # Process anchor and image tags. Images must come first,
546 # because ![foo][f] looks like an anchor.
547 $text = _DoImages
($text);
548 $text = _DoAnchors
($text);
550 # Make links out of things like `<http://example.com/>`
551 # Must come after _DoAnchors(), because you can use < and >
552 # delimiters in inline links like [this](<url>).
553 $text = _DoAutoLinks
($text);
555 $text = _EncodeAmpsAndAngles
($text);
557 $text = _DoItalicsAndBoldAndStrike
($text);
560 $text =~ s/ {2,}\n/ <br$opt{empty_element_suffix}\n/g;
566 sub _EscapeSpecialChars
{
568 my $tokens ||= _TokenizeHTML
($text);
570 $text = ''; # rebuild $text from the tokens
571 # my $in_pre = 0; # Keep track of when we're inside <pre> or <code> tags.
572 # my $tags_to_skip = qr!<(/?)(?:pre|code|kbd|script|math)[\s>]!;
574 foreach my $cur_token (@
$tokens) {
575 if ($cur_token->[0] eq "tag") {
576 # Within tags, encode *, _ and ~ so they don't conflict
577 # with their use in Markdown for italics and strong.
578 # We're replacing each such character with its
579 # corresponding MD5 checksum value; this is likely
580 # overkill, but it should prevent us from colliding
581 # with the escape values by accident.
582 $cur_token->[1] =~ s! \* !$g_escape_table{'*'}!gx;
583 $cur_token->[1] =~ s! _ !$g_escape_table{'_'}!gx;
584 $cur_token->[1] =~ s! ~ !$g_escape_table{'~'}!gx;
585 $text .= $cur_token->[1];
587 my $t = $cur_token->[1];
588 $t = _EncodeBackslashEscapes
($t);
598 # Turn Markdown link shortcuts into XHTML <a> tags.
603 # First, handle reference-style links: [link text] [id]
606 ( # wrap whole match in $1
608 ($g_nested_brackets) # link text = $2
611 [ ]?
# one optional space
612 (?
:\n[ ]*)?
# one optional newline followed by spaces
620 my $whole_match = $1;
624 if ($link_id eq "") {
625 $link_id = lc $link_text; # for shortcut links like [this][].
628 if (defined $g_urls{$link_id}) {
629 my $url = _PrefixURL
($g_urls{$link_id});
630 $url =~ s! \* !$g_escape_table{'*'}!gx; # We've got to encode these to avoid
631 $url =~ s! _ !$g_escape_table{'_'}!gx; # conflicting with italics, bold
632 $url =~ s! ~ !$g_escape_table{'~'}!gx; # and strike through.
633 $result = "<a href=\"$url\"";
634 if ( defined $g_titles{$link_id} ) {
635 my $title = $g_titles{$link_id};
636 $title =~ s! \* !$g_escape_table{'*'}!gx;
637 $title =~ s! _ !$g_escape_table{'_'}!gx;
638 $title =~ s! ~ !$g_escape_table{'~'}!gx;
639 $result .= " title=\"$title\"";
641 $result .= ">$link_text</a>";
644 $result = $whole_match;
650 # Next, inline-style links: [link text](url "optional title")
653 ( # wrap whole match in $1
655 ($g_nested_brackets) # link text = $2
659 <?
(.*?
)>?
# href = $3
662 (['\042]) # quote char = $5
665 )? # title is optional
670 my $whole_match = $1;
675 $url = _PrefixURL($url);
676 $url =~ s! \* !$g_escape_table{'*'}!gx; # We've got to encode these to avoid
677 $url =~ s! _ !$g_escape_table{'_'}!gx; # conflicting with italics, bold
678 $url =~ s! ~ !$g_escape_table{'~'}!gx; # and strike through.
679 $result = "<a href=\"$url\"";
681 if (defined $title) {
682 $title =~ s/\042/"/g;
683 $title =~ s! \* !$g_escape_table{'*'}!gx;
684 $title =~ s! _ !$g_escape_table{'_'}!gx;
685 $title =~ s! ~ !$g_escape_table{'~'}!gx;
686 $result .= " title=\"$title\"";
689 $result .= ">$link_text</a>";
700 # Turn Markdown image shortcuts into <img> tags.
705 # First, handle reference-style labeled images: ![alt text][id]
708 ( # wrap whole match in $1
710 (.*?
) # alt text = $2
713 [ ]?
# one optional space
714 (?
:\n[ ]*)?
# one optional newline followed by spaces
723 my $whole_match = $1;
727 if ($link_id eq "") {
728 $link_id = lc $alt_text; # for shortcut links like ![this][].
731 $alt_text =~ s/"/"/g;
732 if (defined $g_urls{$link_id}) {
733 my $url = _PrefixURL
($g_urls{$link_id});
734 $url =~ s! \* !$g_escape_table{'*'}!gx; # We've got to encode these to avoid
735 $url =~ s! _ !$g_escape_table{'_'}!gx; # conflicting with italics, bold
736 $url =~ s! ~ !$g_escape_table{'~'}!gx; # and strike through.
737 $result = "<img src=\"$url\" alt=\"$alt_text\"";
738 if (defined $g_titles{$link_id}) {
739 my $title = $g_titles{$link_id};
740 $title =~ s! \* !$g_escape_table{'*'}!gx;
741 $title =~ s! _ !$g_escape_table{'_'}!gx;
742 $title =~ s! ~ !$g_escape_table{'~'}!gx;
743 $result .= " title=\"$title\"";
745 $result .= $opt{empty_element_suffix
};
748 # If there's no such link ID, leave intact:
749 $result = $whole_match;
756 # Next, handle inline images: ![alt text](url "optional title")
757 # Don't forget: encode * and _
760 ( # wrap whole match in $1
762 (.*?
) # alt text = $2
766 <?
(\S
+?
)>?
# src url = $3
769 (['\042]) # quote char = $5
773 )? # title is optional
778 my $whole_match = $1;
786 $url = _PrefixURL($url);
787 $alt_text =~ s/"/"/g;
788 $title =~ s/"/"/g;
789 $url =~ s! \* !$g_escape_table{'*'}!gx; # We've got to encode these to avoid
790 $url =~ s! _ !$g_escape_table{'_'}!gx; # conflicting with italics, bold
791 $url =~ s! ~ !$g_escape_table{'~'}!gx; # and strike through.
792 $result = "<img src=\"$url\" alt=\"$alt_text\"";
793 if (defined $title) {
794 $title =~ s! \* !$g_escape_table{'*'}!gx;
795 $title =~ s! _ !$g_escape_table{'_'}!gx;
796 $title =~ s! ~ !$g_escape_table{'~'}!gx;
797 $result .= " title=\"$title\"";
799 $result .= $opt{empty_element_suffix
};
811 # Setext-style headers:
821 $text =~ s
{ ^(?
:=+[ \t]*\n)?
(.+)[ \t]*\n=+[ \t]*\n+ }{
822 "<h1>" . _RunSpanGamut
($1) . "</h1>\n\n";
825 $text =~ s
{ ^(?
:-+[ \t]*\n)?
(.+)[ \t]*\n-+[ \t]*\n+ }{
826 "<h2>" . _RunSpanGamut
($1) . "</h2>\n\n";
829 $text =~ s
{ ^(?
:~+[ \t]*\n)?
(.+)[ \t]*\n~+[ \t]*\n+ }{
830 "<h3>" . _RunSpanGamut
($1) . "</h3>\n\n";
837 # ## Header 2 with closing hashes ##
842 ^(\#
{1,6}) # $1 = string of #'s
844 (.+?
) # $2 = Header text
846 \#
* # optional closing #'s (not counted)
849 my $h_level = length($1);
850 "<h$h_level>" . _RunSpanGamut
($2) . "</h$h_level>\n\n";
859 # Form HTML ordered (numbered) and unordered (bulleted) lists.
862 my $less_than_tab = $opt{tab_width
} - 1;
864 # Re-usable patterns to match list item bullets and number markers:
865 my $marker_ul = qr/[*+-]/;
866 my $marker_ol = qr/\d+[.]/;
867 my $marker_any = qr/(?:$marker_ul|$marker_ol)/;
869 # Re-usable pattern to match any entirel ul or ol list:
873 [ ]{0,$less_than_tab}
874 (${marker_any
}) # $3 = first list item marker
883 (?
! # Negative lookahead for another list item marker
891 # We use a different prefix before nested lists than top-level lists.
892 # See extended comment in _ProcessListItems().
894 # Note: There's a bit of duplication here. My original implementation
895 # created a scalar regex pattern as the conditional result of the test on
896 # $g_list_level, and then only ran the $text =~ s{...}{...}egmx
897 # substitution once, using the scalar as the pattern. This worked,
898 # everywhere except when running under MT on my hosting account at Pair
899 # Networks. There, this caused all rebuilds to be killed by the reaper (or
900 # perhaps they crashed, but that seems incredibly unlikely given that the
901 # same script on the same server ran fine *except* under MT. I've spent
902 # more time trying to figure out why this is happening than I'd like to
903 # admit. My only guess, backed up by the fact that this workaround works,
904 # is that Perl optimizes the substition when it can figure out that the
905 # pattern will never change, and when this optimization isn't on, we run
906 # afoul of the reaper. Thus, the slightly redundant code to that uses two
907 # static s/// patterns rather than one conditional pattern.
915 my $list_type = ($3 =~ m/$marker_ul/) ?
"ul" : "ol";
916 # Turn double returns into triple returns, so that we can make a
917 # paragraph for the last item in a list, if necessary:
918 $list =~ s/\n{2,}/\n\n\n/g;
919 my $result = _ProcessListItems
($list, $marker_any);
920 $result = "<$list_type>\n" . $result . "</$list_type>\n";
930 my $list_type = ($3 =~ m/$marker_ul/) ?
"ul" : "ol";
931 # Turn double returns into triple returns, so that we can make a
932 # paragraph for the last item in a list, if necessary:
933 $list =~ s/\n{2,}/\n\n\n/g;
934 my $result = _ProcessListItems
($list, $marker_any);
935 $result = "<$list_type>\n" . $result . "</$list_type>\n";
945 sub _ProcessListItems
{
947 # Process the contents of a single ordered or unordered list, splitting it
948 # into individual list items.
951 my $list_str = shift;
952 my $marker_any = shift;
955 # The $g_list_level global keeps track of when we're inside a list.
956 # Each time we enter a list, we increment it; when we leave a list,
957 # we decrement. If it's zero, we're not in a list anymore.
959 # We do this because when we're not inside a list, we want to treat
960 # something like this:
962 # I recommend upgrading to version
963 # 8. Oops, now this line is treated
966 # As a single paragraph, despite the fact that the second line starts
967 # with a digit-period-space sequence.
969 # Whereas when we're inside a list (or sub-list), that line will be
970 # treated as the start of a sub-list. What a kludge, huh? This is
971 # an aspect of Markdown's syntax that's hard to parse perfectly
972 # without resorting to mind-reading. Perhaps the solution is to
973 # change the syntax rules such that sub-lists must start with a
974 # starting cardinal number; e.g. "1." or "a.".
978 # trim trailing blank lines:
979 $list_str =~ s/\n{2,}\z/\n/;
983 (\n)?
# leading line = $1
984 (^[ \t]*) # leading whitespace = $2
985 ($marker_any) [ \t]+ # list marker = $3
986 ((?s
:.+?
) # list item text = $4
988 (?
= \n* (\z
| \
2 ($marker_any) [ \t]+))
991 my $leading_line = $1;
992 my $leading_space = $2;
994 if ($leading_line or ($item =~ m/\n{2,}/)) {
995 $item = _RunBlockGamut
(_Outdent
($item));
998 # Recursion for sub-lists:
999 $item = _DoLists
(_Outdent
($item));
1001 $item = _RunSpanGamut
($item);
1004 "<li>" . $item . "</li>\n";
1015 # Process Markdown `<pre><code>` blocks.
1022 ( # $1 = the code block -- one or more lines, starting with a space/tab
1024 (?
:[ ]{$opt{tab_width
}} | \t) # Lines must start with a tab or a tab-width of spaces
1028 ((?
=^[ ]{0,$opt{tab_width
}}\S
)|\Z
) # Lookahead for non-space at line-start, or end of doc
1031 my $result; # return value
1033 $codeblock = _EncodeCode
(_Outdent
($codeblock));
1034 $codeblock = _Detab
($codeblock);
1035 $codeblock =~ s/\A\n+//; # trim leading newlines
1036 $codeblock =~ s/\s+\z//; # trim trailing whitespace
1038 $result = "\n\n<pre><code>" . $codeblock . "\n</code></pre>\n\n";
1049 # * Backtick quotes are used for <code></code> spans.
1051 # * You can use multiple backticks as the delimiters if you want to
1052 # include literal backticks in the code span. So, this input:
1054 # Just type ``foo `bar` baz`` at the prompt.
1056 # Will translate to:
1058 # <p>Just type <code>foo `bar` baz</code> at the prompt.</p>
1060 # There's no arbitrary limit to the number of backticks you
1061 # can use as delimters. If you need three consecutive backticks
1062 # in your code, use four for delimiters, etc.
1064 # * You can use spaces to get literal backticks at the edges:
1066 # ... type `` `bar` `` ...
1070 # ... type <code>`bar`</code> ...
1076 (`+) # $1 = Opening run of `
1077 (.+?
) # $2 = The code block
1079 \1 # Matching closer
1083 $c =~ s/^[ \t]*//g; # leading whitespace
1084 $c =~ s/[ \t]*$//g; # trailing whitespace
1085 $c = _EncodeCode
($c);
1095 # Encode/escape certain characters inside Markdown code runs.
1096 # The point is that in code, these characters are literals,
1097 # and lose their special Markdown meanings.
1101 # Encode all ampersands; HTML entities are not
1102 # entities within a Markdown code span.
1105 # Encode $'s, but only if we're running under Blosxom.
1106 # (Blosxom interpolates Perl variables in article bodies.)
1109 if (defined($blosxom::version
)) {
1115 # Do the angle bracket song and dance:
1119 # Now, escape characters that are magic in Markdown:
1120 s! \* !$g_escape_table{'*'}!gx;
1121 s! _ !$g_escape_table{'_'}!gx;
1122 s! ~ !$g_escape_table{'~'}!gx;
1123 s! { !$g_escape_table{'{'}!gx;
1124 s! } !$g_escape_table{'}'}!gx;
1125 s! \[ !$g_escape_table{'['}!gx;
1126 s! \] !$g_escape_table{']'}!gx;
1127 s! \\ !$g_escape_table{'\\'}!gx;
1133 sub _DoItalicsAndBoldAndStrike
{
1136 # <strong> must go first:
1137 $text =~ s
{ \
*\
* (?
=\S
) (.+?
[*_
]*) (?
<=\S
) \
*\
* }
1138 {<strong
>$1</strong
>}gsx
;
1139 $text =~ s
{ (?
<!\w
) __
(?
=\S
) (.+?
[*_
]*) (?
<=\S
) __
(?
!\w
) }
1140 {<strong
>$1</strong
>}gsx
;
1142 $text =~ s
{ ~~ (?
=\S
) (.+?
[*_
]*) (?
<=\S
) ~~ }
1143 {<strike
>$1</strike
>}gsx
;
1145 $text =~ s
{ \
* (?
=\S
) (.+?
) (?
<=\S
) \
* }
1147 $text =~ s
{ (?
<!\w
) _
(?
=\S
) (.+?
) (?
<=\S
) _
(?
!\w
) }
1154 sub _DoBlockQuotes
{
1158 ( # Wrap whole match in $1
1160 ^[ \t]*>[ \t]?
# '>' at the start of a line
1161 .+\n # rest of the first line
1162 (.+\n)* # subsequent consecutive lines
1168 $bq =~ s/^[ \t]*>[ \t]?//gm; # trim one level of quoting
1169 $bq =~ s/^[ \t]+$//mg; # trim whitespace-only lines
1170 $bq = _RunBlockGamut
($bq); # recurse
1173 # These leading spaces screw with <pre> content, so we need to fix that:
1182 "<blockquote>\n$bq\n</blockquote>\n\n";
1190 sub _FormParagraphs
{
1193 # $text - string to process with html <p> tags
1197 # Strip leading and trailing lines:
1201 my @grafs = split(/\n{2,}/, $text);
1207 unless (defined( $g_html_blocks{$_} )) {
1208 $_ = _RunSpanGamut
($_);
1215 # Unhashify HTML blocks
1218 if (defined( $g_html_blocks{$_} )) {
1219 $_ = $g_html_blocks{$_};
1223 return join "\n\n", @grafs;
1227 sub _EncodeAmpsAndAngles
{
1228 # Smart processing for ampersands and angle brackets that need to be encoded.
1232 # Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
1233 # http://bumppo.net/projects/amputator/
1234 $text =~ s/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/&/g;
1237 $text =~ s{<(?![a-z/?\$!])}{<}gi;
1243 sub _EncodeBackslashEscapes
{
1245 # Parameter: String.
1246 # Returns: The string, with after processing the following backslash
1251 s! \\\\ !$g_escape_table{'\\'}!gx; # Must process escaped backslashes first.
1252 s! \\` !$g_escape_table{'`'}!gx;
1253 s! \\\* !$g_escape_table{'*'}!gx;
1254 s! \\_ !$g_escape_table{'_'}!gx;
1255 s! \\~ !$g_escape_table{'~'}!gx;
1256 s! \\\{ !$g_escape_table{'{'}!gx;
1257 s! \\\} !$g_escape_table{'}'}!gx;
1258 s! \\\[ !$g_escape_table{'['}!gx;
1259 s! \\\] !$g_escape_table{']'}!gx;
1260 s! \\\( !$g_escape_table{'('}!gx;
1261 s! \\\) !$g_escape_table{')'}!gx;
1262 s! \\> !$g_escape_table{'>'}!gx;
1263 s! \\\# !$g_escape_table{'#'}!gx;
1264 s! \\\+ !$g_escape_table{'+'}!gx;
1265 s! \\\- !$g_escape_table{'-'}!gx;
1266 s! \\\. !$g_escape_table{'.'}!gx;
1267 s{ \\! }{$g_escape_table{'!'}}gx
;
1276 $text =~ s{<((https?|ftp):[^'\042>\s]+)>}{<a href="$1">$1</a>}gi;
1278 # Email addresses: <address@domain.foo>
1285 [-a
-z0
-9]+(\
.[-a
-z0
-9]+)*\
.[a
-z
]+
1289 _EncodeEmailAddress
( _UnescapeSpecialChars
($1) );
1296 sub _EncodeEmailAddress
{
1298 # Input: an email address, e.g. "foo@example.com"
1300 # Output: the email address as a mailto link, with each character
1301 # of the address encoded as either a decimal or hex entity, in
1302 # the hopes of foiling most address harvesting spam bots. E.g.:
1304 # <a href="mailto:foo@e
1305 # xample.com">foo
1306 # @example.com</a>
1308 # Based on a filter by Matthew Wickline, posted to the BBEdit-Talk
1309 # mailing list: <http://tinyurl.com/yu7ue>
1316 sub { '&#' . ord(shift) . ';' },
1317 sub { '&#x' . sprintf( "%X", ord(shift) ) . ';' },
1321 $addr = "mailto:" . $addr;
1325 if ( $char eq '@' ) {
1326 # this *must* be encoded. I insist.
1327 $char = $encode[int rand 1]->($char);
1328 } elsif ( $char ne ':' ) {
1329 # leave ':' alone (to spot mailto: later)
1331 # roughly 10% raw, 45% hex, 45% dec
1333 $r > .9 ?
$encode[2]->($char) :
1334 $r < .45 ?
$encode[1]->($char) :
1341 $addr = qq{<a href
="$addr">$addr</a
>};
1342 $addr =~ s{">.+?:}{">}; # strip the mailto: from the visible part
1348 sub _UnescapeSpecialChars
{
1350 # Swap back in all the special characters we've hidden.
1354 while( my($char, $hash) = each(%g_escape_table) ) {
1355 $text =~ s/$hash/$char/g;
1363 # Parameter: String containing HTML markup.
1364 # Returns: Reference to an array of the tokens comprising the input
1365 # string. Each token is either a tag (possibly with nested,
1366 # tags contained therein, such as <a href="<MTFoo>">, or a
1367 # run of text between tags. Each element of the array is a
1368 # two-element array; the first is either 'tag' or 'text';
1369 # the second is the actual value.
1372 # Derived from the _tokenize() subroutine from Brad Choate's MTRegex plugin.
1373 # <http://www.bradchoate.com/past/mtregex.php>
1378 my $len = length $str;
1382 my $nested_tags = join('|', ('(?:<[a-z/!$](?:[^<>]') x
$depth) . (')*>)' x
$depth);
1383 my $match = qr
/(?s
: <! ( -- .*?
-- \s
* )+ > ) | # comment
1384 (?s
: <\? .*?
\?> ) | # processing instruction
1385 $nested_tags/ix
; # nested tags
1387 while ($str =~ m/($match)/g) {
1389 my $sec_start = pos $str;
1390 my $tag_start = $sec_start - length $whole_tag;
1391 if ($pos < $tag_start) {
1392 push @tokens, ['text', substr($str, $pos, $tag_start - $pos)];
1394 push @tokens, ['tag', $whole_tag];
1397 push @tokens, ['text', substr($str, $pos, $len - $pos)] if $pos < $len;
1404 # Remove one level of line-leading tabs or spaces
1408 $text =~ s/^(\t|[ ]{1,$opt{tab_width}})//gm;
1415 # Expand tabs to spaces using $opt{tab_width} if no second argument
1418 my $ts = shift || $opt{tab_width
};
1419 # From the Perl camel book "Fluent Perl" section (slightly modified)
1420 $text =~ s/(.*?)(\t+)/$1 . ' ' x (length($2) * $ts - length($1) % $ts)/ge;
1427 # Add URL prefix if needed
1431 return $url unless $opt{url_prefix
} ne '' || $opt{img_prefix
} ne '';
1432 return $url if $url =~ m
,^//, || $url =~ /^[A-Za-z][A-Za-z0-9+.-]*:/;
1433 my $ans = $opt{url_prefix
};
1434 $ans = $opt{img_prefix
}
1435 if $opt{img_prefix
} ne '' && $url =~ /\.(?:png|gif|jpe?g|svg?z)$/i;
1436 return $url unless $ans ne '';
1437 $ans .= '/' if substr($ans, -1, 1) ne '/';
1438 $ans .= substr($url, 0, 1) eq '/' ?
substr($url, 1) : $url;
1457 B<Markdown.pl> [ B<--help> ] [ B<--html4tags> ] [ B<--htmlroot>=I<prefix> ]
1458 [ B<--imageroot>=I<prefix> ] [ B<--version> ] [ B<--shortversion> ]
1464 Markdown is a text-to-HTML filter; it translates an easy-to-read /
1465 easy-to-write structured text format into HTML. Markdown's text format
1466 is most similar to that of plain text email, and supports features such
1467 as headers, *emphasis*, code blocks, blockquotes, and links.
1469 Markdown's syntax is designed not as a generic markup language, but
1470 specifically to serve as a front-end to (X)HTML. You can use span-level
1471 HTML tags anywhere in a Markdown document, and you can use block level
1472 HTML tags (like <div> and <table> as well).
1474 For more information about Markdown's syntax, see the `basics.text`
1475 and `syntax.text` files included with `Markdown.pl`.
1480 Use "--" to end switch parsing. For example, to open a file named "-z", use:
1487 =item B<--html4tags>
1489 Use HTML 4 style for empty element tags, e.g.:
1493 instead of Markdown's default XHTML style tags, e.g.:
1498 =item B<-r> I<prefix>, B<--htmlroot>=I<prefix>
1500 Any non-absolute URLs have I<prefix> prepended.
1503 =item B<-i> I<prefix>, B<--imageroot>=I<prefix>
1505 Any non-absolute URLs have I<prefix> prepended (overriding the B<-r> prefix
1506 if any) but only if they end in an image suffix.
1509 =item B<-V>, B<--version>
1511 Display Markdown's version number and copyright information.
1514 =item B<-s>, B<--shortversion>
1516 Display the short-form version number.
1519 =item B<-h>, B<--help>
1521 Display Markdown's help.
1527 =head1 VERSION HISTORY
1529 See the readme file for detailed release notes for this version.
1545 http://daringfireball.net
1546 http://daringfireball.net/projects/markdown/
1548 PHP port and other contributions by Michel Fortin
1551 Additional enhancements and tweaks by Kyle J. McKay
1552 mackyle<at>gmail.com
1555 =head1 COPYRIGHT AND LICENSE
1557 Copyright (C) 2003-2004 John Gruber
1558 Copyright (C) 2015,2016 Kyle J. McKay
1559 All rights reserved.
1561 Redistribution and use in source and binary forms, with or without
1562 modification, are permitted provided that the following conditions are
1565 * Redistributions of source code must retain the above copyright
1566 notice, this list of conditions and the following disclaimer.
1568 * Redistributions in binary form must reproduce the above copyright
1569 notice, this list of conditions and the following disclaimer in the
1570 documentation and/or other materials provided with the distribution.
1572 * Neither the name "Markdown" nor the names of its contributors may
1573 be used to endorse or promote products derived from this software
1574 without specific prior written permission.
1576 This software is provided by the copyright holders and contributors "as
1577 is" and any express or implied warranties, including, but not limited
1578 to, the implied warranties of merchantability and fitness for a
1579 particular purpose are disclaimed. In no event shall the copyright owner
1580 or contributors be liable for any direct, indirect, incidental, special,
1581 exemplary, or consequential damages (including, but not limited to,
1582 procurement of substitute goods or services; loss of use, data, or
1583 profits; or business interruption) however caused and on any theory of
1584 liability, whether in contract, strict liability, or tort (including
1585 negligence or otherwise) arising in any way out of the use of this
1586 software, even if advised of the possibility of such damage.