3 # Markdown Extra - A text-to-HTML conversion tool for web writers
6 # Copyright (c) 2004-2008 Michel Fortin
7 # <http://www.michelf.com/projects/php-markdown/>
10 # Copyright (c) 2004-2006 John Gruber
11 # <http://daringfireball.net/projects/markdown/>
15 define( 'MARKDOWN_VERSION', "1.0.1m" ); # Sat 21 Jun 2008
16 define( 'MARKDOWNEXTRA_VERSION', "1.2.3" ); # Wed 31 Dec 2008
20 # Global default settings:
23 # Change to ">" for HTML output
24 @define( 'MARKDOWN_EMPTY_ELEMENT_SUFFIX', " />");
26 # Define the width of a tab for code blocks.
27 @define( 'MARKDOWN_TAB_WIDTH', 4 );
29 # Optional title attribute for footnote links and backlinks.
30 @define( 'MARKDOWN_FN_LINK_TITLE', "" );
31 @define( 'MARKDOWN_FN_BACKLINK_TITLE', "" );
33 # Optional class attribute for footnote links and backlinks.
34 @define( 'MARKDOWN_FN_LINK_CLASS', "" );
35 @define( 'MARKDOWN_FN_BACKLINK_CLASS', "" );
37 # Enables special handling for links pointing outside of the current domain.
38 @define( 'MARKDOWN_EL_ENABLE', true); # Use this feature at all?
39 @define( 'MARKDOWN_EL_LOCAL_DOMAIN', null); # Leave as null to autodetect
40 @define( 'MARKDOWN_EL_NEW_WINDOW', true); # Open link in a new browser?
41 @define( 'MARKDOWN_EL_CSS_CLASS', 'external'); # Leave as null for no class
43 # Enables header auto-self-linking.
44 @define( 'MARKDOWN_HA_ENABLE', true ); # Use this feature at all?
45 @define( 'MARKDOWN_HA_CLASS', 'hidden-selflink' ); # Leave as null for no class
46 @define( 'MARKDOWN_HA_TEXT', '←' ); # The text to use as the link
53 # Change to false to remove Markdown from posts and/or comments.
54 @define( 'MARKDOWN_WP_POSTS', true );
55 @define( 'MARKDOWN_WP_COMMENTS', true );
59 ### Standard Function Interface ###
61 @define( 'MARKDOWN_PARSER_CLASS', 'MarkdownExtra_Parser' );
63 function Markdown($text) {
65 # Initialize the parser and return the result of its transform method.
67 # Setup static parser variable.
69 if (!isset($parser)) {
70 $parser_class = MARKDOWN_PARSER_CLASS;
71 $parser = new $parser_class;
74 # Transform text using parser.
75 return $parser->transform($text);
79 ### WordPress Plugin Interface ###
82 Plugin Name: Markdown Extra
83 Plugin URI: http://www.michelf.com/projects/php-markdown/
84 Description: <a href="http://daringfireball.net/projects/markdown/syntax">Markdown syntax</a> allows you to write using an easy-to-read, easy-to-write plain text format. Based on the original Perl version by <a href="http://daringfireball.net/">John Gruber</a>. <a href="http://www.michelf.com/projects/php-markdown/">More...</a>
87 Author URI: http://www.michelf.com/
90 if (isset($wp_version)) {
91 # More details about how it works here:
92 # <http://www.michelf.com/weblog/2005/wordpress-text-flow-vs-markdown/>
94 # Post content and excerpts
95 # - Remove WordPress paragraph generator.
96 # - Run Markdown on excerpt, then remove all tags.
97 # - Add paragraph tag around the excerpt, but remove it for the excerpt rss.
98 if (MARKDOWN_WP_POSTS) {
99 remove_filter('the_content', 'wpautop');
100 remove_filter('the_content_rss', 'wpautop');
101 remove_filter('the_excerpt', 'wpautop');
102 add_filter('the_content', 'mdwp_MarkdownPost', 6);
103 add_filter('the_content_rss', 'mdwp_MarkdownPost', 6);
104 add_filter('get_the_excerpt', 'mdwp_MarkdownPost', 6);
105 add_filter('get_the_excerpt', 'trim', 7);
106 add_filter('the_excerpt', 'mdwp_add_p');
107 add_filter('the_excerpt_rss', 'mdwp_strip_p');
109 remove_filter('content_save_pre', 'balanceTags', 50);
110 remove_filter('excerpt_save_pre', 'balanceTags', 50);
111 add_filter('the_content', 'balanceTags', 50);
112 add_filter('get_the_excerpt', 'balanceTags', 9);
115 # Add a footnote id prefix to posts when inside a loop.
116 function mdwp_MarkdownPost($text) {
119 $parser_class = MARKDOWN_PARSER_CLASS;
120 $parser = new $parser_class;
122 if (is_single() || is_page() || is_feed()) {
123 $parser->fn_id_prefix = "";
125 $parser->fn_id_prefix = get_the_ID() . ".";
127 return $parser->transform($text);
131 # - Remove WordPress paragraph generator.
132 # - Remove WordPress auto-link generator.
133 # - Scramble important tags before passing them to the kses filter.
134 # - Run Markdown on excerpt then remove paragraph tags.
135 if (MARKDOWN_WP_COMMENTS) {
136 remove_filter('comment_text', 'wpautop', 30);
137 remove_filter('comment_text', 'make_clickable');
138 add_filter('pre_comment_content', 'Markdown', 6);
139 add_filter('pre_comment_content', 'mdwp_hide_tags', 8);
140 add_filter('pre_comment_content', 'mdwp_show_tags', 12);
141 add_filter('get_comment_text', 'Markdown', 6);
142 add_filter('get_comment_excerpt', 'Markdown', 6);
143 add_filter('get_comment_excerpt', 'mdwp_strip_p', 7);
145 global $mdwp_hidden_tags, $mdwp_placeholders;
146 $mdwp_hidden_tags = explode(' ',
147 '<p> </p> <pre> </pre> <ol> </ol> <ul> </ul> <li> </li>');
148 $mdwp_placeholders = explode(' ', str_rot13(
149 'pEj07ZbbBZ U1kqgh4w4p pre2zmeN6K QTi31t9pre ol0MP1jzJR '.
150 'ML5IjmbRol ulANi1NsGY J7zRLJqPul liA8ctl16T K9nhooUHli'));
153 function mdwp_add_p($text) {
154 if (!preg_match('{^$|^<(p|ul|ol|dl|pre|blockquote)>}i', $text)) {
155 $text = '<p>'.$text.'</p>';
156 $text = preg_replace('{\n{2,}}', "</p>\n\n<p>", $text);
161 function mdwp_strip_p($t) { return preg_replace('{</?p>}i', '', $t); }
163 function mdwp_hide_tags($text) {
164 global $mdwp_hidden_tags, $mdwp_placeholders;
165 return str_replace($mdwp_hidden_tags, $mdwp_placeholders, $text);
167 function mdwp_show_tags($text) {
168 global $mdwp_hidden_tags, $mdwp_placeholders;
169 return str_replace($mdwp_placeholders, $mdwp_hidden_tags, $text);
174 ### bBlog Plugin Info ###
176 function identify_modifier_markdown() {
178 'name' => 'markdown',
179 'type' => 'modifier',
180 'nicename' => 'PHP Markdown Extra',
181 'description' => 'A text-to-HTML conversion tool for web writers',
182 'authors' => 'Michel Fortin and John Gruber',
184 'version' => MARKDOWNEXTRA_VERSION,
185 'help' => '<a href="http://daringfireball.net/projects/markdown/syntax">Markdown syntax</a> allows you to write using an easy-to-read, easy-to-write plain text format. Based on the original Perl version by <a href="http://daringfireball.net/">John Gruber</a>. <a href="http://www.michelf.com/projects/php-markdown/">More...</a>',
190 ### Smarty Modifier Interface ###
192 function smarty_modifier_markdown($text) {
193 return Markdown($text);
197 ### Textile Compatibility Mode ###
199 # Rename this file to "classTextile.php" and it can replace Textile everywhere.
201 if (strcasecmp(substr(__FILE__, -16), "classTextile.php") == 0) {
202 # Try to include PHP SmartyPants. Should be in the same directory.
203 @include_once 'smartypants.php';
204 # Fake Textile class. It calls Markdown instead.
206 function TextileThis($text, $lite='', $encode='') {
207 if ($lite == '' && $encode == '') $text = Markdown($text);
208 if (function_exists('SmartyPants')) $text = SmartyPants($text);
211 # Fake restricted version: restrictions are not supported for now.
212 function TextileRestricted($text, $lite='', $noimage='') {
213 return $this->TextileThis($text, $lite);
215 # Workaround to ensure compatibility with TextPattern 4.0.3.
216 function blockLite($text) { return $text; }
223 # Markdown Parser Class
226 class Markdown_Parser {
228 # Regex to match balanced [brackets].
229 # Needed to insert a maximum bracked depth while converting to PHP.
230 var $nested_brackets_depth = 6;
231 var $nested_brackets_re;
233 var $nested_url_parenthesis_depth = 4;
234 var $nested_url_parenthesis_re;
236 # Table of hash values for escaped characters:
237 var $escape_chars = '\`*_{}[]()>#+-.!';
238 var $escape_chars_re;
240 # Change to ">" for HTML output.
241 var $empty_element_suffix = MARKDOWN_EMPTY_ELEMENT_SUFFIX;
242 var $tab_width = MARKDOWN_TAB_WIDTH;
244 # Change to `true` to disallow markup or entities.
245 var $no_markup = false;
246 var $no_entities = false;
248 # Predefined urls and titles for reference links and images.
249 var $predef_urls = array();
250 var $predef_titles = array();
253 function Markdown_Parser() {
255 # Constructor function. Initialize appropriate member variables.
258 $this->prepareItalicsAndBold();
260 $this->nested_brackets_re =
261 str_repeat('(?>[^\[\]]+|\[', $this->nested_brackets_depth).
262 str_repeat('\])*', $this->nested_brackets_depth);
264 $this->nested_url_parenthesis_re =
265 str_repeat('(?>[^()\s]+|\(', $this->nested_url_parenthesis_depth).
266 str_repeat('(?>\)))*', $this->nested_url_parenthesis_depth);
268 $this->escape_chars_re = '['.preg_quote($this->escape_chars).']';
270 # Sort document, block, and span gamut in ascendent priority order.
271 asort($this->document_gamut);
272 asort($this->block_gamut);
273 asort($this->span_gamut);
277 # Internal hashes used during transformation.
279 var $titles = array();
280 var $html_hashes = array();
282 # Status flag to avoid invalid nesting.
283 var $in_anchor = false;
288 # Called before the transformation process starts to setup parser
291 # Clear global hashes.
292 $this->urls = $this->predef_urls;
293 $this->titles = $this->predef_titles;
294 $this->html_hashes = array();
299 function teardown() {
301 # Called after the transformation process to clear any variable
302 # which may be taking up memory unnecessarly.
304 $this->urls = array();
305 $this->titles = array();
306 $this->html_hashes = array();
310 function transform($text) {
312 # Main function. Performs some preprocessing on the input text
313 # and pass it through the document gamut.
317 # Remove UTF-8 BOM and marker character in input, if present.
318 $text = preg_replace('{^\xEF\xBB\xBF|\x1A}', '', $text);
320 # Standardize line endings:
321 # DOS to Unix and Mac to Unix
322 $text = preg_replace('{\r\n?}', "\n", $text);
324 # Make sure $text ends with a couple of newlines:
327 # Convert all tabs to spaces.
328 $text = $this->detab($text);
330 # Turn block-level HTML blocks into hash entries
331 $text = $this->hashHTMLBlocks($text);
333 # Strip any lines consisting only of spaces and tabs.
334 # This makes subsequent regexen easier to write, because we can
335 # match consecutive blank lines with /\n+/ instead of something
336 # contorted like /[ ]*\n+/ .
337 $text = preg_replace('/^[ ]+$/m', '', $text);
339 # Run document gamut methods.
340 foreach ($this->document_gamut as $method => $priority) {
341 $text = $this->$method($text);
349 var $document_gamut = array(
350 # Strip link definitions, store in hashes.
351 "stripLinkDefinitions" => 20,
353 "runBasicBlockGamut" => 30,
357 function stripLinkDefinitions($text) {
359 # Strips link definitions from text, stores the URLs and titles in
362 $less_than_tab = $this->tab_width - 1;
364 # Link defs are in the form: ^[id]: url "optional title"
365 $text = preg_replace_callback('{
366 ^[ ]{0,'.$less_than_tab.'}\[(.+)\][ ]?: # id = $1
368 \n? # maybe *one* newline
370 <?(\S+?)>? # url = $2
372 \n? # maybe one newline
375 (?<=\s) # lookbehind for whitespace
380 )? # title is optional
383 array(&$this, '_stripLinkDefinitions_callback'),
387 function _stripLinkDefinitions_callback($matches) {
388 $link_id = strtolower($matches[1]);
389 $this->urls[$link_id] = $matches[2];
390 $this->titles[$link_id] =& $matches[3];
391 return ''; # String that will replace the block
395 function hashHTMLBlocks($text) {
396 if ($this->no_markup) return $text;
398 $less_than_tab = $this->tab_width - 1;
400 # Hashify HTML blocks:
401 # We only want to do this for block-level HTML tags, such as headers,
402 # lists, and tables. That's because we still want to wrap <p>s around
403 # "paragraphs" that are wrapped in non-block-level tags, such as anchors,
404 # phrase emphasis, and spans. The list of tags we're looking for is
407 # * List "a" is made of tags which can be both inline or block-level.
408 # These will be treated block-level when the start tag is alone on
409 # its line, otherwise they're not matched here and will be taken as
411 # * List "b" is made of tags which are always block-level;
413 $block_tags_a_re = 'ins|del';
414 $block_tags_b_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|'.
415 'script|noscript|form|fieldset|iframe|math|textarea';
417 # Regular expression for the content of a block tag.
418 $nested_tags_level = 4;
420 (?> # optional tag attributes
421 \s # starts with whitespace
423 [^>"/]+ # text outside quotes
425 /+(?!>) # slash not followed by ">"
427 "[^"]*" # text inside double quotes (tolerate ">")
429 \'[^\']*\' # text inside single quotes (tolerate ">")
436 [^<]+ # content without tag
438 <\2 # nested opening tag
439 '.$attr.' # attributes
443 >', $nested_tags_level). # end of opening tag
444 '.*?'. # last level nested tag content
446 </\2\s*> # closing nested tag
449 <(?!/\2\s*> # other tags with a different name
453 $content2 = str_replace('\2', '\3', $content);
455 # First, look for nested blocks, e.g.:
458 # tags for inner block must be indented.
462 # The outermost tags must start at the left margin for this to match, and
463 # the inner nested divs must be indented.
464 # We need to do this before the next, more liberal match, because the next
465 # match will start at the first `<div>` and stop at the first `</div>`.
466 $text = preg_replace_callback('{(?>
468 (?<=\n\n) # Starting after a blank line
470 \A\n? # the beginning of the doc
474 # Match from `\n<tag>` to `</tag>\n`, handling nested tags
477 [ ]{0,'.$less_than_tab.'}
478 <('.$block_tags_b_re.')# start tag = $2
479 '.$attr.'> # attributes followed by > and \n
480 '.$content.' # content, support nesting
481 </\2> # the matching end tag
482 [ ]* # trailing spaces/tabs
483 (?=\n+|\Z) # followed by a newline or end of document
485 | # Special version for tags of group a.
487 [ ]{0,'.$less_than_tab.'}
488 <('.$block_tags_a_re.')# start tag = $3
489 '.$attr.'>[ ]*\n # attributes followed by >
490 '.$content2.' # content, support nesting
491 </\3> # the matching end tag
492 [ ]* # trailing spaces/tabs
493 (?=\n+|\Z) # followed by a newline or end of document
495 | # Special case just for <hr />. It was easier to make a special
496 # case than to make the other regex more complicated.
498 [ ]{0,'.$less_than_tab.'}
499 <(hr) # start tag = $2
500 '.$attr.' # attributes
501 /?> # the matching end tag
503 (?=\n{2,}|\Z) # followed by a blank line or end of document
505 | # Special case for standalone HTML comments:
507 [ ]{0,'.$less_than_tab.'}
512 (?=\n{2,}|\Z) # followed by a blank line or end of document
514 | # PHP and ASP-style processor instructions (<? and <%)
516 [ ]{0,'.$less_than_tab.'}
523 (?=\n{2,}|\Z) # followed by a blank line or end of document
527 array(&$this, '_hashHTMLBlocks_callback'),
532 function _hashHTMLBlocks_callback($matches) {
534 $key = $this->hashBlock($text);
535 return "\n\n$key\n\n";
539 function hashPart($text, $boundary = 'X') {
541 # Called whenever a tag must be hashed when a function insert an atomic
542 # element in the text stream. Passing $text to through this function gives
543 # a unique text-token which will be reverted back when calling unhash.
545 # The $boundary argument specify what character should be used to surround
546 # the token. By convension, "B" is used for block elements that needs not
547 # to be wrapped into paragraph tags at the end, ":" is used for elements
548 # that are word separators and "X" is used in the general case.
550 # Swap back any tag hash found in $text so we do not have to `unhash`
551 # multiple times at the end.
552 $text = $this->unhash($text);
554 # Then hash the block.
556 $key = "$boundary\x1A" . ++$i . $boundary;
557 $this->html_hashes[$key] = $text;
558 return $key; # String that will replace the tag.
562 function hashBlock($text) {
564 # Shortcut function for hashPart with block-level boundaries.
566 return $this->hashPart($text, 'B');
570 var $block_gamut = array(
572 # These are all the transformations that form block-level
573 # tags like paragraphs, headers, and list items.
576 "doHorizontalRules" => 20,
579 "doCodeBlocks" => 50,
580 "doBlockQuotes" => 60,
583 function runBlockGamut($text) {
585 # Run block gamut tranformations.
587 # We need to escape raw HTML in Markdown source before doing anything
588 # else. This need to be done for each block, and not only at the
589 # begining in the Markdown function since hashed blocks can be part of
590 # list items and could have been indented. Indented blocks would have
591 # been seen as a code block in a previous pass of hashHTMLBlocks.
592 $text = $this->hashHTMLBlocks($text);
594 return $this->runBasicBlockGamut($text);
597 function runBasicBlockGamut($text) {
599 # Run block gamut tranformations, without hashing HTML blocks. This is
600 # useful when HTML blocks are known to be already hashed, like in the first
601 # whole-document pass.
603 foreach ($this->block_gamut as $method => $priority) {
604 $text = $this->$method($text);
607 # Finally form paragraph and restore hashed blocks.
608 $text = $this->formParagraphs($text);
614 function doHorizontalRules($text) {
615 # Do Horizontal Rules:
618 ^[ ]{0,3} # Leading space
619 ([-*_]) # $1: First marker
620 (?> # Repeated marker group
621 [ ]{0,2} # Zero, one, or two spaces.
622 \1 # Marker character
623 ){2,} # Group repeated at least twice
624 [ ]* # Tailing spaces
627 "\n".$this->hashBlock("<hr$this->empty_element_suffix")."\n",
632 var $span_gamut = array(
634 # These are all the transformations that occur *within* block-level
635 # tags like paragraphs, headers, and list items.
637 # Process character escapes, code spans, and inline HTML
641 # Process anchor and image tags. Images must come first,
642 # because ![foo][f] looks like an anchor.
646 # Make links out of things like `<http://example.com/>`
647 # Must come after doAnchors, because you can use < and >
648 # delimiters in inline links like [this](<url>).
650 "encodeAmpsAndAngles" => 40,
652 "doItalicsAndBold" => 50,
653 "doHardBreaks" => 60,
656 function runSpanGamut($text) {
658 # Run span gamut tranformations.
660 foreach ($this->span_gamut as $method => $priority) {
661 $text = $this->$method($text);
668 function doHardBreaks($text) {
670 return preg_replace_callback('/ {2,}\n/',
671 array(&$this, '_doHardBreaks_callback'), $text);
673 function _doHardBreaks_callback($matches) {
674 return $this->hashPart("<br$this->empty_element_suffix\n");
678 function doAnchors($text) {
680 # Turn Markdown link shortcuts into XHTML <a> tags.
682 if ($this->in_anchor) return $text;
683 $this->in_anchor = true;
686 # First, handle reference-style links: [link text] [id]
688 $text = preg_replace_callback('{
689 ( # wrap whole match in $1
691 ('.$this->nested_brackets_re.') # link text = $2
694 [ ]? # one optional space
695 (?:\n[ ]*)? # one optional newline followed by spaces
702 array(&$this, '_doAnchors_reference_callback'), $text);
705 # Next, inline-style links: [link text](url "optional title")
707 $text = preg_replace_callback('{
708 ( # wrap whole match in $1
710 ('.$this->nested_brackets_re.') # link text = $2
717 ('.$this->nested_url_parenthesis_re.') # href = $4
721 ([\'"]) # quote char = $6
724 [ ]* # ignore any spaces/tabs between closing quote and )
725 )? # title is optional
729 array(&$this, '_DoAnchors_inline_callback'), $text);
732 # Last, handle reference-style shortcuts: [link text]
733 # These must come last in case you've also got [link test][1]
734 # or [link test](/foo)
736 // $text = preg_replace_callback('{
737 // ( # wrap whole match in $1
739 // ([^\[\]]+) # link text = $2; can\'t contain [ or ]
743 // array(&$this, '_doAnchors_reference_callback'), $text);
745 $this->in_anchor = false;
748 function _doAnchors_reference_callback($matches) {
749 $whole_match = $matches[1];
750 $link_text = $matches[2];
751 $link_id =& $matches[3];
753 if ($link_id == "") {
754 # for shortcut links like [this][] or [this].
755 $link_id = $link_text;
758 # lower-case and turn embedded newlines into spaces
759 $link_id = strtolower($link_id);
760 $link_id = preg_replace('{[ ]?\n}', ' ', $link_id);
762 if (isset($this->urls[$link_id])) {
763 $url = $this->urls[$link_id];
764 $url = $this->encodeAttribute($url);
766 $result = "<a href=\"$url\"";
767 if ( isset( $this->titles[$link_id] ) ) {
768 $title = $this->titles[$link_id];
769 $title = $this->encodeAttribute($title);
770 $result .= " title=\"$title\"";
773 $link_text = $this->runSpanGamut($link_text);
774 $result .= ">$link_text</a>";
775 $result = $this->hashPart($result);
778 $result = $whole_match;
782 function _doAnchors_inline_callback($matches) {
783 $whole_match = $matches[1];
784 $link_text = $this->runSpanGamut($matches[2]);
785 $url = $matches[3] == '' ? $matches[4] : $matches[3];
786 $title =& $matches[7];
788 $url = $this->encodeAttribute($url);
790 $result = "<a href=\"$url\"";
792 $title = $this->encodeAttribute($title);
793 $result .= " title=\"$title\"";
796 $link_text = $this->runSpanGamut($link_text);
797 $result .= ">$link_text</a>";
799 return $this->hashPart($result);
803 function doImages($text) {
805 # Turn Markdown image shortcuts into <img> tags.
808 # First, handle reference-style labeled images: ![alt text][id]
810 $text = preg_replace_callback('{
811 ( # wrap whole match in $1
813 ('.$this->nested_brackets_re.') # alt text = $2
816 [ ]? # one optional space
817 (?:\n[ ]*)? # one optional newline followed by spaces
825 array(&$this, '_doImages_reference_callback'), $text);
828 # Next, handle inline images: ![alt text](url "optional title")
829 # Don't forget: encode * and _
831 $text = preg_replace_callback('{
832 ( # wrap whole match in $1
834 ('.$this->nested_brackets_re.') # alt text = $2
836 \s? # One optional whitespace character
840 <(\S*)> # src url = $3
842 ('.$this->nested_url_parenthesis_re.') # src url = $4
846 ([\'"]) # quote char = $6
850 )? # title is optional
854 array(&$this, '_doImages_inline_callback'), $text);
858 function _doImages_reference_callback($matches) {
859 $whole_match = $matches[1];
860 $alt_text = $matches[2];
861 $link_id = strtolower($matches[3]);
863 if ($link_id == "") {
864 $link_id = strtolower($alt_text); # for shortcut links like ![this][].
867 $alt_text = $this->encodeAttribute($alt_text);
868 if (isset($this->urls[$link_id])) {
869 $url = $this->encodeAttribute($this->urls[$link_id]);
870 $result = "<img src=\"$url\" alt=\"$alt_text\"";
871 if (isset($this->titles[$link_id])) {
872 $title = $this->titles[$link_id];
873 $title = $this->encodeAttribute($title);
874 $result .= " title=\"$title\"";
876 $result .= $this->empty_element_suffix;
877 $result = $this->hashPart($result);
880 # If there's no such link ID, leave intact:
881 $result = $whole_match;
886 function _doImages_inline_callback($matches) {
887 $whole_match = $matches[1];
888 $alt_text = $matches[2];
889 $url = $matches[3] == '' ? $matches[4] : $matches[3];
890 $title =& $matches[7];
892 $alt_text = $this->encodeAttribute($alt_text);
893 $url = $this->encodeAttribute($url);
894 $result = "<img src=\"$url\" alt=\"$alt_text\"";
896 $title = $this->encodeAttribute($title);
897 $result .= " title=\"$title\""; # $title already quoted
899 $result .= $this->empty_element_suffix;
901 return $this->hashPart($result);
905 function doHeaders($text) {
906 # Setext-style headers:
913 $text = preg_replace_callback('{ ^(.+?)[ ]*\n(=+|-+)[ ]*\n+ }mx',
914 array(&$this, '_doHeaders_callback_setext'), $text);
919 # ## Header 2 with closing hashes ##
923 $text = preg_replace_callback('{
924 ^(\#{1,6}) # $1 = string of #\'s
926 (.+?) # $2 = Header text
928 \#* # optional closing #\'s (not counted)
931 array(&$this, '_doHeaders_callback_atx'), $text);
935 function _doHeaders_callback_setext($matches) {
936 # Terrible hack to check we haven't found an empty list item.
937 if ($matches[2] == '-' && preg_match('{^-(?: |$)}', $matches[1]))
940 $level = $matches[2]{0} == '=' ? 1 : 2;
941 $block = "<h$level>".$this->runSpanGamut($matches[1])."</h$level>";
942 return "\n" . $this->hashBlock($block) . "\n\n";
944 function _doHeaders_callback_atx($matches) {
945 $level = strlen($matches[1]);
946 $block = "<h$level>".$this->runSpanGamut($matches[2])."</h$level>";
947 return "\n" . $this->hashBlock($block) . "\n\n";
951 function doLists($text) {
953 # Form HTML ordered (numbered) and unordered (bulleted) lists.
955 $less_than_tab = $this->tab_width - 1;
957 # Re-usable patterns to match list item bullets and number markers:
958 $marker_ul_re = '[*+-]';
959 $marker_ol_re = '\d+[.]';
960 $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)";
962 $markers_relist = array($marker_ul_re, $marker_ol_re);
964 foreach ($markers_relist as $marker_re) {
965 # Re-usable pattern to match any entirel ul or ol list:
969 [ ]{0,'.$less_than_tab.'}
970 ('.$marker_re.') # $3 = first list item marker
979 (?! # Negative lookahead for another list item marker
987 # We use a different prefix before nested lists than top-level lists.
988 # See extended comment in _ProcessListItems().
990 if ($this->list_level) {
991 $text = preg_replace_callback('{
995 array(&$this, '_doLists_callback'), $text);
998 $text = preg_replace_callback('{
999 (?:(?<=\n)\n|\A\n?) # Must eat the newline
1002 array(&$this, '_doLists_callback'), $text);
1008 function _doLists_callback($matches) {
1009 # Re-usable patterns to match list item bullets and number markers:
1010 $marker_ul_re = '[*+-]';
1011 $marker_ol_re = '\d+[.]';
1012 $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)";
1014 $list = $matches[1];
1015 $list_type = preg_match("/$marker_ul_re/", $matches[3]) ? "ul" : "ol";
1017 $marker_any_re = ( $list_type == "ul" ? $marker_ul_re : $marker_ol_re );
1020 $result = $this->processListItems($list, $marker_any_re);
1022 $result = $this->hashBlock("<$list_type>\n" . $result . "</$list_type>");
1023 return "\n". $result ."\n\n";
1026 var $list_level = 0;
1028 function processListItems($list_str, $marker_any_re) {
1030 # Process the contents of a single ordered or unordered list, splitting it
1031 # into individual list items.
1033 # The $this->list_level global keeps track of when we're inside a list.
1034 # Each time we enter a list, we increment it; when we leave a list,
1035 # we decrement. If it's zero, we're not in a list anymore.
1037 # We do this because when we're not inside a list, we want to treat
1038 # something like this:
1040 # I recommend upgrading to version
1041 # 8. Oops, now this line is treated
1044 # As a single paragraph, despite the fact that the second line starts
1045 # with a digit-period-space sequence.
1047 # Whereas when we're inside a list (or sub-list), that line will be
1048 # treated as the start of a sub-list. What a kludge, huh? This is
1049 # an aspect of Markdown's syntax that's hard to parse perfectly
1050 # without resorting to mind-reading. Perhaps the solution is to
1051 # change the syntax rules such that sub-lists must start with a
1052 # starting cardinal number; e.g. "1." or "a.".
1054 $this->list_level++;
1056 # trim trailing blank lines:
1057 $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str);
1059 $list_str = preg_replace_callback('{
1060 (\n)? # leading line = $1
1061 (^[ ]*) # leading whitespace = $2
1062 ('.$marker_any_re.' # list marker and space = $3
1063 (?:[ ]+|(?=\n)) # space only required if item is not empty
1065 ((?s:.*?)) # list item text = $4
1066 (?:(\n+(?=\n))|\n) # tailing blank line = $5
1067 (?= \n* (\z | \2 ('.$marker_any_re.') (?:[ ]+|(?=\n))))
1069 array(&$this, '_processListItems_callback'), $list_str);
1071 $this->list_level--;
1074 function _processListItems_callback($matches) {
1075 $item = $matches[4];
1076 $leading_line =& $matches[1];
1077 $leading_space =& $matches[2];
1078 $marker_space = $matches[3];
1079 $tailing_blank_line =& $matches[5];
1081 if ($leading_line || $tailing_blank_line ||
1082 preg_match('/\n{2,}/', $item))
1084 # Replace marker with the appropriate whitespace indentation
1085 $item = $leading_space . str_repeat(' ', strlen($marker_space)) . $item;
1086 $item = $this->runBlockGamut($this->outdent($item)."\n");
1089 # Recursion for sub-lists:
1090 $item = $this->doLists($this->outdent($item));
1091 $item = preg_replace('/\n+$/', '', $item);
1092 $item = $this->runSpanGamut($item);
1095 return "<li>" . $item . "</li>\n";
1099 function doCodeBlocks($text) {
1101 # Process Markdown `<pre><code>` blocks.
1103 $text = preg_replace_callback('{
1105 ( # $1 = the code block -- one or more lines, starting with a space/tab
1107 [ ]{'.$this->tab_width.'} # Lines must start with a tab or a tab-width of spaces
1111 ((?=^[ ]{0,'.$this->tab_width.'}\S)|\Z) # Lookahead for non-space at line-start, or end of doc
1113 array(&$this, '_doCodeBlocks_callback'), $text);
1117 function _doCodeBlocks_callback($matches) {
1118 $codeblock = $matches[1];
1120 $codeblock = $this->outdent($codeblock);
1121 $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES);
1123 # trim leading newlines and trailing newlines
1124 $codeblock = preg_replace('/\A\n+|\n+\z/', '', $codeblock);
1126 $codeblock = "<pre><code>$codeblock\n</code></pre>";
1127 return "\n\n".$this->hashBlock($codeblock)."\n\n";
1131 function makeCodeSpan($code) {
1133 # Create a code span markup for $code. Called from handleSpanToken.
1135 $code = htmlspecialchars(trim($code), ENT_NOQUOTES);
1136 return $this->hashPart("<code>$code</code>");
1140 var $em_relist = array(
1141 '' => '(?:(?<!\*)\*(?!\*)|(?<!_)_(?!_))(?=\S)(?![.,:;]\s)',
1142 '*' => '(?<=\S)(?<!\*)\*(?!\*)',
1143 '_' => '(?<=\S)(?<!_)_(?!_)',
1145 var $strong_relist = array(
1146 '' => '(?:(?<!\*)\*\*(?!\*)|(?<!_)__(?!_))(?=\S)(?![.,:;]\s)',
1147 '**' => '(?<=\S)(?<!\*)\*\*(?!\*)',
1148 '__' => '(?<=\S)(?<!_)__(?!_)',
1150 var $em_strong_relist = array(
1151 '' => '(?:(?<!\*)\*\*\*(?!\*)|(?<!_)___(?!_))(?=\S)(?![.,:;]\s)',
1152 '***' => '(?<=\S)(?<!\*)\*\*\*(?!\*)',
1153 '___' => '(?<=\S)(?<!_)___(?!_)',
1155 var $em_strong_prepared_relist;
1157 function prepareItalicsAndBold() {
1159 # Prepare regular expressions for seraching emphasis tokens in any
1162 foreach ($this->em_relist as $em => $em_re) {
1163 foreach ($this->strong_relist as $strong => $strong_re) {
1164 # Construct list of allowed token expressions.
1165 $token_relist = array();
1166 if (isset($this->em_strong_relist["$em$strong"])) {
1167 $token_relist[] = $this->em_strong_relist["$em$strong"];
1169 $token_relist[] = $em_re;
1170 $token_relist[] = $strong_re;
1172 # Construct master expression from list.
1173 $token_re = '{('. implode('|', $token_relist) .')}';
1174 $this->em_strong_prepared_relist["$em$strong"] = $token_re;
1179 function doItalicsAndBold($text) {
1180 $token_stack = array('');
1181 $text_stack = array('');
1184 $tree_char_em = false;
1188 # Get prepared regular expression for seraching emphasis tokens
1189 # in current context.
1191 $token_re = $this->em_strong_prepared_relist["$em$strong"];
1194 # Each loop iteration seach for the next emphasis token.
1195 # Each token is then passed to handleSpanToken.
1197 $parts = preg_split($token_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE);
1198 $text_stack[0] .= $parts[0];
1199 $token =& $parts[1];
1202 if (empty($token)) {
1203 # Reached end of text span: empty stack without emitting.
1204 # any more emphasis.
1205 while ($token_stack[0]) {
1206 $text_stack[1] .= array_shift($token_stack);
1207 $text_stack[0] .= array_shift($text_stack);
1212 $token_len = strlen($token);
1213 if ($tree_char_em) {
1214 # Reached closing marker while inside a three-char emphasis.
1215 if ($token_len == 3) {
1216 # Three-char closing marker, close em and strong.
1217 array_shift($token_stack);
1218 $span = array_shift($text_stack);
1219 $span = $this->runSpanGamut($span);
1220 $span = "<strong><em>$span</em></strong>";
1221 $text_stack[0] .= $this->hashPart($span);
1225 # Other closing marker: close one em or strong and
1226 # change current token state to match the other
1227 $token_stack[0] = str_repeat($token{0}, 3-$token_len);
1228 $tag = $token_len == 2 ? "strong" : "em";
1229 $span = $text_stack[0];
1230 $span = $this->runSpanGamut($span);
1231 $span = "<$tag>$span</$tag>";
1232 $text_stack[0] = $this->hashPart($span);
1233 $$tag = ''; # $$tag stands for $em or $strong
1235 $tree_char_em = false;
1236 } else if ($token_len == 3) {
1238 # Reached closing marker for both em and strong.
1239 # Closing strong marker:
1240 for ($i = 0; $i < 2; ++$i) {
1241 $shifted_token = array_shift($token_stack);
1242 $tag = strlen($shifted_token) == 2 ? "strong" : "em";
1243 $span = array_shift($text_stack);
1244 $span = $this->runSpanGamut($span);
1245 $span = "<$tag>$span</$tag>";
1246 $text_stack[0] .= $this->hashPart($span);
1247 $$tag = ''; # $$tag stands for $em or $strong
1250 # Reached opening three-char emphasis marker. Push on token
1251 # stack; will be handled by the special condition above.
1254 array_unshift($token_stack, $token);
1255 array_unshift($text_stack, '');
1256 $tree_char_em = true;
1258 } else if ($token_len == 2) {
1260 # Unwind any dangling emphasis marker:
1261 if (strlen($token_stack[0]) == 1) {
1262 $text_stack[1] .= array_shift($token_stack);
1263 $text_stack[0] .= array_shift($text_stack);
1265 # Closing strong marker:
1266 array_shift($token_stack);
1267 $span = array_shift($text_stack);
1268 $span = $this->runSpanGamut($span);
1269 $span = "<strong>$span</strong>";
1270 $text_stack[0] .= $this->hashPart($span);
1273 array_unshift($token_stack, $token);
1274 array_unshift($text_stack, '');
1278 # Here $token_len == 1
1280 if (strlen($token_stack[0]) == 1) {
1281 # Closing emphasis marker:
1282 array_shift($token_stack);
1283 $span = array_shift($text_stack);
1284 $span = $this->runSpanGamut($span);
1285 $span = "<em>$span</em>";
1286 $text_stack[0] .= $this->hashPart($span);
1289 $text_stack[0] .= $token;
1292 array_unshift($token_stack, $token);
1293 array_unshift($text_stack, '');
1298 return $text_stack[0];
1302 function doBlockQuotes($text) {
1303 $text = preg_replace_callback('/
1304 ( # Wrap whole match in $1
1306 ^[ ]*>[ ]? # ">" at the start of a line
1307 .+\n # rest of the first line
1308 (.+\n)* # subsequent consecutive lines
1313 array(&$this, '_doBlockQuotes_callback'), $text);
1317 function _doBlockQuotes_callback($matches) {
1319 # trim one level of quoting - trim whitespace-only lines
1320 $bq = preg_replace('/^[ ]*>[ ]?|^[ ]+$/m', '', $bq);
1321 $bq = $this->runBlockGamut($bq); # recurse
1323 $bq = preg_replace('/^/m', " ", $bq);
1324 # These leading spaces cause problem with <pre> content,
1325 # so we need to fix that:
1326 $bq = preg_replace_callback('{(\s*<pre>.+?</pre>)}sx',
1327 array(&$this, '_DoBlockQuotes_callback2'), $bq);
1329 return "\n". $this->hashBlock("<blockquote>\n$bq\n</blockquote>")."\n\n";
1331 function _doBlockQuotes_callback2($matches) {
1333 $pre = preg_replace('/^ /m', '', $pre);
1338 function formParagraphs($text) {
1341 # $text - string to process with html <p> tags
1343 # Strip leading and trailing lines:
1344 $text = preg_replace('/\A\n+|\n+\z/', '', $text);
1346 $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY);
1349 # Wrap <p> tags and unhashify HTML blocks
1351 foreach ($grafs as $key => $value) {
1352 if (!preg_match('/^B\x1A[0-9]+B$/', $value)) {
1354 $value = $this->runSpanGamut($value);
1355 $value = preg_replace('/^([ ]*)/', "<p>", $value);
1357 $grafs[$key] = $this->unhash($value);
1361 # Modify elements of @grafs in-place...
1363 $block = $this->html_hashes[$graf];
1365 // if (preg_match('{
1367 // ( # $1 = <div> tag
1371 // markdown\s*=\s* ([\'"]) # $2 = attr quote char
1377 // ( # $3 = contents
1380 // (</div>) # $4 = closing tag
1382 // }xs', $block, $matches))
1384 // list(, $div_open, , $div_content, $div_close) = $matches;
1386 // # We can't call Markdown(), because that resets the hash;
1387 // # that initialization code should be pulled into its own sub, though.
1388 // $div_content = $this->hashHTMLBlocks($div_content);
1390 // # Run document gamut methods on the content.
1391 // foreach ($this->document_gamut as $method => $priority) {
1392 // $div_content = $this->$method($div_content);
1395 // $div_open = preg_replace(
1396 // '{\smarkdown\s*=\s*([\'"]).+?\1}', '', $div_open);
1398 // $graf = $div_open . "\n" . $div_content . "\n" . $div_close;
1400 $grafs[$key] = $graf;
1404 return implode("\n\n", $grafs);
1408 function encodeAttribute($text) {
1410 # Encode text for a double-quoted HTML attribute. This function
1411 # is *not* suitable for attributes enclosed in single quotes.
1413 $text = $this->encodeAmpsAndAngles($text);
1414 $text = str_replace('"', '"', $text);
1419 function encodeAmpsAndAngles($text) {
1421 # Smart processing for ampersands and angle brackets that need to
1422 # be encoded. Valid character entities are left alone unless the
1423 # no-entities mode is set.
1425 if ($this->no_entities) {
1426 $text = str_replace('&', '&', $text);
1428 # Ampersand-encoding based entirely on Nat Irons's Amputator
1429 # MT plugin: <http://bumppo.net/projects/amputator/>
1430 $text = preg_replace('/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/',
1433 # Encode remaining <'s
1434 $text = str_replace('<', '<', $text);
1440 function doAutoLinks($text) {
1441 $text = preg_replace_callback('{<((https?|ftp|dict):[^\'">\s]+)>}i',
1442 array(&$this, '_doAutoLinks_url_callback'), $text);
1444 # Email addresses: <address@domain.foo>
1445 $text = preg_replace_callback('{
1451 [-a-z0-9\x80-\xFF]+(\.[-a-z0-9\x80-\xFF]+)*\.[a-z]+
1455 array(&$this, '_doAutoLinks_email_callback'), $text);
1459 function _doAutoLinks_url_callback($matches) {
1460 $url = $this->encodeAttribute($matches[1]);
1461 $link = "<a href=\"$url\">$url</a>";
1462 return $this->hashPart($link);
1464 function _doAutoLinks_email_callback($matches) {
1465 $address = $matches[1];
1466 $link = $this->encodeEmailAddress($address);
1467 return $this->hashPart($link);
1471 function encodeEmailAddress($addr) {
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 # <p><a href="mailto:foo
1480 # @example.co
1481 # m">foo@exampl
1482 # e.com</a></p>
1484 # Based by a filter by Matthew Wickline, posted to BBEdit-Talk.
1485 # With some optimizations by Milian Wolff.
1487 $addr = "mailto:" . $addr;
1488 $chars = preg_split('/(?<!^)(?!$)/', $addr);
1489 $seed = (int)abs(crc32($addr) / strlen($addr)); # Deterministic seed.
1491 foreach ($chars as $key => $char) {
1493 # Ignore non-ascii chars.
1495 $r = ($seed * (1 + $key)) % 100; # Pseudo-random function.
1496 # roughly 10% raw, 45% hex, 45% dec
1497 # '@' *must* be encoded. I insist.
1498 if ($r > 90 && $char != '@') /* do nothing */;
1499 else if ($r < 45) $chars[$key] = '&#x'.dechex($ord).';';
1500 else $chars[$key] = '&#'.$ord.';';
1504 $addr = implode('', $chars);
1505 $text = implode('', array_slice($chars, 7)); # text without `mailto:`
1506 $addr = "<a href=\"$addr\">$text</a>";
1512 function parseSpan($str) {
1514 # Take the string $str and parse it into tokens, hashing embeded HTML,
1515 # escaped characters and handling code spans.
1521 \\\\'.$this->escape_chars_re.'
1524 `+ # code span marker
1525 '.( $this->no_markup ? '' : '
1527 <!-- .*? --> # comment
1529 <\?.*?\?> | <%.*?%> # processing instruction
1531 <[/!$]?[-a-zA-Z0-9:]+ # regular tags
1534 (?>[^"\'>]+|"[^"]*"|\'[^\']*\')*
1543 # Each loop iteration seach for either the next tag, the next
1544 # openning code span marker, or the next escaped character.
1545 # Each token is then passed to handleSpanToken.
1547 $parts = preg_split($span_re, $str, 2, PREG_SPLIT_DELIM_CAPTURE);
1549 # Create token from text preceding tag.
1550 if ($parts[0] != "") {
1551 $output .= $parts[0];
1554 # Check if we reach the end.
1555 if (isset($parts[1])) {
1556 $output .= $this->handleSpanToken($parts[1], $parts[2]);
1568 function handleSpanToken($token, &$str) {
1570 # Handle $token provided by parseSpan by determining its nature and
1571 # returning the corresponding value that should replace it.
1573 switch ($token{0}) {
1575 return $this->hashPart("&#". ord($token{1}). ";");
1577 # Search for end marker in remaining text.
1578 if (preg_match('/^(.*?[^`])'.preg_quote($token).'(?!`)(.*)$/sm',
1582 $codespan = $this->makeCodeSpan($matches[1]);
1583 return $this->hashPart($codespan);
1585 return $token; // return as text since no ending marker found.
1587 return $this->hashPart($token);
1592 function outdent($text) {
1594 # Remove one level of line-leading tabs or spaces
1596 return preg_replace('/^(\t|[ ]{1,'.$this->tab_width.'})/m', '', $text);
1600 # String length function for detab. `_initDetab` will create a function to
1601 # hanlde UTF-8 if the default function does not exist.
1602 var $utf8_strlen = 'mb_strlen';
1604 function detab($text) {
1606 # Replace tabs with the appropriate amount of space.
1608 # For each line we separate the line in blocks delemited by
1609 # tab characters. Then we reconstruct every line by adding the
1610 # appropriate number of space between each blocks.
1612 $text = preg_replace_callback('/^.*\t.*$/m',
1613 array(&$this, '_detab_callback'), $text);
1617 function _detab_callback($matches) {
1618 $line = $matches[0];
1619 $strlen = $this->utf8_strlen; # strlen function for UTF-8.
1622 $blocks = explode("\t", $line);
1623 # Add each blocks to the line.
1625 unset($blocks[0]); # Do not add first block twice.
1626 foreach ($blocks as $block) {
1627 # Calculate amount of space, insert spaces, insert block.
1628 $amount = $this->tab_width -
1629 $strlen($line, 'UTF-8') % $this->tab_width;
1630 $line .= str_repeat(" ", $amount) . $block;
1634 function _initDetab() {
1636 # Check for the availability of the function in the `utf8_strlen` property
1637 # (initially `mb_strlen`). If the function is not available, create a
1638 # function that will loosely count the number of UTF-8 characters with a
1639 # regular expression.
1641 if (function_exists($this->utf8_strlen)) return;
1642 $this->utf8_strlen = create_function('$text', 'return preg_match_all(
1643 "/[\\\\x00-\\\\xBF]|[\\\\xC0-\\\\xFF][\\\\x80-\\\\xBF]*/",
1648 function unhash($text) {
1650 # Swap back in all the tags hashed by _HashHTMLBlocks.
1652 return preg_replace_callback('/(.)\x1A[0-9]+\1/',
1653 array(&$this, '_unhash_callback'), $text);
1655 function _unhash_callback($matches) {
1656 return $this->html_hashes[$matches[0]];
1663 # Markdown Extra Parser Class
1666 class MarkdownExtra_Parser extends Markdown_Parser {
1668 # Prefix for footnote ids.
1669 var $fn_id_prefix = "";
1671 # Optional title attribute for footnote links and backlinks.
1672 var $fn_link_title = MARKDOWN_FN_LINK_TITLE;
1673 var $fn_backlink_title = MARKDOWN_FN_BACKLINK_TITLE;
1675 # Optional class attribute for footnote links and backlinks.
1676 var $fn_link_class = MARKDOWN_FN_LINK_CLASS;
1677 var $fn_backlink_class = MARKDOWN_FN_BACKLINK_CLASS;
1679 var $el_enable = MARKDOWN_EL_ENABLE;
1680 var $el_local_domain = MARKDOWN_EL_LOCAL_DOMAIN;
1681 var $el_new_window = MARKDOWN_EL_NEW_WINDOW;
1682 var $el_css_class = MARKDOWN_EL_CSS_CLASS;
1684 var $ha_enable = MARKDOWN_HA_ENABLE;
1685 var $ha_class = MARKDOWN_HA_CLASS;
1686 var $ha_text = MARKDOWN_HA_TEXT;
1688 # Predefined abbreviations.
1689 var $predef_abbr = array();
1692 function MarkdownExtra_Parser() {
1694 # Constructor function. Initialize the parser object.
1696 # Add extra escapable characters before parent constructor
1697 # initialize the table.
1698 $this->escape_chars .= ':|';
1700 if ($this->el_local_domain === null) {
1701 $this->el_local_domain = $_SERVER['SERVER_NAME'];
1704 # Insert extra document, block, and span transformations.
1705 # Parent constructor will do the sorting.
1706 $this->document_gamut += array(
1707 "doFencedCodeBlocks" => 5,
1708 "stripFootnotes" => 15,
1709 "stripAbbreviations" => 25,
1710 "appendFootnotes" => 50,
1712 $this->block_gamut += array(
1713 "doFencedCodeBlocks" => 5,
1717 $this->span_gamut += array(
1719 "doAbbreviations" => 70,
1722 parent::Markdown_Parser();
1726 # Extra variables used during extra transformations.
1727 var $footnotes = array();
1728 var $footnotes_ordered = array();
1729 var $abbr_desciptions = array();
1730 var $abbr_word_re = '';
1732 # Give the current footnote number.
1733 var $footnote_counter = 1;
1738 # Setting up Extra-specific variables.
1742 $this->footnotes = array();
1743 $this->footnotes_ordered = array();
1744 $this->abbr_desciptions = array();
1745 $this->abbr_word_re = '';
1746 $this->footnote_counter = 1;
1748 foreach ($this->predef_abbr as $abbr_word => $abbr_desc) {
1749 if ($this->abbr_word_re)
1750 $this->abbr_word_re .= '|';
1751 $this->abbr_word_re .= preg_quote($abbr_word);
1752 $this->abbr_desciptions[$abbr_word] = trim($abbr_desc);
1756 function teardown() {
1758 # Clearing Extra-specific variables.
1760 $this->footnotes = array();
1761 $this->footnotes_ordered = array();
1762 $this->abbr_desciptions = array();
1763 $this->abbr_word_re = '';
1769 ### HTML Block Parser ###
1771 # Tags that are always treated as block tags:
1772 var $block_tags_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|form|fieldset|iframe|hr|legend';
1774 # Tags treated as block tags only if the opening tag is alone on it's line:
1775 var $context_block_tags_re = 'script|noscript|math|ins|del';
1777 # Tags where markdown="1" default to span mode:
1778 var $contain_span_tags_re = 'p|h[1-6]|li|dd|dt|td|th|legend|address';
1780 # Tags which must not have their contents modified, no matter where
1782 var $clean_tags_re = 'script|math';
1784 # Tags that do not need to be closed.
1785 var $auto_close_tags_re = 'hr|img';
1788 function hashHTMLBlocks($text) {
1790 # Hashify HTML Blocks and "clean tags".
1792 # We only want to do this for block-level HTML tags, such as headers,
1793 # lists, and tables. That's because we still want to wrap <p>s around
1794 # "paragraphs" that are wrapped in non-block-level tags, such as anchors,
1795 # phrase emphasis, and spans. The list of tags we're looking for is
1798 # This works by calling _HashHTMLBlocks_InMarkdown, which then calls
1799 # _HashHTMLBlocks_InHTML when it encounter block tags. When the markdown="1"
1800 # attribute is found whitin a tag, _HashHTMLBlocks_InHTML calls back
1801 # _HashHTMLBlocks_InMarkdown to handle the Markdown syntax within the tag.
1802 # These two functions are calling each other. It's recursive!
1805 # Call the HTML-in-Markdown hasher.
1807 list($text, ) = $this->_hashHTMLBlocks_inMarkdown($text);
1811 function _hashHTMLBlocks_inMarkdown($text, $indent = 0,
1812 $enclosing_tag_re = '', $span = false)
1815 # Parse markdown text, calling _HashHTMLBlocks_InHTML for block tags.
1817 # * $indent is the number of space to be ignored when checking for code
1818 # blocks. This is important because if we don't take the indent into
1819 # account, something like this (which looks right) won't work as expected:
1822 # <div markdown="1">
1823 # Hello World. <-- Is this a Markdown code block or text?
1824 # </div> <-- Is this a Markdown code block or a real tag?
1827 # If you don't like this, just don't indent the tag on which
1828 # you apply the markdown="1" attribute.
1830 # * If $enclosing_tag_re is not empty, stops at the first unmatched closing
1831 # tag with that name. Nested tags supported.
1833 # * If $span is true, text inside must treated as span. So any double
1834 # newline will be replaced by a single newline so that it does not create
1837 # Returns an array of that form: ( processed text , remaining text )
1839 if ($text === '') return array('', '');
1841 # Regex to check for the presense of newlines around a block tag.
1842 $newline_before_re = '/(?:^\n?|\n\n)*$/';
1845 ^ # Start of text following the tag.
1846 (?>[ ]*<!--.*?-->)? # Optional comment.
1847 [ ]*\n # Must be followed by newline.
1850 # Regex to match any tag.
1853 ( # $2: Capture hole tag.
1854 </? # Any opening or closing tag.
1856 '.$this->block_tags_re.' |
1857 '.$this->context_block_tags_re.' |
1858 '.$this->clean_tags_re.' |
1859 (?!\s)'.$enclosing_tag_re.'
1862 (?=[\s"\'/a-zA-Z0-9]) # Allowed characters after tag name.
1864 ".*?" | # Double quotes (can contain `>`)
1865 \'.*?\' | # Single quotes (can contain `>`)
1866 .+? # Anything but quotes and `>`.
1871 <!-- .*? --> # HTML Comment
1873 <\?.*?\?> | <%.*?%> # Processing instruction
1875 <!\[CDATA\[.*?\]\]> # CData Block
1879 '. ( !$span ? ' # If not in span.
1881 # Indented code block
1882 (?> ^[ ]*\n? | \n[ ]*\n )
1883 [ ]{'.($indent+4).'}[^\n]* \n
1885 (?: [ ]{'.($indent+4).'}[^\n]* | [ ]* ) \n
1888 # Fenced code block marker
1890 [ ]{'.($indent).'}~~~+[ ]*\n
1891 ' : '' ). ' # End (if not is span).
1896 $depth = 0; # Current depth inside the tag tree.
1897 $parsed = ""; # Parsed text that will be returned.
1900 # Loop through every tag until we find the closing tag of the parent
1901 # or loop until reaching the end of text if no parent tag specified.
1905 # Split the text using the first $tag_match pattern found.
1906 # Text before pattern will be first in the array, text after
1907 # pattern will be at the end, and between will be any catches made
1910 $parts = preg_split($block_tag_re, $text, 2,
1911 PREG_SPLIT_DELIM_CAPTURE);
1913 # If in Markdown span mode, add a empty-string span-level hash
1914 # after each newline to prevent triggering any block element.
1916 $void = $this->hashPart("", ':');
1917 $newline = "$void\n";
1918 $parts[0] = $void . str_replace("\n", $newline, $parts[0]) . $void;
1921 $parsed .= $parts[0]; # Text before current tag.
1923 # If end of $text has been reached. Stop loop.
1924 if (count($parts) < 3) {
1929 $tag = $parts[1]; # Tag to handle.
1930 $text = $parts[2]; # Remaining text after current tag.
1931 $tag_re = preg_quote($tag); # For use in a regular expression.
1934 # Check for: Code span marker
1936 if ($tag{0} == "`") {
1937 # Find corresponding end marker.
1938 $tag_re = preg_quote($tag);
1939 if (preg_match('{^(?>.+?|\n(?!\n))*?(?<!`)'.$tag_re.'(?!`)}',
1942 # End marker found: pass text unchanged until marker.
1943 $parsed .= $tag . $matches[0];
1944 $text = substr($text, strlen($matches[0]));
1947 # Unmatched marker: just skip it.
1952 # Check for: Indented code block or fenced code block marker.
1954 else if ($tag{0} == "\n" || $tag{0} == "~") {
1955 if ($tag{1} == "\n" || $tag{1} == " ") {
1956 # Indented code block: pass it unchanged, will be handled
1961 # Fenced code block marker: find matching end marker.
1962 $tag_re = preg_quote(trim($tag));
1963 if (preg_match('{^(?>.*\n)+?'.$tag_re.' *\n}', $text,
1966 # End marker found: pass text unchanged until marker.
1967 $parsed .= $tag . $matches[0];
1968 $text = substr($text, strlen($matches[0]));
1971 # No end marker: just skip it.
1977 # Check for: Opening Block level tag or
1978 # Opening Context Block tag (like ins and del)
1979 # used as a block tag (tag is alone on it's line).
1981 else if (preg_match('{^<(?:'.$this->block_tags_re.')\b}', $tag) ||
1982 ( preg_match('{^<(?:'.$this->context_block_tags_re.')\b}', $tag) &&
1983 preg_match($newline_before_re, $parsed) &&
1984 preg_match($newline_after_re, $text) )
1987 # Need to parse tag and following text using the HTML parser.
1988 list($block_text, $text) =
1989 $this->_hashHTMLBlocks_inHTML($tag . $text, "hashBlock", true);
1991 # Make sure it stays outside of any paragraph by adding newlines.
1992 $parsed .= "\n\n$block_text\n\n";
1995 # Check for: Clean tag (like script, math)
1996 # HTML Comments, processing instructions.
1998 else if (preg_match('{^<(?:'.$this->clean_tags_re.')\b}', $tag) ||
1999 $tag{1} == '!' || $tag{1} == '?')
2001 # Need to parse tag and following text using the HTML parser.
2002 # (don't check for markdown attribute)
2003 list($block_text, $text) =
2004 $this->_hashHTMLBlocks_inHTML($tag . $text, "hashClean", false);
2006 $parsed .= $block_text;
2009 # Check for: Tag with same name as enclosing tag.
2011 else if ($enclosing_tag_re !== '' &&
2012 # Same name as enclosing tag.
2013 preg_match('{^</?(?:'.$enclosing_tag_re.')\b}', $tag))
2016 # Increase/decrease nested tag count.
2018 if ($tag{1} == '/') $depth--;
2019 else if ($tag{strlen($tag)-2} != '/') $depth++;
2023 # Going out of parent element. Clean up and break so we
2024 # return to the calling function.
2026 $text = $tag . $text;
2035 } while ($depth >= 0);
2037 return array($parsed, $text);
2039 function _hashHTMLBlocks_inHTML($text, $hash_method, $md_attr) {
2041 # Parse HTML, calling _HashHTMLBlocks_InMarkdown for block tags.
2043 # * Calls $hash_method to convert any blocks.
2044 # * Stops when the first opening tag closes.
2045 # * $md_attr indicate if the use of the `markdown="1"` attribute is allowed.
2046 # (it is not inside clean tags)
2048 # Returns an array of that form: ( processed text , remaining text )
2050 if ($text === '') return array('', '');
2052 # Regex to match `markdown` attribute inside of a tag.
2053 $markdown_attr_re = '
2055 \s* # Eat whitespace before the `markdown` attribute
2059 (["\']) # $1: quote delimiter
2060 (.*?) # $2: attribute value
2061 \1 # matching delimiter
2063 ([^\s>]*) # $3: unquoted attribute value
2065 () # $4: make $3 always defined (avoid warnings)
2068 # Regex to match any tag.
2070 ( # $2: Capture hole tag.
2071 </? # Any opening or closing tag.
2074 (?=[\s"\'/a-zA-Z0-9]) # Allowed characters after tag name.
2076 ".*?" | # Double quotes (can contain `>`)
2077 \'.*?\' | # Single quotes (can contain `>`)
2078 .+? # Anything but quotes and `>`.
2083 <!-- .*? --> # HTML Comment
2085 <\?.*?\?> | <%.*?%> # Processing instruction
2087 <!\[CDATA\[.*?\]\]> # CData Block
2091 $original_text = $text; # Save original text in case of faliure.
2093 $depth = 0; # Current depth inside the tag tree.
2094 $block_text = ""; # Temporary text holder for current text.
2095 $parsed = ""; # Parsed text that will be returned.
2098 # Get the name of the starting tag.
2099 # (This pattern makes $base_tag_name_re safe without quoting.)
2101 if (preg_match('/^<([\w:$]*)\b/', $text, $matches))
2102 $base_tag_name_re = $matches[1];
2105 # Loop through every tag until we find the corresponding closing tag.
2109 # Split the text using the first $tag_match pattern found.
2110 # Text before pattern will be first in the array, text after
2111 # pattern will be at the end, and between will be any catches made
2114 $parts = preg_split($tag_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE);
2116 if (count($parts) < 3) {
2118 # End of $text reached with unbalenced tag(s).
2119 # In that case, we return original text unchanged and pass the
2120 # first character as filtered to prevent an infinite loop in the
2123 return array($original_text{0}, substr($original_text, 1));
2126 $block_text .= $parts[0]; # Text before current tag.
2127 $tag = $parts[1]; # Tag to handle.
2128 $text = $parts[2]; # Remaining text after current tag.
2131 # Check for: Auto-close tag (like <hr/>)
2132 # Comments and Processing Instructions.
2134 if (preg_match('{^</?(?:'.$this->auto_close_tags_re.')\b}', $tag) ||
2135 $tag{1} == '!' || $tag{1} == '?')
2137 # Just add the tag to the block as if it was text.
2138 $block_text .= $tag;
2142 # Increase/decrease nested tag count. Only do so if
2143 # the tag's name match base tag's.
2145 if (preg_match('{^</?'.$base_tag_name_re.'\b}', $tag)) {
2146 if ($tag{1} == '/') $depth--;
2147 else if ($tag{strlen($tag)-2} != '/') $depth++;
2151 # Check for `markdown="1"` attribute and handle it.
2154 preg_match($markdown_attr_re, $tag, $attr_m) &&
2155 preg_match('/^1|block|span$/', $attr_m[2] . $attr_m[3]))
2157 # Remove `markdown` attribute from opening tag.
2158 $tag = preg_replace($markdown_attr_re, '', $tag);
2160 # Check if text inside this tag must be parsed in span mode.
2161 $this->mode = $attr_m[2] . $attr_m[3];
2162 $span_mode = $this->mode == 'span' || $this->mode != 'block' &&
2163 preg_match('{^<(?:'.$this->contain_span_tags_re.')\b}', $tag);
2165 # Calculate indent before tag.
2166 if (preg_match('/(?:^|\n)( *?)(?! ).*?$/', $block_text, $matches)) {
2167 $strlen = $this->utf8_strlen;
2168 $indent = $strlen($matches[1], 'UTF-8');
2173 # End preceding block with this tag.
2174 $block_text .= $tag;
2175 $parsed .= $this->$hash_method($block_text);
2177 # Get enclosing tag name for the ParseMarkdown function.
2178 # (This pattern makes $tag_name_re safe without quoting.)
2179 preg_match('/^<([\w:$]*)\b/', $tag, $matches);
2180 $tag_name_re = $matches[1];
2182 # Parse the content using the HTML-in-Markdown parser.
2183 list ($block_text, $text)
2184 = $this->_hashHTMLBlocks_inMarkdown($text, $indent,
2185 $tag_name_re, $span_mode);
2187 # Outdent markdown text.
2189 $block_text = preg_replace("/^[ ]{1,$indent}/m", "",
2193 # Append tag content to parsed text.
2194 if (!$span_mode) $parsed .= "\n\n$block_text\n\n";
2195 else $parsed .= "$block_text";
2197 # Start over a new block.
2200 else $block_text .= $tag;
2203 } while ($depth > 0);
2206 # Hash last block text that wasn't processed inside the loop.
2208 $parsed .= $this->$hash_method($block_text);
2210 return array($parsed, $text);
2214 function hashClean($text) {
2216 # Called whenever a tag must be hashed when a function insert a "clean" tag
2217 # in $text, it pass through this function and is automaticaly escaped,
2218 # blocking invalid nested overlap.
2220 return $this->hashPart($text, 'C');
2223 function _doAnchors_inline_callback($matches) {
2224 // $whole_match = $matches[1];
2225 $link_text = $this->runSpanGamut($matches[2]);
2226 $url = $matches[3] == '' ? $matches[4] : $matches[3];
2227 $title =& $matches[7];
2229 $url = $this->encodeAttribute($url);
2231 $result = "<a href=\"$url\"";
2232 if (isset($title)) {
2233 $title = $this->encodeAttribute($title);
2234 $result .= " title=\"$title\"";
2237 if ($this->el_enable && preg_match('/^https?\:\/\//', $url) && !preg_match('/^https?\:\/\/'.$this->el_local_domain.'/', $url)) {
2238 if ($this->el_new_window) {
2239 $result .= ' target="_blank"';
2242 if ($this->el_css_class) {
2243 $result .= ' class="'.$this->el_css_class.'"';
2247 $link_text = $this->runSpanGamut($link_text);
2248 $result .= ">$link_text</a>";
2250 return $this->hashPart($result);
2253 function _doAnchors_reference_callback($matches) {
2254 $whole_match = $matches[1];
2255 $link_text = $matches[2];
2256 $link_id =& $matches[3];
2259 if ($link_id == "") {
2260 # for shortcut links like [this][] or [this].
2261 $link_id = $link_text;
2264 # lower-case and turn embedded newlines into spaces
2265 $link_id = strtolower($link_id);
2266 $link_id = preg_replace('{[ ]?\n}', ' ', $link_id);
2268 if (isset($this->urls[$link_id])) {
2269 $url = $this->urls[$link_id];
2270 $url = $this->encodeAttribute($url);
2272 $result = "<a href=\"$url\"";
2273 if ( isset( $this->titles[$link_id] ) ) {
2274 $title = $this->titles[$link_id];
2275 $title = $this->encodeAttribute($title);
2276 $result .= " title=\"$title\"";
2279 if ($this->el_enable && preg_match('/^https?\:\/\//', $url) && !preg_match('/^https?\:\/\/'.$this->el_local_domain.'/', $url)) {
2280 if ($this->el_new_window) {
2281 $result .= ' target="_blank"';
2284 if ($this->el_css_class) {
2285 $result .= ' class="'.$this->el_css_class.'"';
2289 $link_text = $this->runSpanGamut($link_text);
2290 $result .= ">$link_text</a>";
2291 $result = $this->hashPart($result);
2294 $result = $whole_match;
2299 function doHeaders($text) {
2301 # Redefined to add id attribute support.
2303 # Setext-style headers:
2304 # Header 1 {#header1}
2307 # Header 2 {#header2}
2310 $text = preg_replace_callback(
2312 (^.+?) # $1: Header text
2313 (?:[ ]+\{\#([-_:a-zA-Z0-9]+)\})? # $2: Id attribute
2314 [ ]*\n(=+|-+)[ ]*\n+ # $3: Header footer
2316 array(&$this, '_doHeaders_callback_setext'), $text);
2318 # atx-style headers:
2319 # # Header 1 {#header1}
2320 # ## Header 2 {#header2}
2321 # ## Header 2 with closing hashes ## {#header3}
2323 # ###### Header 6 {#header2}
2325 $text = preg_replace_callback('{
2326 ^(\#{1,6}) # $1 = string of #\'s
2328 (.+?) # $2 = Header text
2330 \#* # optional closing #\'s (not counted)
2331 (?:[ ]+\{\#([-_:a-zA-Z0-9]+)\})? # id attribute
2335 array(&$this, '_doHeaders_callback_atx'), $text);
2339 function _doHeaders_attr($attr) {
2340 if (empty($attr)) return "";
2341 return " id=\"$attr\"";
2343 function _doHeaders_callback_setext($matches) {
2344 if ($matches[3] == '-' && preg_match('{^- }', $matches[1]))
2346 $level = $matches[3]{0} == '=' ? 1 : 2;
2347 $attr = $this->_doHeaders_attr($id =& $matches[2]);
2348 $body = $this->runSpanGamut($matches[1]);
2349 $body = $this->_doHeaders_selflink($id, $body);
2351 $block = "<h$level$attr>$body</h$level>";
2352 return "\n" . $this->hashBlock($block) . "\n\n";
2354 function _doHeaders_callback_atx($matches) {
2355 $level = strlen($matches[1]);
2356 $attr = $this->_doHeaders_attr($id =& $matches[3]);
2357 $body = $this->runSpanGamut($matches[2]);
2358 $body = $this->_doHeaders_selflink($id, $body);
2360 $block = "<h$level$attr>$body</h$level>";
2361 return "\n" . $this->hashBlock($block) . "\n\n";
2363 function _doHeaders_selflink($id, $body) {
2365 $link = '<a href="#'.$id.'"';
2367 if ($this->ha_class) {
2368 $link .= ' class="'.$this->ha_class.'"';
2371 $link .= '>'.$this->ha_text.'</a>';
2380 function doTables($text) {
2384 $less_than_tab = $this->tab_width - 1;
2386 # Find tables with leading pipe.
2388 # | Header 1 | Header 2
2389 # | -------- | --------
2393 $text = preg_replace_callback('
2396 [ ]{0,'.$less_than_tab.'} # Allowed whitespace.
2397 [|] # Optional leading pipe (present)
2398 (.+) \n # $1: Header row (at least one pipe)
2400 [ ]{0,'.$less_than_tab.'} # Allowed whitespace.
2401 [|] ([ ]*[-:]+[-| :]*) \n # $2: Header underline
2405 [ ]* # Allowed whitespace.
2406 [|] .* \n # Row content.
2409 (?=\n|\Z) # Stop at final double newline.
2411 array(&$this, '_doTable_leadingPipe_callback'), $text);
2414 # Find tables without leading pipe.
2416 # Header 1 | Header 2
2417 # -------- | --------
2421 $text = preg_replace_callback('
2424 [ ]{0,'.$less_than_tab.'} # Allowed whitespace.
2425 (\S.*[|].*) \n # $1: Header row (at least one pipe)
2427 [ ]{0,'.$less_than_tab.'} # Allowed whitespace.
2428 ([-:]+[ ]*[|][-| :]*) \n # $2: Header underline
2432 .* [|] .* \n # Row content
2435 (?=\n|\Z) # Stop at final double newline.
2437 array(&$this, '_DoTable_callback'), $text);
2441 function _doTable_leadingPipe_callback($matches) {
2442 $head = $matches[1];
2443 $underline = $matches[2];
2444 $content = $matches[3];
2446 # Remove leading pipe for each row.
2447 $content = preg_replace('/^ *[|]/m', '', $content);
2449 return $this->_doTable_callback(array($matches[0], $head, $underline, $content));
2451 function _doTable_callback($matches) {
2452 $head = $matches[1];
2453 $underline = $matches[2];
2454 $content = $matches[3];
2456 # Remove any tailing pipes for each line.
2457 $head = preg_replace('/[|] *$/m', '', $head);
2458 $underline = preg_replace('/[|] *$/m', '', $underline);
2459 $content = preg_replace('/[|] *$/m', '', $content);
2461 # Reading alignement from header underline.
2462 $separators = preg_split('/ *[|] */', $underline);
2463 foreach ($separators as $n => $s) {
2464 if (preg_match('/^ *-+: *$/', $s)) $attr[$n] = ' align="right"';
2465 else if (preg_match('/^ *:-+: *$/', $s))$attr[$n] = ' align="center"';
2466 else if (preg_match('/^ *:-+ *$/', $s)) $attr[$n] = ' align="left"';
2467 else $attr[$n] = '';
2470 # Parsing span elements, including code spans, character escapes,
2471 # and inline HTML tags, so that pipes inside those gets ignored.
2472 $head = $this->parseSpan($head);
2473 $headers = preg_split('/ *[|] */', $head);
2474 $col_count = count($headers);
2476 # Write column headers.
2477 $text = "<table>\n";
2478 $text .= "<thead>\n";
2480 foreach ($headers as $n => $header)
2481 $text .= " <th$attr[$n]>".$this->runSpanGamut(trim($header))."</th>\n";
2483 $text .= "</thead>\n";
2485 # Split content by row.
2486 $rows = explode("\n", trim($content, "\n"));
2488 $text .= "<tbody>\n";
2489 foreach ($rows as $row) {
2490 # Parsing span elements, including code spans, character escapes,
2491 # and inline HTML tags, so that pipes inside those gets ignored.
2492 $row = $this->parseSpan($row);
2494 # Split row by cell.
2495 $row_cells = preg_split('/ *[|] */', $row, $col_count);
2496 $row_cells = array_pad($row_cells, $col_count, '');
2499 foreach ($row_cells as $n => $cell)
2500 $text .= " <td$attr[$n]>".$this->runSpanGamut(trim($cell))."</td>\n";
2503 $text .= "</tbody>\n";
2504 $text .= "</table>";
2506 return $this->hashBlock($text) . "\n";
2510 function doDefLists($text) {
2512 # Form HTML definition lists.
2514 $less_than_tab = $this->tab_width - 1;
2516 # Re-usable pattern to match any entire dl list:
2517 $whole_list_re = '(?>
2520 [ ]{0,'.$less_than_tab.'}
2521 ((?>.*\S.*\n)+) # $3 = defined term
2523 [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition
2531 (?! # Negative lookahead for another term
2532 [ ]{0,'.$less_than_tab.'}
2533 (?: \S.*\n )+? # defined term
2535 [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition
2537 (?! # Negative lookahead for another definition
2538 [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition
2544 $text = preg_replace_callback('{
2548 array(&$this, '_doDefLists_callback'), $text);
2552 function _doDefLists_callback($matches) {
2553 # Re-usable patterns to match list item bullets and number markers:
2554 $list = $matches[1];
2556 # Turn double returns into triple returns, so that we can make a
2557 # paragraph for the last item in a list, if necessary:
2558 $result = trim($this->processDefListItems($list));
2559 $result = "<dl>\n" . $result . "\n</dl>";
2560 return $this->hashBlock($result) . "\n\n";
2564 function processDefListItems($list_str) {
2566 # Process the contents of a single definition list, splitting it
2567 # into individual term and definition list items.
2569 $less_than_tab = $this->tab_width - 1;
2571 # trim trailing blank lines:
2572 $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str);
2574 # Process definition terms.
2575 $list_str = preg_replace_callback('{
2576 (?>\A\n?|\n\n+) # leading line
2577 ( # definition terms = $1
2578 [ ]{0,'.$less_than_tab.'} # leading whitespace
2579 (?![:][ ]|[ ]) # negative lookahead for a definition
2580 # mark (colon) or more whitespace.
2581 (?> \S.* \n)+? # actual term (not whitespace).
2583 (?=\n?[ ]{0,3}:[ ]) # lookahead for following line feed
2584 # with a definition mark.
2586 array(&$this, '_processDefListItems_callback_dt'), $list_str);
2588 # Process actual definitions.
2589 $list_str = preg_replace_callback('{
2590 \n(\n+)? # leading line = $1
2591 ( # marker space = $2
2592 [ ]{0,'.$less_than_tab.'} # whitespace before colon
2593 [:][ ]+ # definition mark (colon)
2595 ((?s:.+?)) # definition text = $3
2596 (?= \n+ # stop at next definition mark,
2597 (?: # next term or end of text
2598 [ ]{0,'.$less_than_tab.'} [:][ ] |
2603 array(&$this, '_processDefListItems_callback_dd'), $list_str);
2607 function _processDefListItems_callback_dt($matches) {
2608 $anchor_regexp = '/\{\#([-_:a-zA-Z0-9]+)\}/';
2609 $terms = explode("\n", trim($matches[1]));
2613 foreach ($terms as $term) {
2615 if (preg_match($anchor_regexp, $term, $id) > 0) {
2616 $term = preg_replace($anchor_regexp, '', $term);
2617 $id = ' id="'.trim($id[1]).'"';
2620 if (count($id) === 0) {
2624 $term = $this->runSpanGamut(trim($term));
2625 $text .= "\n<dt$id>" . $term . "</dt>";
2627 return $text . "\n";
2629 function _processDefListItems_callback_dd($matches) {
2630 $leading_line = $matches[1];
2631 $marker_space = $matches[2];
2634 if ($leading_line || preg_match('/\n{2,}/', $def)) {
2635 # Replace marker with the appropriate whitespace indentation
2636 $def = str_repeat(' ', strlen($marker_space)) . $def;
2637 $def = $this->runBlockGamut($this->outdent($def . "\n\n"));
2638 $def = "\n". $def ."\n";
2642 $def = $this->runSpanGamut($this->outdent($def));
2645 return "\n<dd>" . $def . "</dd>\n";
2649 function doFencedCodeBlocks($text) {
2651 # Adding the fenced code block syntax to regular Markdown:
2657 $less_than_tab = $this->tab_width;
2659 $text = preg_replace_callback('{
2663 ~{3,} # Marker: three tilde or more.
2665 [ ]* \n # Whitespace and newline following marker.
2670 (?!\1 [ ]* \n) # Not a closing marker.
2678 array(&$this, '_doFencedCodeBlocks_callback'), $text);
2682 function _doFencedCodeBlocks_callback($matches) {
2683 $codeblock = $matches[2];
2684 $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES);
2685 $codeblock = preg_replace_callback('/^\n+/',
2686 array(&$this, '_doFencedCodeBlocks_newlines'), $codeblock);
2687 $codeblock = "<pre><code>$codeblock</code></pre>";
2688 return "\n\n".$this->hashBlock($codeblock)."\n\n";
2690 function _doFencedCodeBlocks_newlines($matches) {
2691 return str_repeat("<br$this->empty_element_suffix",
2692 strlen($matches[0]));
2697 # Redefining emphasis markers so that emphasis by underscore does not
2698 # work in the middle of a word.
2700 var $em_relist = array(
2701 '' => '(?:(?<!\*)\*(?!\*)|(?<![a-zA-Z0-9_])_(?!_))(?=\S)(?![.,:;]\s)',
2702 '*' => '(?<=\S)(?<!\*)\*(?!\*)',
2703 '_' => '(?<=\S)(?<!_)_(?![a-zA-Z0-9_])',
2705 var $strong_relist = array(
2706 '' => '(?:(?<!\*)\*\*(?!\*)|(?<![a-zA-Z0-9_])__(?!_))(?=\S)(?![.,:;]\s)',
2707 '**' => '(?<=\S)(?<!\*)\*\*(?!\*)',
2708 '__' => '(?<=\S)(?<!_)__(?![a-zA-Z0-9_])',
2710 var $em_strong_relist = array(
2711 '' => '(?:(?<!\*)\*\*\*(?!\*)|(?<![a-zA-Z0-9_])___(?!_))(?=\S)(?![.,:;]\s)',
2712 '***' => '(?<=\S)(?<!\*)\*\*\*(?!\*)',
2713 '___' => '(?<=\S)(?<!_)___(?![a-zA-Z0-9_])',
2717 function formParagraphs($text) {
2720 # $text - string to process with html <p> tags
2722 # Strip leading and trailing lines:
2723 $text = preg_replace('/\A\n+|\n+\z/', '', $text);
2725 $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY);
2728 # Wrap <p> tags and unhashify HTML blocks
2730 foreach ($grafs as $key => $value) {
2731 $value = trim($this->runSpanGamut($value));
2733 # Check if this should be enclosed in a paragraph.
2734 # Clean tag hashes & block tag hashes are left alone.
2735 $is_p = !preg_match('/^B\x1A[0-9]+B|^C\x1A[0-9]+C$/', $value);
2738 $value = "<p>$value</p>";
2740 $grafs[$key] = $value;
2743 # Join grafs in one text, then unhash HTML tags.
2744 $text = implode("\n\n", $grafs);
2746 # Finish by removing any tag hashes still present in $text.
2747 $text = $this->unhash($text);
2755 function stripFootnotes($text) {
2757 # Strips link definitions from text, stores the URLs and titles in
2760 $less_than_tab = $this->tab_width - 1;
2762 # Link defs are in the form: [^id]: url "optional title"
2763 $text = preg_replace_callback('{
2764 ^[ ]{0,'.$less_than_tab.'}\[\^(.+?)\][ ]?: # note_id = $1
2766 \n? # maybe *one* newline
2767 ( # text = $2 (no blank lines allowed)
2772 (?!\[\^.+?\]:\s)# negative lookahead for footnote marker.
2773 (?!\n+[ ]{0,3}\S)# ensure line is not blank and followed
2774 # by non-indented content
2778 array(&$this, '_stripFootnotes_callback'),
2782 function _stripFootnotes_callback($matches) {
2783 $note_id = $this->fn_id_prefix . $matches[1];
2784 $this->footnotes[$note_id] = $this->outdent($matches[2]);
2785 return ''; # String that will replace the block
2789 function doFootnotes($text) {
2791 # Replace footnote references in $text [^id] with a special text-token
2792 # which will be replaced by the actual footnote marker in appendFootnotes.
2794 if (!$this->in_anchor) {
2795 $text = preg_replace('{\[\^(.+?)\]}', "F\x1Afn:\\1\x1A:", $text);
2801 function appendFootnotes($text) {
2803 # Append footnote list to text.
2805 $text = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}',
2806 array(&$this, '_appendFootnotes_callback'), $text);
2808 if (!empty($this->footnotes_ordered)) {
2810 $text .= "<div class=\"footnotes\">\n";
2811 $text .= "<hr". MARKDOWN_EMPTY_ELEMENT_SUFFIX ."\n";
2812 $text .= "<ol>\n\n";
2814 $attr = " rev=\"footnote\"";
2815 if ($this->fn_backlink_class != "") {
2816 $class = $this->fn_backlink_class;
2817 $class = $this->encodeAttribute($class);
2818 $attr .= " class=\"$class\"";
2820 if ($this->fn_backlink_title != "") {
2821 $title = $this->fn_backlink_title;
2822 $title = $this->encodeAttribute($title);
2823 $attr .= " title=\"$title\"";
2827 while (!empty($this->footnotes_ordered)) {
2828 $footnote = reset($this->footnotes_ordered);
2829 $note_id = key($this->footnotes_ordered);
2830 unset($this->footnotes_ordered[$note_id]);
2832 $footnote .= "\n"; # Need to append newline before parsing.
2833 $footnote = $this->runBlockGamut("$footnote\n");
2834 $footnote = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}',
2835 array(&$this, '_appendFootnotes_callback'), $footnote);
2837 $attr = str_replace("%%", ++$num, $attr);
2838 $note_id = $this->encodeAttribute($note_id);
2840 # Add backlink to last paragraph; create new paragraph if needed.
2841 $backlink = "<a href=\"#fnref:$note_id\"$attr>↩</a>";
2842 if (preg_match('{</p>$}', $footnote)) {
2843 $footnote = substr($footnote, 0, -4) . " $backlink</p>";
2845 $footnote .= "\n\n<p>$backlink</p>";
2848 $text .= "<li id=\"fn:$note_id\">\n";
2849 $text .= $footnote . "\n";
2850 $text .= "</li>\n\n";
2858 function _appendFootnotes_callback($matches) {
2859 $node_id = $this->fn_id_prefix . $matches[1];
2861 # Create footnote marker only if it has a corresponding footnote *and*
2862 # the footnote hasn't been used by another marker.
2863 if (isset($this->footnotes[$node_id])) {
2864 # Transfert footnote content to the ordered list.
2865 $this->footnotes_ordered[$node_id] = $this->footnotes[$node_id];
2866 unset($this->footnotes[$node_id]);
2868 $num = $this->footnote_counter++;
2869 $attr = " rel=\"footnote\"";
2870 if ($this->fn_link_class != "") {
2871 $class = $this->fn_link_class;
2872 $class = $this->encodeAttribute($class);
2873 $attr .= " class=\"$class\"";
2875 if ($this->fn_link_title != "") {
2876 $title = $this->fn_link_title;
2877 $title = $this->encodeAttribute($title);
2878 $attr .= " title=\"$title\"";
2881 $attr = str_replace("%%", $num, $attr);
2882 $node_id = $this->encodeAttribute($node_id);
2885 "<sup id=\"fnref:$node_id\">".
2886 "<a href=\"#fn:$node_id\"$attr>$num</a>".
2890 return "[^".$matches[1]."]";
2894 ### Abbreviations ###
2896 function stripAbbreviations($text) {
2898 # Strips abbreviations from text, stores titles in hash references.
2900 $less_than_tab = $this->tab_width - 1;
2902 # Link defs are in the form: [id]*: url "optional title"
2903 $text = preg_replace_callback('{
2904 ^[ ]{0,'.$less_than_tab.'}\*\[(.+?)\][ ]?: # abbr_id = $1
2905 (.*) # text = $2 (no blank lines allowed)
2907 array(&$this, '_stripAbbreviations_callback'),
2911 function _stripAbbreviations_callback($matches) {
2912 $abbr_word = $matches[1];
2913 $abbr_desc = $matches[2];
2914 if ($this->abbr_word_re)
2915 $this->abbr_word_re .= '|';
2916 $this->abbr_word_re .= preg_quote($abbr_word);
2917 $this->abbr_desciptions[$abbr_word] = trim($abbr_desc);
2918 return ''; # String that will replace the block
2922 function doAbbreviations($text) {
2924 # Find defined abbreviations in text and wrap them in <abbr> elements.
2926 if ($this->abbr_word_re) {
2927 // cannot use the /x modifier because abbr_word_re may
2928 // contain significant spaces:
2929 $text = preg_replace_callback('{'.
2931 '(?:'.$this->abbr_word_re.')'.
2934 array(&$this, '_doAbbreviations_callback'), $text);
2938 function _doAbbreviations_callback($matches) {
2939 $abbr = $matches[0];
2940 if (isset($this->abbr_desciptions[$abbr])) {
2941 $desc = $this->abbr_desciptions[$abbr];
2943 return $this->hashPart("<abbr>$abbr</abbr>");
2945 $desc = $this->encodeAttribute($desc);
2946 return $this->hashPart("<abbr title=\"$desc\">$abbr</abbr>");
2964 This is a PHP port of the original Markdown formatter written in Perl
2965 by John Gruber. This special "Extra" version of PHP Markdown features
2966 further enhancements to the syntax for making additional constructs
2967 such as tables and definition list.
2969 Markdown is a text-to-HTML filter; it translates an easy-to-read /
2970 easy-to-write structured text format into HTML. Markdown's text format
2971 is most similar to that of plain text email, and supports features such
2972 as headers, *emphasis*, code blocks, blockquotes, and links.
2974 Markdown's syntax is designed not as a generic markup language, but
2975 specifically to serve as a front-end to (X)HTML. You can use span-level
2976 HTML tags anywhere in a Markdown document, and you can use block level
2977 HTML tags (like <div> and <table> as well).
2979 For more information about Markdown's syntax, see:
2981 <http://daringfireball.net/projects/markdown/>
2987 To file bug reports please send email to:
2989 <michel.fortin@michelf.com>
2991 Please include with your report: (1) the example input; (2) the output you
2992 expected; (3) the output Markdown actually produced.
2998 See the readme file for detailed release notes for this version.
3001 Copyright and License
3002 ---------------------
3004 PHP Markdown & Extra
3005 Copyright (c) 2004-2008 Michel Fortin
3006 <http://www.michelf.com/>
3007 All rights reserved.
3010 Copyright (c) 2003-2006 John Gruber
3011 <http://daringfireball.net/>
3012 All rights reserved.
3014 Redistribution and use in source and binary forms, with or without
3015 modification, are permitted provided that the following conditions are
3018 * Redistributions of source code must retain the above copyright notice,
3019 this list of conditions and the following disclaimer.
3021 * Redistributions in binary form must reproduce the above copyright
3022 notice, this list of conditions and the following disclaimer in the
3023 documentation and/or other materials provided with the distribution.
3025 * Neither the name "Markdown" nor the names of its contributors may
3026 be used to endorse or promote products derived from this software
3027 without specific prior written permission.
3029 This software is provided by the copyright holders and contributors "as
3030 is" and any express or implied warranties, including, but not limited
3031 to, the implied warranties of merchantability and fitness for a
3032 particular purpose are disclaimed. In no event shall the copyright owner
3033 or contributors be liable for any direct, indirect, incidental, special,
3034 exemplary, or consequential damages (including, but not limited to,
3035 procurement of substitute goods or services; loss of use, data, or
3036 profits; or business interruption) however caused and on any theory of
3037 liability, whether in contract, strict liability, or tort (including
3038 negligence or otherwise) arising in any way out of the use of this
3039 software, even if advised of the possibility of such damage.