4 # Markdown -- A text-to-HTML conversion tool for web writers
6 # Copyright (c) 2004 John Gruber
7 # <http://daringfireball.net/projects/markdown/>
16 use Digest::MD5 qw(md5_hex);
17 use vars qw($VERSION);
21 ## Disabled; causes problems under Perl 5.6.1:
23 binmode( STDOUT, ":utf8" ); # c.f.: http://acis.openlib.org/dev/perl-unicode-struggle.html
27 # Global default settings:
29 my $g_empty_element_suffix = " />"; # Change to ">" for HTML output
37 # Regex to match balanced [brackets]. See Friedl's
38 # "Mastering Regular Expressions", 2nd Ed., pp. 328-331.
39 my $g_nested_brackets;
40 $g_nested_brackets = qr{
42 [^\[\]]+ # Anything other than brackets
45 (??{ $g_nested_brackets }) # Recursive set of nested brackets
51 # Table of hash values for escaped characters:
53 foreach my $char (split //, '\\`*_{}[]()>#+-.!') {
54 $g_escape_table{$char} = md5_hex($char);
58 # Global hashes, used by various utility routines
63 # Used to track when we're inside an ordered or unordered list
64 # (see _ProcessListItems() for details):
68 #### Blosxom plug-in interface ##########################################
70 # Set $g_blosxom_use_meta to 1 to use Blosxom's meta plug-in to determine
71 # which posts Markdown should process, using a "meta-markup: markdown"
72 # header. If it's set to 0 (the default), Markdown will process all
74 my $g_blosxom_use_meta = 0;
78 my($pkg, $path, $filename, $story_ref, $title_ref, $body_ref) = @_;
80 if ( (! $g_blosxom_use_meta) or
81 (defined($meta::markup) and ($meta::markup =~ /^\s*markdown\s*$/i))
83 $$body_ref = Markdown($$body_ref);
89 #### Movable Type plug-in interface #####################################
90 eval {require MT}; # Test to see if we're running in MT.
94 require MT::Template::Context;
95 import MT::Template::Context;
97 eval {require MT::Plugin}; # Test to see if we're running >= MT 3.0.
101 my $plugin = new MT::Plugin({
103 description => "A plain-text-to-HTML formatting plugin. (Version: $VERSION)",
104 doc_link => 'http://daringfireball.net/projects/markdown/'
106 MT->add_plugin( $plugin );
109 MT::Template::Context->add_container_tag(MarkdownOptions => sub {
112 my $builder = $ctx->stash('builder');
113 my $tokens = $ctx->stash('tokens');
115 if (defined ($args->{'output'}) ) {
116 $ctx->stash('markdown_output', lc $args->{'output'});
119 defined (my $str = $builder->build($ctx, $tokens) )
120 or return $ctx->error($builder->errstr);
124 MT->add_text_filter('markdown' => {
126 docs => 'http://daringfireball.net/projects/markdown/',
132 my $output = $ctx->stash('markdown_output');
133 if (defined $output && $output =~ m/^html/i) {
134 $g_empty_element_suffix = ">";
135 $ctx->stash('markdown_output', '');
137 elsif (defined $output && $output eq 'raw') {
139 $ctx->stash('markdown_output', '');
143 $g_empty_element_suffix = " />";
146 $text = $raw ? $text : Markdown($text);
151 # If SmartyPants is loaded, add a combo Markdown/SmartyPants text filter:
156 $smartypants = $MT::Template::Context::Global_filters{'smarty_pants'};
160 MT->add_text_filter('markdown_with_smartypants' => {
161 label => 'Markdown With SmartyPants',
162 docs => 'http://daringfireball.net/projects/markdown/',
167 my $output = $ctx->stash('markdown_output');
168 if (defined $output && $output eq 'html') {
169 $g_empty_element_suffix = ">";
172 $g_empty_element_suffix = " />";
175 $text = Markdown($text);
176 $text = $smartypants->($text, '1');
182 #### BBEdit/command-line text filter interface ##########################
183 # Needs to be hidden from MT (and Blosxom when running in static mode).
185 # We're only using $blosxom::version once; tell Perl not to warn us:
187 unless ( defined($blosxom::version) ) {
190 #### Check for command-line switches: #################
193 Getopt::Long::Configure('pass_through');
194 GetOptions(\%cli_opts,
199 if ($cli_opts{'version'}) { # Version info
200 print "\nThis is Markdown, version $VERSION.\n";
201 print "Copyright 2004 John Gruber\n";
202 print "http://daringfireball.net/projects/markdown/\n\n";
205 if ($cli_opts{'shortversion'}) { # Just the version number string.
209 if ($cli_opts{'html4tags'}) { # Use HTML tag style instead of XHTML
210 $g_empty_element_suffix = ">";
214 #### Process incoming text: ###########################
217 local $/; # Slurp the whole file
227 .markdown-body>*:first-child {
228 margin-top: 0 !important;
230 .markdown-body>*:last-child {
231 margin-bottom: 0 !important;
233 .markdown-body a.absent {
236 .markdown-body a.anchor {
246 .markdown-body h1, .markdown-body h2, .markdown-body h3, .markdown-body h4, .markdown-body h5, .markdown-body h6 {
250 -webkit-font-smoothing: antialiased;
254 .markdown-body h1 .mini-icon-link, .markdown-body h2 .mini-icon-link, .markdown-body h3 .mini-icon-link, .markdown-body h4 .mini-icon-link, .markdown-body h5 .mini-icon-link, .markdown-body h6 .mini-icon-link {
258 .markdown-body h1:hover a.anchor, .markdown-body h2:hover a.anchor, .markdown-body h3:hover a.anchor, .markdown-body h4:hover a.anchor, .markdown-body h5:hover a.anchor, .markdown-body h6:hover a.anchor {
259 text-decoration: none;
264 .markdown-body h1:hover a.anchor .mini-icon-link, .markdown-body h2:hover a.anchor .mini-icon-link, .markdown-body h3:hover a.anchor .mini-icon-link, .markdown-body h4:hover a.anchor .mini-icon-link, .markdown-body h5:hover a.anchor .mini-icon-link, .markdown-body h6:hover a.anchor .mini-icon-link {
265 display: inline-block;
267 .markdown-body h1 tt, .markdown-body h1 code, .markdown-body h2 tt, .markdown-body h2 code, .markdown-body h3 tt, .markdown-body h3 code, .markdown-body h4 tt, .markdown-body h4 code, .markdown-body h5 tt, .markdown-body h5 code, .markdown-body h6 tt, .markdown-body h6 code {
276 border-bottom: 1px solid #ccc;
292 .markdown-body p, .markdown-body blockquote, .markdown-body ul, .markdown-body ol, .markdown-body dl, .markdown-body table, .markdown-body pre {
296 background: transparent url("/dirty-shade.png") repeat-x 0 0;
302 .markdown-body>h2:first-child, .markdown-body>h1:first-child, .markdown-body>h1:first-child+h2, .markdown-body>h3:first-child, .markdown-body>h4:first-child, .markdown-body>h5:first-child, .markdown-body>h6:first-child {
306 .markdown-body a:first-child h1, .markdown-body a:first-child h2, .markdown-body a:first-child h3, .markdown-body a:first-child h4, .markdown-body a:first-child h5, .markdown-body a:first-child h6 {
310 .markdown-body h1+p, .markdown-body h2+p, .markdown-body h3+p, .markdown-body h4+p, .markdown-body h5+p, .markdown-body h6+p {
313 .markdown-body li p.first {
314 display: inline-block;
316 .markdown-body ul, .markdown-body ol {
319 .markdown-body ul.no-list, .markdown-body ol.no-list {
320 list-style-type: none;
323 .markdown-body ul li>:first-child, .markdown-body ul li ul:first-of-type, .markdown-body ul li ol:first-of-type, .markdown-body ol li>:first-child, .markdown-body ol li ul:first-of-type, .markdown-body ol li ol:first-of-type {
326 .markdown-body ul li p:last-of-type, .markdown-body ol li p:last-of-type {
329 .markdown-body ul ul, .markdown-body ul ol, .markdown-body ol ol, .markdown-body ol ul {
335 .markdown-body dl dt {
342 .markdown-body dl dt:first-child {
345 .markdown-body dl dt>:first-child {
348 .markdown-body dl dt>:last-child {
351 .markdown-body dl dd {
355 .markdown-body dl dd>:first-child {
358 .markdown-body dl dd>:last-child {
361 .markdown-body blockquote {
362 border-left: 4px solid #DDD;
366 .markdown-body blockquote>:first-child {
369 .markdown-body blockquote>:last-child {
372 .markdown-body table th {
375 .markdown-body table th, .markdown-body table td {
376 border: 1px solid #ccc;
379 .markdown-body table tr {
380 border-top: 1px solid #ccc;
381 background-color: #fff;
383 .markdown-body table tr:nth-child(2n) {
384 background-color: #f8f8f8;
388 -moz-box-sizing: border-box;
389 box-sizing: border-box;
391 .markdown-body span.frame {
395 .markdown-body span.frame>span {
396 border: 1px solid #ddd;
404 .markdown-body span.frame span img {
408 .markdown-body span.frame span span {
414 .markdown-body span.align-center {
419 .markdown-body span.align-center>span {
425 .markdown-body span.align-center span img {
429 .markdown-body span.align-right {
434 .markdown-body span.align-right>span {
440 .markdown-body span.align-right span img {
444 .markdown-body span.float-left {
450 .markdown-body span.float-left span {
453 .markdown-body span.float-right {
459 .markdown-body span.float-right>span {
465 .markdown-body code, .markdown-body tt {
468 border: 1px solid #eaeaea;
469 background-color: #f8f8f8;
472 .markdown-body code {
475 .markdown-body pre>code {
480 background: transparent;
482 .markdown-body .highlight pre, .markdown-body pre {
483 background-color: #f8f8f8;
484 border: 1px solid #ccc;
491 .markdown-body pre code, .markdown-body pre tt {
494 background-color: transparent;
499 print "<div class='markdown-body'>";
500 print Markdown($text);
509 # Main function. The order in which other subs are called here is
510 # essential. Link and image substitutions need to happen before
511 # _EscapeSpecialChars(), so that any *'s or _'s in the <a>
512 # and <img> tags get encoded.
516 # Clear the global hashes. If we don't clear these, you get conflicts
517 # from other articles when generating a page which contains more than
518 # one article (e.g. an index page that shows the N most recent
525 # Standardize line endings:
526 $text =~ s{\r\n}{\n}g; # DOS to Unix
527 $text =~ s{\r}{\n}g; # Mac to Unix
529 # Make sure $text ends with a couple of newlines:
532 # Convert all tabs to spaces.
533 $text = _Detab($text);
535 # Strip any lines consisting only of spaces and tabs.
536 # This makes subsequent regexen easier to write, because we can
537 # match consecutive blank lines with /\n+/ instead of something
538 # contorted like /[ \t]*\n+/ .
539 $text =~ s/^[ \t]+$//mg;
541 # Turn block-level HTML blocks into hash entries
542 $text = _HashHTMLBlocks($text);
544 # Strip link definitions, store in hashes.
545 $text = _StripLinkDefinitions($text);
547 $text = _RunBlockGamut($text);
549 $text = _UnescapeSpecialChars($text);
555 sub _StripLinkDefinitions {
557 # Strips link definitions from text, stores the URLs and titles in
561 my $less_than_tab = $g_tab_width - 1;
563 # Link defs are in the form: ^[id]: url "optional title"
565 ^[ ]{0,$less_than_tab}\[(.+)\]: # id = $1
567 \n? # maybe *one* newline
569 <?(\S+?)>? # url = $2
571 \n? # maybe one newline
574 (?<=\s) # lookbehind for whitespace
579 )? # title is optional
583 $g_urls{lc $1} = _EncodeAmpsAndAngles( $2 ); # Link IDs are case-insensitive
585 $g_titles{lc $1} = $3;
586 $g_titles{lc $1} =~ s/"/"/g;
594 sub _HashHTMLBlocks {
596 my $less_than_tab = $g_tab_width - 1;
598 # Hashify HTML blocks:
599 # We only want to do this for block-level HTML tags, such as headers,
600 # lists, and tables. That's because we still want to wrap <p>s around
601 # "paragraphs" that are wrapped in non-block-level tags, such as anchors,
602 # phrase emphasis, and spans. The list of tags we're looking for is
604 my $block_tags_a = qr/p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del/;
605 my $block_tags_b = qr/p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math/;
607 # First, look for nested blocks, e.g.:
610 # tags for inner block must be indented.
614 # The outermost tags must start at the left margin for this to match, and
615 # the inner nested divs must be indented.
616 # We need to do this before the next, more liberal match, because the next
617 # match will start at the first `<div>` and stop at the first `</div>`.
620 ^ # start of line (with /m)
621 <($block_tags_a) # start tag = $2
623 (.*\n)*? # any number of lines, minimally matching
624 </\2> # the matching end tag
625 [ \t]* # trailing spaces/tabs
626 (?=\n+|\Z) # followed by a newline or end of document
629 my $key = md5_hex($1);
630 $g_html_blocks{$key} = $1;
631 "\n\n" . $key . "\n\n";
636 # Now match more liberally, simply from `\n<tag>` to `</tag>\n`
640 ^ # start of line (with /m)
641 <($block_tags_b) # start tag = $2
643 (.*\n)*? # any number of lines, minimally matching
644 .*</\2> # the matching end tag
645 [ \t]* # trailing spaces/tabs
646 (?=\n+|\Z) # followed by a newline or end of document
649 my $key = md5_hex($1);
650 $g_html_blocks{$key} = $1;
651 "\n\n" . $key . "\n\n";
653 # Special case just for <hr />. It was easier to make a special case than
654 # to make the other regex more complicated.
657 (?<=\n\n) # Starting after a blank line
659 \A\n? # the beginning of the doc
662 [ ]{0,$less_than_tab}
663 <(hr) # start tag = $2
666 /?> # the matching end tag
668 (?=\n{2,}|\Z) # followed by a blank line or end of document
671 my $key = md5_hex($1);
672 $g_html_blocks{$key} = $1;
673 "\n\n" . $key . "\n\n";
676 # Special case for standalone HTML comments:
679 (?<=\n\n) # Starting after a blank line
681 \A\n? # the beginning of the doc
684 [ ]{0,$less_than_tab}
691 (?=\n{2,}|\Z) # followed by a blank line or end of document
694 my $key = md5_hex($1);
695 $g_html_blocks{$key} = $1;
696 "\n\n" . $key . "\n\n";
706 # These are all the transformations that form block-level
707 # tags like paragraphs, headers, and list items.
711 $text = _DoHeaders($text);
713 # Do Horizontal Rules:
714 $text =~ s{^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$}{\n<hr$g_empty_element_suffix\n}gmx;
715 $text =~ s{^[ ]{0,2}([ ]? -[ ]?){3,}[ \t]*$}{\n<hr$g_empty_element_suffix\n}gmx;
716 $text =~ s{^[ ]{0,2}([ ]? _[ ]?){3,}[ \t]*$}{\n<hr$g_empty_element_suffix\n}gmx;
718 $text = _DoLists($text);
720 $text = _DoCodeBlocks($text);
722 $text = _DoBlockQuotes($text);
724 # We already ran _HashHTMLBlocks() before, in Markdown(), but that
725 # was to escape raw HTML in the original Markdown source. This time,
726 # we're escaping the markup we've just created, so that we don't wrap
727 # <p> tags around block-level tags.
728 $text = _HashHTMLBlocks($text);
730 $text = _FormParagraphs($text);
738 # These are all the transformations that occur *within* block-level
739 # tags like paragraphs, headers, and list items.
743 $text = _DoCodeSpans($text);
745 $text = _EscapeSpecialChars($text);
747 # Process anchor and image tags. Images must come first,
748 # because ![foo][f] looks like an anchor.
749 $text = _DoImages($text);
750 $text = _DoAnchors($text);
752 # Make links out of things like `<http://example.com/>`
753 # Must come after _DoAnchors(), because you can use < and >
754 # delimiters in inline links like [this](<url>).
755 $text = _DoAutoLinks($text);
757 $text = _EncodeAmpsAndAngles($text);
759 $text = _DoItalicsAndBold($text);
762 $text =~ s/ {2,}\n/ <br$g_empty_element_suffix\n/g;
768 sub _EscapeSpecialChars {
770 my $tokens ||= _TokenizeHTML($text);
772 $text = ''; # rebuild $text from the tokens
773 # my $in_pre = 0; # Keep track of when we're inside <pre> or <code> tags.
774 # my $tags_to_skip = qr!<(/?)(?:pre|code|kbd|script|math)[\s>]!;
776 foreach my $cur_token (@$tokens) {
777 if ($cur_token->[0] eq "tag") {
778 # Within tags, encode * and _ so they don't conflict
779 # with their use in Markdown for italics and strong.
780 # We're replacing each such character with its
781 # corresponding MD5 checksum value; this is likely
782 # overkill, but it should prevent us from colliding
783 # with the escape values by accident.
784 $cur_token->[1] =~ s! \* !$g_escape_table{'*'}!gx;
785 $cur_token->[1] =~ s! _ !$g_escape_table{'_'}!gx;
786 $text .= $cur_token->[1];
788 my $t = $cur_token->[1];
789 $t = _EncodeBackslashEscapes($t);
799 # Turn Markdown link shortcuts into XHTML <a> tags.
804 # First, handle reference-style links: [link text] [id]
807 ( # wrap whole match in $1
809 ($g_nested_brackets) # link text = $2
812 [ ]? # one optional space
813 (?:\n[ ]*)? # one optional newline followed by spaces
821 my $whole_match = $1;
825 if ($link_id eq "") {
826 $link_id = lc $link_text; # for shortcut links like [this][].
829 if (defined $g_urls{$link_id}) {
830 my $url = $g_urls{$link_id};
831 $url =~ s! \* !$g_escape_table{'*'}!gx; # We've got to encode these to avoid
832 $url =~ s! _ !$g_escape_table{'_'}!gx; # conflicting with italics/bold.
833 $result = "<a href=\"$url\"";
834 if ( defined $g_titles{$link_id} ) {
835 my $title = $g_titles{$link_id};
836 $title =~ s! \* !$g_escape_table{'*'}!gx;
837 $title =~ s! _ !$g_escape_table{'_'}!gx;
838 $result .= " title=\"$title\"";
840 $result .= ">$link_text</a>";
843 $result = $whole_match;
849 # Next, inline-style links: [link text](url "optional title")
852 ( # wrap whole match in $1
854 ($g_nested_brackets) # link text = $2
858 <?(.*?)>? # href = $3
861 (['"]) # quote char = $5
864 )? # title is optional
869 my $whole_match = $1;
874 $url =~ s! \* !$g_escape_table{'*'}!gx; # We've got to encode these to avoid
875 $url =~ s! _ !$g_escape_table{'_'}!gx; # conflicting with italics/bold.
876 $result = "<a href=\"$url\"";
878 if (defined $title) {
879 $title =~ s/"/"/g;
880 $title =~ s! \* !$g_escape_table{'*'}!gx;
881 $title =~ s! _ !$g_escape_table{'_'}!gx;
882 $result .= " title=\"$title\"";
885 $result .= ">$link_text</a>";
896 # Turn Markdown image shortcuts into <img> tags.
901 # First, handle reference-style labeled images: ![alt text][id]
904 ( # wrap whole match in $1
906 (.*?) # alt text = $2
909 [ ]? # one optional space
910 (?:\n[ ]*)? # one optional newline followed by spaces
919 my $whole_match = $1;
923 if ($link_id eq "") {
924 $link_id = lc $alt_text; # for shortcut links like ![this][].
927 $alt_text =~ s/"/"/g;
928 if (defined $g_urls{$link_id}) {
929 my $url = $g_urls{$link_id};
930 $url =~ s! \* !$g_escape_table{'*'}!gx; # We've got to encode these to avoid
931 $url =~ s! _ !$g_escape_table{'_'}!gx; # conflicting with italics/bold.
932 $result = "<img src=\"$url\" alt=\"$alt_text\"";
933 if (defined $g_titles{$link_id}) {
934 my $title = $g_titles{$link_id};
935 $title =~ s! \* !$g_escape_table{'*'}!gx;
936 $title =~ s! _ !$g_escape_table{'_'}!gx;
937 $result .= " title=\"$title\"";
939 $result .= $g_empty_element_suffix;
942 # If there's no such link ID, leave intact:
943 $result = $whole_match;
950 # Next, handle inline images: 
951 # Don't forget: encode * and _
954 ( # wrap whole match in $1
956 (.*?) # alt text = $2
960 <?(\S+?)>? # src url = $3
963 (['"]) # quote char = $5
967 )? # title is optional
972 my $whole_match = $1;
980 $alt_text =~ s/"/"/g;
981 $title =~ s/"/"/g;
982 $url =~ s! \* !$g_escape_table{'*'}!gx; # We've got to encode these to avoid
983 $url =~ s! _ !$g_escape_table{'_'}!gx; # conflicting with italics/bold.
984 $result = "<img src=\"$url\" alt=\"$alt_text\"";
985 if (defined $title) {
986 $title =~ s! \* !$g_escape_table{'*'}!gx;
987 $title =~ s! _ !$g_escape_table{'_'}!gx;
988 $result .= " title=\"$title\"";
990 $result .= $g_empty_element_suffix;
1002 # Setext-style headers:
1009 $text =~ s{ ^(.+)[ \t]*\n=+[ \t]*\n+ }{
1010 "<h1>" . _RunSpanGamut($1) . "</h1>\n\n";
1013 $text =~ s{ ^(.+)[ \t]*\n-+[ \t]*\n+ }{
1014 "<h2>" . _RunSpanGamut($1) . "</h2>\n\n";
1018 # atx-style headers:
1021 # ## Header 2 with closing hashes ##
1026 ^(\#{1,6}) # $1 = string of #'s
1028 (.+?) # $2 = Header text
1030 \#* # optional closing #'s (not counted)
1033 my $h_level = length($1);
1034 "<h$h_level>" . _RunSpanGamut($2) . "</h$h_level>\n\n";
1043 # Form HTML ordered (numbered) and unordered (bulleted) lists.
1046 my $less_than_tab = $g_tab_width - 1;
1048 # Re-usable patterns to match list item bullets and number markers:
1049 my $marker_ul = qr/[*+-]/;
1050 my $marker_ol = qr/\d+[.]/;
1051 my $marker_any = qr/(?:$marker_ul|$marker_ol)/;
1053 # Re-usable pattern to match any entirel ul or ol list:
1054 my $whole_list = qr{
1057 [ ]{0,$less_than_tab}
1058 (${marker_any}) # $3 = first list item marker
1067 (?! # Negative lookahead for another list item marker
1075 # We use a different prefix before nested lists than top-level lists.
1076 # See extended comment in _ProcessListItems().
1078 # Note: There's a bit of duplication here. My original implementation
1079 # created a scalar regex pattern as the conditional result of the test on
1080 # $g_list_level, and then only ran the $text =~ s{...}{...}egmx
1081 # substitution once, using the scalar as the pattern. This worked,
1082 # everywhere except when running under MT on my hosting account at Pair
1083 # Networks. There, this caused all rebuilds to be killed by the reaper (or
1084 # perhaps they crashed, but that seems incredibly unlikely given that the
1085 # same script on the same server ran fine *except* under MT. I've spent
1086 # more time trying to figure out why this is happening than I'd like to
1087 # admit. My only guess, backed up by the fact that this workaround works,
1088 # is that Perl optimizes the substition when it can figure out that the
1089 # pattern will never change, and when this optimization isn't on, we run
1090 # afoul of the reaper. Thus, the slightly redundant code to that uses two
1091 # static s/// patterns rather than one conditional pattern.
1093 if ($g_list_level) {
1099 my $list_type = ($3 =~ m/$marker_ul/) ? "ul" : "ol";
1100 # Turn double returns into triple returns, so that we can make a
1101 # paragraph for the last item in a list, if necessary:
1102 $list =~ s/\n{2,}/\n\n\n/g;
1103 my $result = _ProcessListItems($list, $marker_any);
1104 $result = "<$list_type>\n" . $result . "</$list_type>\n";
1114 my $list_type = ($3 =~ m/$marker_ul/) ? "ul" : "ol";
1115 # Turn double returns into triple returns, so that we can make a
1116 # paragraph for the last item in a list, if necessary:
1117 $list =~ s/\n{2,}/\n\n\n/g;
1118 my $result = _ProcessListItems($list, $marker_any);
1119 $result = "<$list_type>\n" . $result . "</$list_type>\n";
1129 sub _ProcessListItems {
1131 # Process the contents of a single ordered or unordered list, splitting it
1132 # into individual list items.
1135 my $list_str = shift;
1136 my $marker_any = shift;
1139 # The $g_list_level global keeps track of when we're inside a list.
1140 # Each time we enter a list, we increment it; when we leave a list,
1141 # we decrement. If it's zero, we're not in a list anymore.
1143 # We do this because when we're not inside a list, we want to treat
1144 # something like this:
1146 # I recommend upgrading to version
1147 # 8. Oops, now this line is treated
1150 # As a single paragraph, despite the fact that the second line starts
1151 # with a digit-period-space sequence.
1153 # Whereas when we're inside a list (or sub-list), that line will be
1154 # treated as the start of a sub-list. What a kludge, huh? This is
1155 # an aspect of Markdown's syntax that's hard to parse perfectly
1156 # without resorting to mind-reading. Perhaps the solution is to
1157 # change the syntax rules such that sub-lists must start with a
1158 # starting cardinal number; e.g. "1." or "a.".
1162 # trim trailing blank lines:
1163 $list_str =~ s/\n{2,}\z/\n/;
1167 (\n)? # leading line = $1
1168 (^[ \t]*) # leading whitespace = $2
1169 ($marker_any) [ \t]+ # list marker = $3
1170 ((?s:.+?) # list item text = $4
1172 (?= \n* (\z | \2 ($marker_any) [ \t]+))
1175 my $leading_line = $1;
1176 my $leading_space = $2;
1178 if ($leading_line or ($item =~ m/\n{2,}/)) {
1179 $item = _RunBlockGamut(_Outdent($item));
1182 # Recursion for sub-lists:
1183 $item = _DoLists(_Outdent($item));
1185 $item = _RunSpanGamut($item);
1188 "<li>" . $item . "</li>\n";
1199 # Process Markdown `<pre><code>` blocks.
1206 ( # $1 = the code block -- one or more lines, starting with a space/tab
1208 (?:[ ]{$g_tab_width} | \t) # Lines must start with a tab or a tab-width of spaces
1212 ((?=^[ ]{0,$g_tab_width}\S)|\Z) # Lookahead for non-space at line-start, or end of doc
1215 my $result; # return value
1217 $codeblock = _EncodeCode(_Outdent($codeblock));
1218 $codeblock = _Detab($codeblock);
1219 $codeblock =~ s/\A\n+//; # trim leading newlines
1220 $codeblock =~ s/\s+\z//; # trim trailing whitespace
1222 $result = "\n\n<pre><code>" . $codeblock . "\n</code></pre>\n\n";
1233 # * Backtick quotes are used for <code></code> spans.
1235 # * You can use multiple backticks as the delimiters if you want to
1236 # include literal backticks in the code span. So, this input:
1238 # Just type ``foo `bar` baz`` at the prompt.
1240 # Will translate to:
1242 # <p>Just type <code>foo `bar` baz</code> at the prompt.</p>
1244 # There's no arbitrary limit to the number of backticks you
1245 # can use as delimters. If you need three consecutive backticks
1246 # in your code, use four for delimiters, etc.
1248 # * You can use spaces to get literal backticks at the edges:
1250 # ... type `` `bar` `` ...
1254 # ... type <code>`bar`</code> ...
1260 (`+) # $1 = Opening run of `
1261 (.+?) # $2 = The code block
1263 \1 # Matching closer
1267 $c =~ s/^[ \t]*//g; # leading whitespace
1268 $c =~ s/[ \t]*$//g; # trailing whitespace
1269 $c = _EncodeCode($c);
1279 # Encode/escape certain characters inside Markdown code runs.
1280 # The point is that in code, these characters are literals,
1281 # and lose their special Markdown meanings.
1285 # Encode all ampersands; HTML entities are not
1286 # entities within a Markdown code span.
1289 # Encode $'s, but only if we're running under Blosxom.
1290 # (Blosxom interpolates Perl variables in article bodies.)
1293 if (defined($blosxom::version)) {
1299 # Do the angle bracket song and dance:
1303 # Now, escape characters that are magic in Markdown:
1304 s! \* !$g_escape_table{'*'}!gx;
1305 s! _ !$g_escape_table{'_'}!gx;
1306 s! { !$g_escape_table{'{'}!gx;
1307 s! } !$g_escape_table{'}'}!gx;
1308 s! \[ !$g_escape_table{'['}!gx;
1309 s! \] !$g_escape_table{']'}!gx;
1310 s! \\ !$g_escape_table{'\\'}!gx;
1316 sub _DoItalicsAndBold {
1319 # <strong> must go first:
1320 $text =~ s{ (\*\*|__) (?=\S) (.+?[*_]*) (?<=\S) \1 }
1321 {<strong>$2</strong>}gsx;
1323 $text =~ s{ (\*|_) (?=\S) (.+?) (?<=\S) \1 }
1330 sub _DoBlockQuotes {
1334 ( # Wrap whole match in $1
1336 ^[ \t]*>[ \t]? # '>' at the start of a line
1337 .+\n # rest of the first line
1338 (.+\n)* # subsequent consecutive lines
1344 $bq =~ s/^[ \t]*>[ \t]?//gm; # trim one level of quoting
1345 $bq =~ s/^[ \t]+$//mg; # trim whitespace-only lines
1346 $bq = _RunBlockGamut($bq); # recurse
1349 # These leading spaces screw with <pre> content, so we need to fix that:
1358 "<blockquote>\n$bq\n</blockquote>\n\n";
1366 sub _FormParagraphs {
1369 # $text - string to process with html <p> tags
1373 # Strip leading and trailing lines:
1377 my @grafs = split(/\n{2,}/, $text);
1383 unless (defined( $g_html_blocks{$_} )) {
1384 $_ = _RunSpanGamut($_);
1391 # Unhashify HTML blocks
1394 if (defined( $g_html_blocks{$_} )) {
1395 $_ = $g_html_blocks{$_};
1399 return join "\n\n", @grafs;
1403 sub _EncodeAmpsAndAngles {
1404 # Smart processing for ampersands and angle brackets that need to be encoded.
1408 # Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
1409 # http://bumppo.net/projects/amputator/
1410 $text =~ s/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/&/g;
1413 $text =~ s{<(?![a-z/?\$!])}{<}gi;
1419 sub _EncodeBackslashEscapes {
1421 # Parameter: String.
1422 # Returns: The string, with after processing the following backslash
1427 s! \\\\ !$g_escape_table{'\\'}!gx; # Must process escaped backslashes first.
1428 s! \\` !$g_escape_table{'`'}!gx;
1429 s! \\\* !$g_escape_table{'*'}!gx;
1430 s! \\_ !$g_escape_table{'_'}!gx;
1431 s! \\\{ !$g_escape_table{'{'}!gx;
1432 s! \\\} !$g_escape_table{'}'}!gx;
1433 s! \\\[ !$g_escape_table{'['}!gx;
1434 s! \\\] !$g_escape_table{']'}!gx;
1435 s! \\\( !$g_escape_table{'('}!gx;
1436 s! \\\) !$g_escape_table{')'}!gx;
1437 s! \\> !$g_escape_table{'>'}!gx;
1438 s! \\\# !$g_escape_table{'#'}!gx;
1439 s! \\\+ !$g_escape_table{'+'}!gx;
1440 s! \\\- !$g_escape_table{'-'}!gx;
1441 s! \\\. !$g_escape_table{'.'}!gx;
1442 s{ \\! }{$g_escape_table{'!'}}gx;
1451 $text =~ s{<((https?|ftp):[^'">\s]+)>}{<a href="$1">$1</a>}gi;
1453 # Email addresses: <address@domain.foo>
1460 [-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+
1464 _EncodeEmailAddress( _UnescapeSpecialChars($1) );
1471 sub _EncodeEmailAddress {
1473 # Input: an email address, e.g. "foo@example.com"
1475 # Output: the email address as a mailto link, with each character
1476 # of the address encoded as either a decimal or hex entity, in
1477 # the hopes of foiling most address harvesting spam bots. E.g.:
1479 # <a href="mailto:foo@e
1480 # xample.com">foo
1481 # @example.com</a>
1483 # Based on a filter by Matthew Wickline, posted to the BBEdit-Talk
1484 # mailing list: <http://tinyurl.com/yu7ue>
1491 sub { '&#' . ord(shift) . ';' },
1492 sub { '&#x' . sprintf( "%X", ord(shift) ) . ';' },
1496 $addr = "mailto:" . $addr;
1500 if ( $char eq '@' ) {
1501 # this *must* be encoded. I insist.
1502 $char = $encode[int rand 1]->($char);
1503 } elsif ( $char ne ':' ) {
1504 # leave ':' alone (to spot mailto: later)
1506 # roughly 10% raw, 45% hex, 45% dec
1508 $r > .9 ? $encode[2]->($char) :
1509 $r < .45 ? $encode[1]->($char) :
1516 $addr = qq{<a href="$addr">$addr</a>};
1517 $addr =~ s{">.+?:}{">}; # strip the mailto: from the visible part
1523 sub _UnescapeSpecialChars {
1525 # Swap back in all the special characters we've hidden.
1529 while( my($char, $hash) = each(%g_escape_table) ) {
1530 $text =~ s/$hash/$char/g;
1538 # Parameter: String containing HTML markup.
1539 # Returns: Reference to an array of the tokens comprising the input
1540 # string. Each token is either a tag (possibly with nested,
1541 # tags contained therein, such as <a href="<MTFoo>">, or a
1542 # run of text between tags. Each element of the array is a
1543 # two-element array; the first is either 'tag' or 'text';
1544 # the second is the actual value.
1547 # Derived from the _tokenize() subroutine from Brad Choate's MTRegex plugin.
1548 # <http://www.bradchoate.com/past/mtregex.php>
1553 my $len = length $str;
1557 my $nested_tags = join('|', ('(?:<[a-z/!$](?:[^<>]') x $depth) . (')*>)' x $depth);
1558 my $match = qr/(?s: <! ( -- .*? -- \s* )+ > ) | # comment
1559 (?s: <\? .*? \?> ) | # processing instruction
1560 $nested_tags/ix; # nested tags
1562 while ($str =~ m/($match)/g) {
1564 my $sec_start = pos $str;
1565 my $tag_start = $sec_start - length $whole_tag;
1566 if ($pos < $tag_start) {
1567 push @tokens, ['text', substr($str, $pos, $tag_start - $pos)];
1569 push @tokens, ['tag', $whole_tag];
1572 push @tokens, ['text', substr($str, $pos, $len - $pos)] if $pos < $len;
1579 # Remove one level of line-leading tabs or spaces
1583 $text =~ s/^(\t|[ ]{1,$g_tab_width})//gm;
1590 # Cribbed from a post by Bart Lateur:
1591 # <http://www.nntp.perl.org/group/perl.macperl.anyperl/154>
1595 $text =~ s{(.*?)\t}{$1.(' ' x ($g_tab_width - length($1) % $g_tab_width))}ge;
1614 B<Markdown.pl> [ B<--html4tags> ] [ B<--version> ] [ B<-shortversion> ]
1620 Markdown is a text-to-HTML filter; it translates an easy-to-read /
1621 easy-to-write structured text format into HTML. Markdown's text format
1622 is most similar to that of plain text email, and supports features such
1623 as headers, *emphasis*, code blocks, blockquotes, and links.
1625 Markdown's syntax is designed not as a generic markup language, but
1626 specifically to serve as a front-end to (X)HTML. You can use span-level
1627 HTML tags anywhere in a Markdown document, and you can use block level
1628 HTML tags (like <div> and <table> as well).
1630 For more information about Markdown's syntax, see:
1632 http://daringfireball.net/projects/markdown/
1637 Use "--" to end switch parsing. For example, to open a file named "-z", use:
1644 =item B<--html4tags>
1646 Use HTML 4 style for empty element tags, e.g.:
1650 instead of Markdown's default XHTML style tags, e.g.:
1655 =item B<-v>, B<--version>
1657 Display Markdown's version number and copyright information.
1660 =item B<-s>, B<--shortversion>
1662 Display the short-form version number.
1671 To file bug reports or feature requests (other than topics listed in the
1672 Caveats section above) please send email to:
1674 support@daringfireball.net
1676 Please include with your report: (1) the example input; (2) the output
1677 you expected; (3) the output Markdown actually produced.
1680 =head1 VERSION HISTORY
1682 See the readme file for detailed release notes for this version.
1692 http://daringfireball.net
1694 PHP port and other contributions by Michel Fortin
1698 =head1 COPYRIGHT AND LICENSE
1700 Copyright (c) 2003-2004 John Gruber
1701 <http://daringfireball.net/>
1702 All rights reserved.
1704 Redistribution and use in source and binary forms, with or without
1705 modification, are permitted provided that the following conditions are
1708 * Redistributions of source code must retain the above copyright notice,
1709 this list of conditions and the following disclaimer.
1711 * Redistributions in binary form must reproduce the above copyright
1712 notice, this list of conditions and the following disclaimer in the
1713 documentation and/or other materials provided with the distribution.
1715 * Neither the name "Markdown" nor the names of its contributors may
1716 be used to endorse or promote products derived from this software
1717 without specific prior written permission.
1719 This software is provided by the copyright holders and contributors "as
1720 is" and any express or implied warranties, including, but not limited
1721 to, the implied warranties of merchantability and fitness for a
1722 particular purpose are disclaimed. In no event shall the copyright owner
1723 or contributors be liable for any direct, indirect, incidental, special,
1724 exemplary, or consequential damages (including, but not limited to,
1725 procurement of substitute goods or services; loss of use, data, or
1726 profits; or business interruption) however caused and on any theory of
1727 liability, whether in contract, strict liability, or tort (including
1728 negligence or otherwise) arising in any way out of the use of this
1729 software, even if advised of the possibility of such damage.