]> git.mxchange.org Git - friendica.git/blob - library/markdown.php
Merge branch 'master' into newui
[friendica.git] / library / markdown.php
1 <?php
2 #
3 # Markdown Extra  -  A text-to-HTML conversion tool for web writers
4 #
5 # PHP Markdown & Extra
6 # Copyright (c) 2004-2008 Michel Fortin
7 # <http://www.michelf.com/projects/php-markdown/>
8 #
9 # Original Markdown
10 # Copyright (c) 2004-2006 John Gruber
11 # <http://daringfireball.net/projects/markdown/>
12 #
13
14
15 define( 'MARKDOWN_VERSION',  "1.0.1m" ); # Sat 21 Jun 2008
16 define( 'MARKDOWNEXTRA_VERSION',  "1.2.3" ); # Wed 31 Dec 2008
17
18
19 #
20 # Global default settings:
21 #
22
23 # Change to ">" for HTML output
24 @define( 'MARKDOWN_EMPTY_ELEMENT_SUFFIX',  " />");
25
26 # Define the width of a tab for code blocks.
27 @define( 'MARKDOWN_TAB_WIDTH',     4 );
28
29 # Optional title attribute for footnote links and backlinks.
30 @define( 'MARKDOWN_FN_LINK_TITLE',         "" );
31 @define( 'MARKDOWN_FN_BACKLINK_TITLE',     "" );
32
33 # Optional class attribute for footnote links and backlinks.
34 @define( 'MARKDOWN_FN_LINK_CLASS',         "" );
35 @define( 'MARKDOWN_FN_BACKLINK_CLASS',     "" );
36
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
42
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',           '&larr;' );   # The text to use as the link
47
48
49 #
50 # WordPress settings:
51 #
52
53 # Change to false to remove Markdown from posts and/or comments.
54 @define( 'MARKDOWN_WP_POSTS',      true );
55 @define( 'MARKDOWN_WP_COMMENTS',   true );
56
57
58
59 ### Standard Function Interface ###
60
61 @define( 'MARKDOWN_PARSER_CLASS',  'MarkdownExtra_Parser' );
62
63 function Markdown($text) {
64 #
65 # Initialize the parser and return the result of its transform method.
66 #
67         # Setup static parser variable.
68         static $parser;
69         if (!isset($parser)) {
70                 $parser_class = MARKDOWN_PARSER_CLASS;
71                 $parser = new $parser_class;
72         }
73
74         # Transform text using parser.
75         return $parser->transform($text);
76 }
77
78
79 ### WordPress Plugin Interface ###
80
81 /*
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>
85 Version: 1.2.2
86 Author: Michel Fortin
87 Author URI: http://www.michelf.com/
88 */
89
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/>
93
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');
108
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);
113         }
114
115         # Add a footnote id prefix to posts when inside a loop.
116         function mdwp_MarkdownPost($text) {
117                 static $parser;
118                 if (!$parser) {
119                         $parser_class = MARKDOWN_PARSER_CLASS;
120                         $parser = new $parser_class;
121                 }
122                 if (is_single() || is_page() || is_feed()) {
123                         $parser->fn_id_prefix = "";
124                 } else {
125                         $parser->fn_id_prefix = get_the_ID() . ".";
126                 }
127                 return $parser->transform($text);
128         }
129
130         # Comments
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);
144
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'));
151         }
152
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);
157                 }
158                 return $text;
159         }
160
161         function mdwp_strip_p($t) { return preg_replace('{</?p>}i', '', $t); }
162
163         function mdwp_hide_tags($text) {
164                 global $mdwp_hidden_tags, $mdwp_placeholders;
165                 return str_replace($mdwp_hidden_tags, $mdwp_placeholders, $text);
166         }
167         function mdwp_show_tags($text) {
168                 global $mdwp_hidden_tags, $mdwp_placeholders;
169                 return str_replace($mdwp_placeholders, $mdwp_hidden_tags, $text);
170         }
171 }
172
173
174 ### bBlog Plugin Info ###
175
176 function identify_modifier_markdown() {
177         return array(
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',
183                 'licence' => 'GPL',
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>',
186                 );
187 }
188
189
190 ### Smarty Modifier Interface ###
191
192 function smarty_modifier_markdown($text) {
193         return Markdown($text);
194 }
195
196
197 ### Textile Compatibility Mode ###
198
199 # Rename this file to "classTextile.php" and it can replace Textile everywhere.
200
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.
205         class Textile {
206                 function TextileThis($text, $lite='', $encode='') {
207                         if ($lite == '' && $encode == '')    $text = Markdown($text);
208                         if (function_exists('SmartyPants'))  $text = SmartyPants($text);
209                         return $text;
210                 }
211                 # Fake restricted version: restrictions are not supported for now.
212                 function TextileRestricted($text, $lite='', $noimage='') {
213                         return $this->TextileThis($text, $lite);
214                 }
215                 # Workaround to ensure compatibility with TextPattern 4.0.3.
216                 function blockLite($text) { return $text; }
217         }
218 }
219
220
221
222 #
223 # Markdown Parser Class
224 #
225
226 class Markdown_Parser {
227
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;
232
233         var $nested_url_parenthesis_depth = 4;
234         var $nested_url_parenthesis_re;
235
236         # Table of hash values for escaped characters:
237         var $escape_chars = '\`*_{}[]()>#+-.!';
238         var $escape_chars_re;
239
240         # Change to ">" for HTML output.
241         var $empty_element_suffix = MARKDOWN_EMPTY_ELEMENT_SUFFIX;
242         var $tab_width = MARKDOWN_TAB_WIDTH;
243
244         # Change to `true` to disallow markup or entities.
245         var $no_markup = false;
246         var $no_entities = false;
247
248         # Predefined urls and titles for reference links and images.
249         var $predef_urls = array();
250         var $predef_titles = array();
251
252
253         function Markdown_Parser() {
254         #
255         # Constructor function. Initialize appropriate member variables.
256         #
257                 $this->_initDetab();
258                 $this->prepareItalicsAndBold();
259
260                 $this->nested_brackets_re =
261                         str_repeat('(?>[^\[\]]+|\[', $this->nested_brackets_depth).
262                         str_repeat('\])*', $this->nested_brackets_depth);
263
264                 $this->nested_url_parenthesis_re =
265                         str_repeat('(?>[^()\s]+|\(', $this->nested_url_parenthesis_depth).
266                         str_repeat('(?>\)))*', $this->nested_url_parenthesis_depth);
267
268                 $this->escape_chars_re = '['.preg_quote($this->escape_chars).']';
269
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);
274         }
275
276
277         # Internal hashes used during transformation.
278         var $urls = array();
279         var $titles = array();
280         var $html_hashes = array();
281
282         # Status flag to avoid invalid nesting.
283         var $in_anchor = false;
284
285
286         function setup() {
287         #
288         # Called before the transformation process starts to setup parser
289         # states.
290         #
291                 # Clear global hashes.
292                 $this->urls = $this->predef_urls;
293                 $this->titles = $this->predef_titles;
294                 $this->html_hashes = array();
295
296                 $in_anchor = false;
297         }
298
299         function teardown() {
300         #
301         # Called after the transformation process to clear any variable
302         # which may be taking up memory unnecessarly.
303         #
304                 $this->urls = array();
305                 $this->titles = array();
306                 $this->html_hashes = array();
307         }
308
309
310         function transform($text) {
311         #
312         # Main function. Performs some preprocessing on the input text
313         # and pass it through the document gamut.
314         #
315                 $this->setup();
316
317                 # Remove UTF-8 BOM and marker character in input, if present.
318                 $text = preg_replace('{^\xEF\xBB\xBF|\x1A}', '', $text);
319
320                 # Standardize line endings:
321                 #   DOS to Unix and Mac to Unix
322                 $text = preg_replace('{\r\n?}', "\n", $text);
323
324                 # Make sure $text ends with a couple of newlines:
325                 $text .= "\n\n";
326
327                 # Convert all tabs to spaces.
328                 $text = $this->detab($text);
329
330                 # Turn block-level HTML blocks into hash entries
331                 $text = $this->hashHTMLBlocks($text);
332
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);
338
339                 # Run document gamut methods.
340                 foreach ($this->document_gamut as $method => $priority) {
341                         $text = $this->$method($text);
342                 }
343
344                 $this->teardown();
345
346                 return $text . "\n";
347         }
348
349         var $document_gamut = array(
350                 # Strip link definitions, store in hashes.
351                 "stripLinkDefinitions" => 20,
352
353                 "runBasicBlockGamut"   => 30,
354                 );
355
356
357         function stripLinkDefinitions($text) {
358         #
359         # Strips link definitions from text, stores the URLs and titles in
360         # hash references.
361         #
362                 $less_than_tab = $this->tab_width - 1;
363
364                 # Link defs are in the form: ^[id]: url "optional title"
365                 $text = preg_replace_callback('{
366                                                         ^[ ]{0,'.$less_than_tab.'}\[(.+)\][ ]?: # id = $1
367                                                           [ ]*
368                                                           \n?                           # maybe *one* newline
369                                                           [ ]*
370                                                         <?(\S+?)>?                      # url = $2
371                                                           [ ]*
372                                                           \n?                           # maybe one newline
373                                                           [ ]*
374                                                         (?:
375                                                                 (?<=\s)                 # lookbehind for whitespace
376                                                                 ["(]
377                                                                 (.*?)                   # title = $3
378                                                                 [")]
379                                                                 [ ]*
380                                                         )?      # title is optional
381                                                         (?:\n+|\Z)
382                         }xm',
383                         array(&$this, '_stripLinkDefinitions_callback'),
384                         $text);
385                 return $text;
386         }
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
392         }
393
394
395         function hashHTMLBlocks($text) {
396                 if ($this->no_markup)  return $text;
397
398                 $less_than_tab = $this->tab_width - 1;
399
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
405                 # hard-coded:
406                 #
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
410                 #    inline later.
411                 # *  List "b" is made of tags which are always block-level;
412                 #
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';
416
417                 # Regular expression for the content of a block tag.
418                 $nested_tags_level = 4;
419                 $attr = '
420                         (?>                             # optional tag attributes
421                           \s                    # starts with whitespace
422                           (?>
423                                 [^>"/]+         # text outside quotes
424                           |
425                                 /+(?!>)         # slash not followed by ">"
426                           |
427                                 "[^"]*"         # text inside double quotes (tolerate ">")
428                           |
429                                 \'[^\']*\'      # text inside single quotes (tolerate ">")
430                           )*
431                         )?
432                         ';
433                 $content =
434                         str_repeat('
435                                 (?>
436                                   [^<]+                 # content without tag
437                                 |
438                                   <\2                   # nested opening tag
439                                         '.$attr.'       # attributes
440                                         (?>
441                                           />
442                                         |
443                                           >', $nested_tags_level).      # end of opening tag
444                                           '.*?'.                                        # last level nested tag content
445                         str_repeat('
446                                           </\2\s*>      # closing nested tag
447                                         )
448                                   |
449                                         <(?!/\2\s*>     # other tags with a different name
450                                   )
451                                 )*',
452                                 $nested_tags_level);
453                 $content2 = str_replace('\2', '\3', $content);
454
455                 # First, look for nested blocks, e.g.:
456                 #       <div>
457                 #               <div>
458                 #               tags for inner block must be indented.
459                 #               </div>
460                 #       </div>
461                 #
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('{(?>
467                         (?>
468                                 (?<=\n\n)               # Starting after a blank line
469                                 |                               # or
470                                 \A\n?                   # the beginning of the doc
471                         )
472                         (                                               # save in $1
473
474                           # Match from `\n<tag>` to `</tag>\n`, handling nested tags
475                           # in between.
476
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
484
485                         | # Special version for tags of group a.
486
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
494
495                         | # Special case just for <hr />. It was easier to make a special
496                           # case than to make the other regex more complicated.
497
498                                                 [ ]{0,'.$less_than_tab.'}
499                                                 <(hr)                           # start tag = $2
500                                                 '.$attr.'                       # attributes
501                                                 /?>                                     # the matching end tag
502                                                 [ ]*
503                                                 (?=\n{2,}|\Z)           # followed by a blank line or end of document
504
505                         | # Special case for standalone HTML comments:
506
507                                         [ ]{0,'.$less_than_tab.'}
508                                         (?s:
509                                                 <!-- .*? -->
510                                         )
511                                         [ ]*
512                                         (?=\n{2,}|\Z)           # followed by a blank line or end of document
513
514                         | # PHP and ASP-style processor instructions (<? and <%)
515
516                                         [ ]{0,'.$less_than_tab.'}
517                                         (?s:
518                                                 <([?%])                 # $2
519                                                 .*?
520                                                 \2>
521                                         )
522                                         [ ]*
523                                         (?=\n{2,}|\Z)           # followed by a blank line or end of document
524
525                         )
526                         )}Sxmi',
527                         array(&$this, '_hashHTMLBlocks_callback'),
528                         $text);
529
530                 return $text;
531         }
532         function _hashHTMLBlocks_callback($matches) {
533                 $text = $matches[1];
534                 $key  = $this->hashBlock($text);
535                 return "\n\n$key\n\n";
536         }
537
538
539         function hashPart($text, $boundary = 'X') {
540         #
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.
544         #
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.
549         #
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);
553
554                 # Then hash the block.
555                 static $i = 0;
556                 $key = "$boundary\x1A" . ++$i . $boundary;
557                 $this->html_hashes[$key] = $text;
558                 return $key; # String that will replace the tag.
559         }
560
561
562         function hashBlock($text) {
563         #
564         # Shortcut function for hashPart with block-level boundaries.
565         #
566                 return $this->hashPart($text, 'B');
567         }
568
569
570         var $block_gamut = array(
571         #
572         # These are all the transformations that form block-level
573         # tags like paragraphs, headers, and list items.
574         #
575                 "doHeaders"         => 10,
576                 "doHorizontalRules" => 20,
577
578                 "doLists"           => 40,
579                 "doCodeBlocks"      => 50,
580                 "doBlockQuotes"     => 60,
581                 );
582
583         function runBlockGamut($text) {
584         #
585         # Run block gamut tranformations.
586         #
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);
593
594                 return $this->runBasicBlockGamut($text);
595         }
596
597         function runBasicBlockGamut($text) {
598         #
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.
602         #
603                 foreach ($this->block_gamut as $method => $priority) {
604                         $text = $this->$method($text);
605                 }
606
607                 # Finally form paragraph and restore hashed blocks.
608                 $text = $this->formParagraphs($text);
609
610                 return $text;
611         }
612
613
614         function doHorizontalRules($text) {
615                 # Do Horizontal Rules:
616                 return preg_replace(
617                         '{
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
625                                 $                       # End of line.
626                         }mx',
627                         "\n".$this->hashBlock("<hr$this->empty_element_suffix")."\n",
628                         $text);
629         }
630
631
632         var $span_gamut = array(
633         #
634         # These are all the transformations that occur *within* block-level
635         # tags like paragraphs, headers, and list items.
636         #
637                 # Process character escapes, code spans, and inline HTML
638                 # in one shot.
639                 "parseSpan"           => -30,
640
641                 # Process anchor and image tags. Images must come first,
642                 # because ![foo][f] looks like an anchor.
643                 "doImages"            =>  10,
644                 "doAnchors"           =>  20,
645
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>).
649                 "doAutoLinks"         =>  30,
650                 "encodeAmpsAndAngles" =>  40,
651
652                 "doItalicsAndBold"    =>  50,
653                 "doHardBreaks"        =>  60,
654                 );
655
656         function runSpanGamut($text) {
657         #
658         # Run span gamut tranformations.
659         #
660                 foreach ($this->span_gamut as $method => $priority) {
661                         $text = $this->$method($text);
662                 }
663
664                 return $text;
665         }
666
667
668         function doHardBreaks($text) {
669                 # Do hard breaks:
670                 return preg_replace_callback('/ {2,}\n/',
671                         array(&$this, '_doHardBreaks_callback'), $text);
672         }
673         function _doHardBreaks_callback($matches) {
674                 return $this->hashPart("<br$this->empty_element_suffix\n");
675         }
676
677
678         function doAnchors($text) {
679         #
680         # Turn Markdown link shortcuts into XHTML <a> tags.
681         #
682                 if ($this->in_anchor) return $text;
683                 $this->in_anchor = true;
684
685                 #
686                 # First, handle reference-style links: [link text] [id]
687                 #
688                 $text = preg_replace_callback('{
689                         (                                       # wrap whole match in $1
690                           \[
691                                 ('.$this->nested_brackets_re.') # link text = $2
692                           \]
693
694                           [ ]?                          # one optional space
695                           (?:\n[ ]*)?           # one optional newline followed by spaces
696
697                           \[
698                                 (.*?)           # id = $3
699                           \]
700                         )
701                         }xs',
702                         array(&$this, '_doAnchors_reference_callback'), $text);
703
704                 #
705                 # Next, inline-style links: [link text](url "optional title")
706                 #
707                 $text = preg_replace_callback('{
708                         (                               # wrap whole match in $1
709                           \[
710                                 ('.$this->nested_brackets_re.') # link text = $2
711                           \]
712                           \(                    # literal paren
713                                 [ ]*
714                                 (?:
715                                         <(\S*)> # href = $3
716                                 |
717                                         ('.$this->nested_url_parenthesis_re.')  # href = $4
718                                 )
719                                 [ ]*
720                                 (                       # $5
721                                   ([\'"])       # quote char = $6
722                                   (.*?)         # Title = $7
723                                   \6            # matching quote
724                                   [ ]*  # ignore any spaces/tabs between closing quote and )
725                                 )?                      # title is optional
726                           \)
727                         )
728                         }xs',
729                         array(&$this, '_DoAnchors_inline_callback'), $text);
730
731                 #
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)
735                 #
736 //              $text = preg_replace_callback('{
737 //                      (                                       # wrap whole match in $1
738 //                        \[
739 //                              ([^\[\]]+)              # link text = $2; can\'t contain [ or ]
740 //                        \]
741 //                      )
742 //                      }xs',
743 //                      array(&$this, '_doAnchors_reference_callback'), $text);
744
745                 $this->in_anchor = false;
746                 return $text;
747         }
748         function _doAnchors_reference_callback($matches) {
749                 $whole_match =  $matches[1];
750                 $link_text   =  $matches[2];
751                 $link_id     =& $matches[3];
752
753                 if ($link_id == "") {
754                         # for shortcut links like [this][] or [this].
755                         $link_id = $link_text;
756                 }
757
758                 # lower-case and turn embedded newlines into spaces
759                 $link_id = strtolower($link_id);
760                 $link_id = preg_replace('{[ ]?\n}', ' ', $link_id);
761
762                 if (isset($this->urls[$link_id])) {
763                         $url = $this->urls[$link_id];
764                         $url = $this->encodeAttribute($url);
765
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\"";
771                         }
772
773                         $link_text = $this->runSpanGamut($link_text);
774                         $result .= ">$link_text</a>";
775                         $result = $this->hashPart($result);
776                 }
777                 else {
778                         $result = $whole_match;
779                 }
780                 return $result;
781         }
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];
787
788                 $url = $this->encodeAttribute($url);
789
790                 $result = "<a href=\"$url\"";
791                 if (isset($title)) {
792                         $title = $this->encodeAttribute($title);
793                         $result .=  " title=\"$title\"";
794                 }
795
796                 $link_text = $this->runSpanGamut($link_text);
797                 $result .= ">$link_text</a>";
798
799                 return $this->hashPart($result);
800         }
801
802
803         function doImages($text) {
804         #
805         # Turn Markdown image shortcuts into <img> tags.
806         #
807                 #
808                 # First, handle reference-style labeled images: ![alt text][id]
809                 #
810                 $text = preg_replace_callback('{
811                         (                               # wrap whole match in $1
812                           !\[
813                                 ('.$this->nested_brackets_re.')         # alt text = $2
814                           \]
815
816                           [ ]?                          # one optional space
817                           (?:\n[ ]*)?           # one optional newline followed by spaces
818
819                           \[
820                                 (.*?)           # id = $3
821                           \]
822
823                         )
824                         }xs',
825                         array(&$this, '_doImages_reference_callback'), $text);
826
827                 #
828                 # Next, handle inline images:  ![alt text](url "optional title")
829                 # Don't forget: encode * and _
830                 #
831                 $text = preg_replace_callback('{
832                         (                               # wrap whole match in $1
833                           !\[
834                                 ('.$this->nested_brackets_re.')         # alt text = $2
835                           \]
836                           \s?                   # One optional whitespace character
837                           \(                    # literal paren
838                                 [ ]*
839                                 (?:
840                                         <(\S*)> # src url = $3
841                                 |
842                                         ('.$this->nested_url_parenthesis_re.')  # src url = $4
843                                 )
844                                 [ ]*
845                                 (                       # $5
846                                   ([\'"])       # quote char = $6
847                                   (.*?)         # title = $7
848                                   \6            # matching quote
849                                   [ ]*
850                                 )?                      # title is optional
851                           \)
852                         )
853                         }xs',
854                         array(&$this, '_doImages_inline_callback'), $text);
855
856                 return $text;
857         }
858         function _doImages_reference_callback($matches) {
859                 $whole_match = $matches[1];
860                 $alt_text    = $matches[2];
861                 $link_id     = strtolower($matches[3]);
862
863                 if ($link_id == "") {
864                         $link_id = strtolower($alt_text); # for shortcut links like ![this][].
865                 }
866
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\"";
875                         }
876                         $result .= $this->empty_element_suffix;
877                         $result = $this->hashPart($result);
878                 }
879                 else {
880                         # If there's no such link ID, leave intact:
881                         $result = $whole_match;
882                 }
883
884                 return $result;
885         }
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];
891
892                 $alt_text = $this->encodeAttribute($alt_text);
893                 $url = $this->encodeAttribute($url);
894                 $result = "<img src=\"$url\" alt=\"$alt_text\"";
895                 if (isset($title)) {
896                         $title = $this->encodeAttribute($title);
897                         $result .=  " title=\"$title\""; # $title already quoted
898                 }
899                 $result .= $this->empty_element_suffix;
900
901                 return $this->hashPart($result);
902         }
903
904
905         function doHeaders($text) {
906                 # Setext-style headers:
907                 #         Header 1
908                 #         ========
909                 #
910                 #         Header 2
911                 #         --------
912                 #
913                 $text = preg_replace_callback('{ ^(.+?)[ ]*\n(=+|-+)[ ]*\n+ }mx',
914                         array(&$this, '_doHeaders_callback_setext'), $text);
915
916                 # atx-style headers:
917                 #       # Header 1
918                 #       ## Header 2
919                 #       ## Header 2 with closing hashes ##
920                 #       ...
921                 #       ###### Header 6
922                 #
923                 $text = preg_replace_callback('{
924                                 ^(\#{1,6})      # $1 = string of #\'s
925                                 [ ]*
926                                 (.+?)           # $2 = Header text
927                                 [ ]*
928                                 \#*                     # optional closing #\'s (not counted)
929                                 \n+
930                         }xm',
931                         array(&$this, '_doHeaders_callback_atx'), $text);
932
933                 return $text;
934         }
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]))
938                         return $matches[0];
939
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";
943         }
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";
948         }
949
950
951         function doLists($text) {
952         #
953         # Form HTML ordered (numbered) and unordered (bulleted) lists.
954         #
955                 $less_than_tab = $this->tab_width - 1;
956
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)";
961
962                 $markers_relist = array($marker_ul_re, $marker_ol_re);
963
964                 foreach ($markers_relist as $marker_re) {
965                         # Re-usable pattern to match any entirel ul or ol list:
966                         $whole_list_re = '
967                                 (                                                               # $1 = whole list
968                                   (                                                             # $2
969                                         [ ]{0,'.$less_than_tab.'}
970                                         ('.$marker_re.')                        # $3 = first list item marker
971                                         [ ]+
972                                   )
973                                   (?s:.+?)
974                                   (                                                             # $4
975                                           \z
976                                         |
977                                           \n{2,}
978                                           (?=\S)
979                                           (?!                                           # Negative lookahead for another list item marker
980                                                 [ ]*
981                                                 '.$marker_re.'[ ]+
982                                           )
983                                   )
984                                 )
985                         '; // mx
986
987                         # We use a different prefix before nested lists than top-level lists.
988                         # See extended comment in _ProcessListItems().
989
990                         if ($this->list_level) {
991                                 $text = preg_replace_callback('{
992                                                 ^
993                                                 '.$whole_list_re.'
994                                         }mx',
995                                         array(&$this, '_doLists_callback'), $text);
996                         }
997                         else {
998                                 $text = preg_replace_callback('{
999                                                 (?:(?<=\n)\n|\A\n?) # Must eat the newline
1000                                                 '.$whole_list_re.'
1001                                         }mx',
1002                                         array(&$this, '_doLists_callback'), $text);
1003                         }
1004                 }
1005
1006                 return $text;
1007         }
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)";
1013
1014                 $list = $matches[1];
1015                 $list_type = preg_match("/$marker_ul_re/", $matches[3]) ? "ul" : "ol";
1016
1017                 $marker_any_re = ( $list_type == "ul" ? $marker_ul_re : $marker_ol_re );
1018
1019                 $list .= "\n";
1020                 $result = $this->processListItems($list, $marker_any_re);
1021
1022                 $result = $this->hashBlock("<$list_type>\n" . $result . "</$list_type>");
1023                 return "\n". $result ."\n\n";
1024         }
1025
1026         var $list_level = 0;
1027
1028         function processListItems($list_str, $marker_any_re) {
1029         #
1030         #       Process the contents of a single ordered or unordered list, splitting it
1031         #       into individual list items.
1032         #
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.
1036                 #
1037                 # We do this because when we're not inside a list, we want to treat
1038                 # something like this:
1039                 #
1040                 #               I recommend upgrading to version
1041                 #               8. Oops, now this line is treated
1042                 #               as a sub-list.
1043                 #
1044                 # As a single paragraph, despite the fact that the second line starts
1045                 # with a digit-period-space sequence.
1046                 #
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.".
1053
1054                 $this->list_level++;
1055
1056                 # trim trailing blank lines:
1057                 $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str);
1058
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
1064                         )
1065                         ((?s:.*?))                                              # list item text   = $4
1066                         (?:(\n+(?=\n))|\n)                              # tailing blank line = $5
1067                         (?= \n* (\z | \2 ('.$marker_any_re.') (?:[ ]+|(?=\n))))
1068                         }xm',
1069                         array(&$this, '_processListItems_callback'), $list_str);
1070
1071                 $this->list_level--;
1072                 return $list_str;
1073         }
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];
1080
1081                 if ($leading_line || $tailing_blank_line ||
1082                         preg_match('/\n{2,}/', $item))
1083                 {
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");
1087                 }
1088                 else {
1089                         # Recursion for sub-lists:
1090                         $item = $this->doLists($this->outdent($item));
1091                         $item = preg_replace('/\n+$/', '', $item);
1092                         $item = $this->runSpanGamut($item);
1093                 }
1094
1095                 return "<li>" . $item . "</li>\n";
1096         }
1097
1098
1099         function doCodeBlocks($text) {
1100         #
1101         #       Process Markdown `<pre><code>` blocks.
1102         #
1103                 $text = preg_replace_callback('{
1104                                 (?:\n\n|\A\n?)
1105                                 (                   # $1 = the code block -- one or more lines, starting with a space/tab
1106                                   (?>
1107                                         [ ]{'.$this->tab_width.'}  # Lines must start with a tab or a tab-width of spaces
1108                                         .*\n+
1109                                   )+
1110                                 )
1111                                 ((?=^[ ]{0,'.$this->tab_width.'}\S)|\Z) # Lookahead for non-space at line-start, or end of doc
1112                         }xm',
1113                         array(&$this, '_doCodeBlocks_callback'), $text);
1114
1115                 return $text;
1116         }
1117         function _doCodeBlocks_callback($matches) {
1118                 $codeblock = $matches[1];
1119
1120                 $codeblock = $this->outdent($codeblock);
1121                 $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES);
1122
1123                 # trim leading newlines and trailing newlines
1124                 $codeblock = preg_replace('/\A\n+|\n+\z/', '', $codeblock);
1125
1126                 $codeblock = "<pre><code>$codeblock\n</code></pre>";
1127                 return "\n\n".$this->hashBlock($codeblock)."\n\n";
1128         }
1129
1130
1131         function makeCodeSpan($code) {
1132         #
1133         # Create a code span markup for $code. Called from handleSpanToken.
1134         #
1135                 $code = htmlspecialchars(trim($code), ENT_NOQUOTES);
1136                 return $this->hashPart("<code>$code</code>");
1137         }
1138
1139
1140         var $em_relist = array(
1141                 ''  => '(?:(?<!\*)\*(?!\*)|(?<!_)_(?!_))(?=\S)(?![.,:;]\s)',
1142                 '*' => '(?<=\S)(?<!\*)\*(?!\*)',
1143                 '_' => '(?<=\S)(?<!_)_(?!_)',
1144                 );
1145         var $strong_relist = array(
1146                 ''   => '(?:(?<!\*)\*\*(?!\*)|(?<!_)__(?!_))(?=\S)(?![.,:;]\s)',
1147                 '**' => '(?<=\S)(?<!\*)\*\*(?!\*)',
1148                 '__' => '(?<=\S)(?<!_)__(?!_)',
1149                 );
1150         var $em_strong_relist = array(
1151                 ''    => '(?:(?<!\*)\*\*\*(?!\*)|(?<!_)___(?!_))(?=\S)(?![.,:;]\s)',
1152                 '***' => '(?<=\S)(?<!\*)\*\*\*(?!\*)',
1153                 '___' => '(?<=\S)(?<!_)___(?!_)',
1154                 );
1155         var $em_strong_prepared_relist;
1156
1157         function prepareItalicsAndBold() {
1158         #
1159         # Prepare regular expressions for seraching emphasis tokens in any
1160         # context.
1161         #
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"];
1168                                 }
1169                                 $token_relist[] = $em_re;
1170                                 $token_relist[] = $strong_re;
1171
1172                                 # Construct master expression from list.
1173                                 $token_re = '{('. implode('|', $token_relist) .')}';
1174                                 $this->em_strong_prepared_relist["$em$strong"] = $token_re;
1175                         }
1176                 }
1177         }
1178
1179         function doItalicsAndBold($text) {
1180                 $token_stack = array('');
1181                 $text_stack = array('');
1182                 $em = '';
1183                 $strong = '';
1184                 $tree_char_em = false;
1185
1186                 while (1) {
1187                         #
1188                         # Get prepared regular expression for seraching emphasis tokens
1189                         # in current context.
1190                         #
1191                         $token_re = $this->em_strong_prepared_relist["$em$strong"];
1192
1193                         #
1194                         # Each loop iteration seach for the next emphasis token.
1195                         # Each token is then passed to handleSpanToken.
1196                         #
1197                         $parts = preg_split($token_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE);
1198                         $text_stack[0] .= $parts[0];
1199                         $token =& $parts[1];
1200                         $text =& $parts[2];
1201
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);
1208                                 }
1209                                 break;
1210                         }
1211
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);
1222                                         $em = '';
1223                                         $strong = '';
1224                                 } else {
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
1234                                 }
1235                                 $tree_char_em = false;
1236                         } else if ($token_len == 3) {
1237                                 if ($em) {
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
1248                                         }
1249                                 } else {
1250                                         # Reached opening three-char emphasis marker. Push on token
1251                                         # stack; will be handled by the special condition above.
1252                                         $em = $token{0};
1253                                         $strong = "$em$em";
1254                                         array_unshift($token_stack, $token);
1255                                         array_unshift($text_stack, '');
1256                                         $tree_char_em = true;
1257                                 }
1258                         } else if ($token_len == 2) {
1259                                 if ($strong) {
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);
1264                                         }
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);
1271                                         $strong = '';
1272                                 } else {
1273                                         array_unshift($token_stack, $token);
1274                                         array_unshift($text_stack, '');
1275                                         $strong = $token;
1276                                 }
1277                         } else {
1278                                 # Here $token_len == 1
1279                                 if ($em) {
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);
1287                                                 $em = '';
1288                                         } else {
1289                                                 $text_stack[0] .= $token;
1290                                         }
1291                                 } else {
1292                                         array_unshift($token_stack, $token);
1293                                         array_unshift($text_stack, '');
1294                                         $em = $token;
1295                                 }
1296                         }
1297                 }
1298                 return $text_stack[0];
1299         }
1300
1301
1302         function doBlockQuotes($text) {
1303                 $text = preg_replace_callback('/
1304                           (                                                             # Wrap whole match in $1
1305                                 (?>
1306                                   ^[ ]*>[ ]?                    # ">" at the start of a line
1307                                         .+\n                                    # rest of the first line
1308                                   (.+\n)*                                       # subsequent consecutive lines
1309                                   \n*                                           # blanks
1310                                 )+
1311                           )
1312                         /xm',
1313                         array(&$this, '_doBlockQuotes_callback'), $text);
1314
1315                 return $text;
1316         }
1317         function _doBlockQuotes_callback($matches) {
1318                 $bq = $matches[1];
1319                 # trim one level of quoting - trim whitespace-only lines
1320                 $bq = preg_replace('/^[ ]*>[ ]?|^[ ]+$/m', '', $bq);
1321                 $bq = $this->runBlockGamut($bq);                # recurse
1322
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);
1328
1329                 return "\n". $this->hashBlock("<blockquote>\n$bq\n</blockquote>")."\n\n";
1330         }
1331         function _doBlockQuotes_callback2($matches) {
1332                 $pre = $matches[1];
1333                 $pre = preg_replace('/^  /m', '', $pre);
1334                 return $pre;
1335         }
1336
1337
1338         function formParagraphs($text) {
1339         #
1340         #       Params:
1341         #               $text - string to process with html <p> tags
1342         #
1343                 # Strip leading and trailing lines:
1344                 $text = preg_replace('/\A\n+|\n+\z/', '', $text);
1345
1346                 $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY);
1347
1348                 #
1349                 # Wrap <p> tags and unhashify HTML blocks
1350                 #
1351                 foreach ($grafs as $key => $value) {
1352                         if (!preg_match('/^B\x1A[0-9]+B$/', $value)) {
1353                                 # Is a paragraph.
1354                                 $value = $this->runSpanGamut($value);
1355                                 $value = preg_replace('/^([ ]*)/', "<p>", $value);
1356                                 $value .= "</p>";
1357                                 $grafs[$key] = $this->unhash($value);
1358                         }
1359                         else {
1360                                 # Is a block.
1361                                 # Modify elements of @grafs in-place...
1362                                 $graf = $value;
1363                                 $block = $this->html_hashes[$graf];
1364                                 $graf = $block;
1365 //                              if (preg_match('{
1366 //                                      \A
1367 //                                      (                                                       # $1 = <div> tag
1368 //                                        <div  \s+
1369 //                                        [^>]*
1370 //                                        \b
1371 //                                        markdown\s*=\s*  ([\'"])      #       $2 = attr quote char
1372 //                                        1
1373 //                                        \2
1374 //                                        [^>]*
1375 //                                        >
1376 //                                      )
1377 //                                      (                                                       # $3 = contents
1378 //                                      .*
1379 //                                      )
1380 //                                      (</div>)                                        # $4 = closing tag
1381 //                                      \z
1382 //                                      }xs', $block, $matches))
1383 //                              {
1384 //                                      list(, $div_open, , $div_content, $div_close) = $matches;
1385 //
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);
1389 //
1390 //                                      # Run document gamut methods on the content.
1391 //                                      foreach ($this->document_gamut as $method => $priority) {
1392 //                                              $div_content = $this->$method($div_content);
1393 //                                      }
1394 //
1395 //                                      $div_open = preg_replace(
1396 //                                              '{\smarkdown\s*=\s*([\'"]).+?\1}', '', $div_open);
1397 //
1398 //                                      $graf = $div_open . "\n" . $div_content . "\n" . $div_close;
1399 //                              }
1400                                 $grafs[$key] = $graf;
1401                         }
1402                 }
1403
1404                 return implode("\n\n", $grafs);
1405         }
1406
1407
1408         function encodeAttribute($text) {
1409         #
1410         # Encode text for a double-quoted HTML attribute. This function
1411         # is *not* suitable for attributes enclosed in single quotes.
1412         #
1413                 $text = $this->encodeAmpsAndAngles($text);
1414                 $text = str_replace('"', '&quot;', $text);
1415                 return $text;
1416         }
1417
1418
1419         function encodeAmpsAndAngles($text) {
1420         #
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.
1424         #
1425                 if ($this->no_entities) {
1426                         $text = str_replace('&', '&amp;', $text);
1427                 } else {
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+);)/',
1431                                                                 '&amp;', $text);;
1432                 }
1433                 # Encode remaining <'s
1434                 $text = str_replace('<', '&lt;', $text);
1435
1436                 return $text;
1437         }
1438
1439
1440         function doAutoLinks($text) {
1441                 $text = preg_replace_callback('{<((https?|ftp|dict):[^\'">\s]+)>}i',
1442                         array(&$this, '_doAutoLinks_url_callback'), $text);
1443
1444                 # Email addresses: <address@domain.foo>
1445                 $text = preg_replace_callback('{
1446                         <
1447                         (?:mailto:)?
1448                         (
1449                                 [-.\w\x80-\xFF]+
1450                                 \@
1451                                 [-a-z0-9\x80-\xFF]+(\.[-a-z0-9\x80-\xFF]+)*\.[a-z]+
1452                         )
1453                         >
1454                         }xi',
1455                         array(&$this, '_doAutoLinks_email_callback'), $text);
1456
1457                 return $text;
1458         }
1459         function _doAutoLinks_url_callback($matches) {
1460                 $url = $this->encodeAttribute($matches[1]);
1461                 $link = "<a href=\"$url\">$url</a>";
1462                 return $this->hashPart($link);
1463         }
1464         function _doAutoLinks_email_callback($matches) {
1465                 $address = $matches[1];
1466                 $link = $this->encodeEmailAddress($address);
1467                 return $this->hashPart($link);
1468         }
1469
1470
1471         function encodeEmailAddress($addr) {
1472         #
1473         #       Input: an email address, e.g. "foo@example.com"
1474         #
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.:
1478         #
1479         #         <p><a href="&#109;&#x61;&#105;&#x6c;&#116;&#x6f;&#58;&#x66;o&#111;
1480         #        &#x40;&#101;&#x78;&#97;&#x6d;&#112;&#x6c;&#101;&#46;&#x63;&#111;
1481         #        &#x6d;">&#x66;o&#111;&#x40;&#101;&#x78;&#97;&#x6d;&#112;&#x6c;
1482         #        &#101;&#46;&#x63;&#111;&#x6d;</a></p>
1483         #
1484         #       Based by a filter by Matthew Wickline, posted to BBEdit-Talk.
1485         #   With some optimizations by Milian Wolff.
1486         #
1487                 $addr = "mailto:" . $addr;
1488                 $chars = preg_split('/(?<!^)(?!$)/', $addr);
1489                 $seed = (int)abs(crc32($addr) / strlen($addr)); # Deterministic seed.
1490
1491                 foreach ($chars as $key => $char) {
1492                         $ord = ord($char);
1493                         # Ignore non-ascii chars.
1494                         if ($ord < 128) {
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.';';
1501                         }
1502                 }
1503
1504                 $addr = implode('', $chars);
1505                 $text = implode('', array_slice($chars, 7)); # text without `mailto:`
1506                 $addr = "<a href=\"$addr\">$text</a>";
1507
1508                 return $addr;
1509         }
1510
1511
1512         function parseSpan($str) {
1513         #
1514         # Take the string $str and parse it into tokens, hashing embeded HTML,
1515         # escaped characters and handling code spans.
1516         #
1517                 $output = '';
1518
1519                 $span_re = '{
1520                                 (
1521                                         \\\\'.$this->escape_chars_re.'
1522                                 |
1523                                         (?<![`\\\\])
1524                                         `+                                              # code span marker
1525                         '.( $this->no_markup ? '' : '
1526                                 |
1527                                         <!--    .*?     -->             # comment
1528                                 |
1529                                         <\?.*?\?> | <%.*?%>             # processing instruction
1530                                 |
1531                                         <[/!$]?[-a-zA-Z0-9:_]+  # regular tags
1532                                         (?>
1533                                                 \s
1534                                                 (?>[^"\'>]+|"[^"]*"|\'[^\']*\')*
1535                                         )?
1536                                         >
1537                         ').'
1538                                 )
1539                                 }xs';
1540
1541                 while (1) {
1542                         #
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.
1546                         #
1547                         $parts = preg_split($span_re, $str, 2, PREG_SPLIT_DELIM_CAPTURE);
1548
1549                         # Create token from text preceding tag.
1550                         if ($parts[0] != "") {
1551                                 $output .= $parts[0];
1552                         }
1553
1554                         # Check if we reach the end.
1555                         if (isset($parts[1])) {
1556                                 $output .= $this->handleSpanToken($parts[1], $parts[2]);
1557                                 $str = $parts[2];
1558                         }
1559                         else {
1560                                 break;
1561                         }
1562                 }
1563
1564                 return $output;
1565         }
1566
1567
1568         function handleSpanToken($token, &$str) {
1569         #
1570         # Handle $token provided by parseSpan by determining its nature and
1571         # returning the corresponding value that should replace it.
1572         #
1573                 switch ($token{0}) {
1574                         case "\\":
1575                                 return $this->hashPart("&#". ord($token{1}). ";");
1576                         case "`":
1577                                 # Search for end marker in remaining text.
1578                                 if (preg_match('/^(.*?[^`])'.preg_quote($token).'(?!`)(.*)$/sm',
1579                                         $str, $matches))
1580                                 {
1581                                         $str = $matches[2];
1582                                         $codespan = $this->makeCodeSpan($matches[1]);
1583                                         return $this->hashPart($codespan);
1584                                 }
1585                                 return $token; // return as text since no ending marker found.
1586                         default:
1587                                 return $this->hashPart($token);
1588                 }
1589         }
1590
1591
1592         function outdent($text) {
1593         #
1594         # Remove one level of line-leading tabs or spaces
1595         #
1596                 return preg_replace('/^(\t|[ ]{1,'.$this->tab_width.'})/m', '', $text);
1597         }
1598
1599
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';
1603
1604         function detab($text) {
1605         #
1606         # Replace tabs with the appropriate amount of space.
1607         #
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.
1611
1612                 $text = preg_replace_callback('/^.*\t.*$/m',
1613                         array(&$this, '_detab_callback'), $text);
1614
1615                 return $text;
1616         }
1617         function _detab_callback($matches) {
1618                 $line = $matches[0];
1619                 $strlen = $this->utf8_strlen; # strlen function for UTF-8.
1620
1621                 # Split in blocks.
1622                 $blocks = explode("\t", $line);
1623                 # Add each blocks to the line.
1624                 $line = $blocks[0];
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;
1631                 }
1632                 return $line;
1633         }
1634         function _initDetab() {
1635         #
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.
1640         #
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]*/",
1644                         $text, $m);');
1645         }
1646
1647
1648         function unhash($text) {
1649         #
1650         # Swap back in all the tags hashed by _HashHTMLBlocks.
1651         #
1652                 return preg_replace_callback('/(.)\x1A[0-9]+\1/',
1653                         array(&$this, '_unhash_callback'), $text);
1654         }
1655         function _unhash_callback($matches) {
1656                 return $this->html_hashes[$matches[0]];
1657         }
1658
1659 }
1660
1661
1662 #
1663 # Markdown Extra Parser Class
1664 #
1665
1666 class MarkdownExtra_Parser extends Markdown_Parser {
1667
1668         # Prefix for footnote ids.
1669         var $fn_id_prefix = "";
1670
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;
1674
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;
1678
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;
1683
1684         var $ha_enable = MARKDOWN_HA_ENABLE;
1685         var $ha_class = MARKDOWN_HA_CLASS;
1686         var $ha_text = MARKDOWN_HA_TEXT;
1687
1688         # Predefined abbreviations.
1689         var $predef_abbr = array();
1690
1691
1692         function MarkdownExtra_Parser() {
1693         #
1694         # Constructor function. Initialize the parser object.
1695         #
1696                 # Add extra escapable characters before parent constructor
1697                 # initialize the table.
1698                 $this->escape_chars .= ':|';
1699
1700                 if ($this->el_local_domain === null) {
1701                         $this->el_local_domain = $_SERVER['SERVER_NAME'];
1702                 }
1703
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,
1711                         );
1712                 $this->block_gamut += array(
1713                         "doFencedCodeBlocks" => 5,
1714                         "doTables"           => 15,
1715                         "doDefLists"         => 45,
1716                         );
1717                 $this->span_gamut += array(
1718                         "doFootnotes"        => 5,
1719                         "doAbbreviations"    => 70,
1720                         );
1721
1722                 parent::Markdown_Parser();
1723         }
1724
1725
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 = '';
1731
1732         # Give the current footnote number.
1733         var $footnote_counter = 1;
1734
1735
1736         function setup() {
1737         #
1738         # Setting up Extra-specific variables.
1739         #
1740                 parent::setup();
1741
1742                 $this->footnotes = array();
1743                 $this->footnotes_ordered = array();
1744                 $this->abbr_desciptions = array();
1745                 $this->abbr_word_re = '';
1746                 $this->footnote_counter = 1;
1747
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);
1753                 }
1754         }
1755
1756         function teardown() {
1757         #
1758         # Clearing Extra-specific variables.
1759         #
1760                 $this->footnotes = array();
1761                 $this->footnotes_ordered = array();
1762                 $this->abbr_desciptions = array();
1763                 $this->abbr_word_re = '';
1764
1765                 parent::teardown();
1766         }
1767
1768
1769         ### HTML Block Parser ###
1770
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';
1773
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';
1776
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';
1779
1780         # Tags which must not have their contents modified, no matter where
1781         # they appear:
1782         var $clean_tags_re = 'script|math';
1783
1784         # Tags that do not need to be closed.
1785         var $auto_close_tags_re = 'hr|img';
1786
1787
1788         function hashHTMLBlocks($text) {
1789         #
1790         # Hashify HTML Blocks and "clean tags".
1791         #
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
1796         # hard-coded.
1797         #
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!
1803         #
1804                 #
1805                 # Call the HTML-in-Markdown hasher.
1806                 #
1807                 list($text, ) = $this->_hashHTMLBlocks_inMarkdown($text);
1808
1809                 return $text;
1810         }
1811         function _hashHTMLBlocks_inMarkdown($text, $indent = 0,
1812                                                                                 $enclosing_tag_re = '', $span = false)
1813         {
1814         #
1815         # Parse markdown text, calling _HashHTMLBlocks_InHTML for block tags.
1816         #
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:
1820         #
1821         #     <div>
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?
1825         #     <div>
1826         #
1827         #     If you don't like this, just don't indent the tag on which
1828         #     you apply the markdown="1" attribute.
1829         #
1830         # *   If $enclosing_tag_re is not empty, stops at the first unmatched closing
1831         #     tag with that name. Nested tags supported.
1832         #
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
1835         #     paragraphs.
1836         #
1837         # Returns an array of that form: ( processed text , remaining text )
1838         #
1839                 if ($text === '') return array('', '');
1840
1841                 # Regex to check for the presense of newlines around a block tag.
1842                 $newline_before_re = '/(?:^\n?|\n\n)*$/';
1843                 $newline_after_re =
1844                         '{
1845                                 ^                                               # Start of text following the tag.
1846                                 (?>[ ]*<!--.*?-->)?             # Optional comment.
1847                                 [ ]*\n                                  # Must be followed by newline.
1848                         }xs';
1849
1850                 # Regex to match any tag.
1851                 $block_tag_re =
1852                         '{
1853                                 (                                       # $2: Capture hole tag.
1854                                         </?                                     # Any opening or closing tag.
1855                                                 (?>                             # Tag name.
1856                                                         '.$this->block_tags_re.'                        |
1857                                                         '.$this->context_block_tags_re.'        |
1858                                                         '.$this->clean_tags_re.'                |
1859                                                         (?!\s)'.$enclosing_tag_re.'
1860                                                 )
1861                                                 (?:
1862                                                         (?=[\s"\'/a-zA-Z0-9])   # Allowed characters after tag name.
1863                                                         (?>
1864                                                                 ".*?"           |       # Double quotes (can contain `>`)
1865                                                                 \'.*?\'         |       # Single quotes (can contain `>`)
1866                                                                 .+?                             # Anything but quotes and `>`.
1867                                                         )*?
1868                                                 )?
1869                                         >                                       # End of tag.
1870                                 |
1871                                         <!--    .*?     -->     # HTML Comment
1872                                 |
1873                                         <\?.*?\?> | <%.*?%>     # Processing instruction
1874                                 |
1875                                         <!\[CDATA\[.*?\]\]>     # CData Block
1876                                 |
1877                                         # Code span marker
1878                                         `+
1879                                 '. ( !$span ? ' # If not in span.
1880                                 |
1881                                         # Indented code block
1882                                         (?> ^[ ]*\n? | \n[ ]*\n )
1883                                         [ ]{'.($indent+4).'}[^\n]* \n
1884                                         (?>
1885                                                 (?: [ ]{'.($indent+4).'}[^\n]* | [ ]* ) \n
1886                                         )*
1887                                 |
1888                                         # Fenced code block marker
1889                                         (?> ^ | \n )
1890                                         [ ]{'.($indent).'}~~~+[ ]*\n
1891                                 ' : '' ). ' # End (if not is span).
1892                                 )
1893                         }xs';
1894
1895
1896                 $depth = 0;             # Current depth inside the tag tree.
1897                 $parsed = "";   # Parsed text that will be returned.
1898
1899                 #
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.
1902                 #
1903                 do {
1904                         #
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
1908                         # by the pattern.
1909                         #
1910                         $parts = preg_split($block_tag_re, $text, 2,
1911                                                                 PREG_SPLIT_DELIM_CAPTURE);
1912
1913                         # If in Markdown span mode, add a empty-string span-level hash
1914                         # after each newline to prevent triggering any block element.
1915                         if ($span) {
1916                                 $void = $this->hashPart("", ':');
1917                                 $newline = "$void\n";
1918                                 $parts[0] = $void . str_replace("\n", $newline, $parts[0]) . $void;
1919                         }
1920
1921                         $parsed .= $parts[0]; # Text before current tag.
1922
1923                         # If end of $text has been reached. Stop loop.
1924                         if (count($parts) < 3) {
1925                                 $text = "";
1926                                 break;
1927                         }
1928
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.
1932
1933                         #
1934                         # Check for: Code span marker
1935                         #
1936                         if ($tag{0} == "`") {
1937                                 # Find corresponding end marker.
1938                                 $tag_re = preg_quote($tag);
1939                                 if (preg_match('{^(?>.+?|\n(?!\n))*?(?<!`)'.$tag_re.'(?!`)}',
1940                                         $text, $matches))
1941                                 {
1942                                         # End marker found: pass text unchanged until marker.
1943                                         $parsed .= $tag . $matches[0];
1944                                         $text = substr($text, strlen($matches[0]));
1945                                 }
1946                                 else {
1947                                         # Unmatched marker: just skip it.
1948                                         $parsed .= $tag;
1949                                 }
1950                         }
1951                         #
1952                         # Check for: Indented code block or fenced code block marker.
1953                         #
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
1957                                         # later.
1958                                         $parsed .= $tag;
1959                                 }
1960                                 else {
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,
1964                                                 $matches))
1965                                         {
1966                                                 # End marker found: pass text unchanged until marker.
1967                                                 $parsed .= $tag . $matches[0];
1968                                                 $text = substr($text, strlen($matches[0]));
1969                                         }
1970                                         else {
1971                                                 # No end marker: just skip it.
1972                                                 $parsed .= $tag;
1973                                         }
1974                                 }
1975                         }
1976                         #
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).
1980                         #
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)    )
1985                                 )
1986                         {
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);
1990
1991                                 # Make sure it stays outside of any paragraph by adding newlines.
1992                                 $parsed .= "\n\n$block_text\n\n";
1993                         }
1994                         #
1995                         # Check for: Clean tag (like script, math)
1996                         #            HTML Comments, processing instructions.
1997                         #
1998                         else if (preg_match('{^<(?:'.$this->clean_tags_re.')\b}', $tag) ||
1999                                 $tag{1} == '!' || $tag{1} == '?')
2000                         {
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);
2005
2006                                 $parsed .= $block_text;
2007                         }
2008                         #
2009                         # Check for: Tag with same name as enclosing tag.
2010                         #
2011                         else if ($enclosing_tag_re !== '' &&
2012                                 # Same name as enclosing tag.
2013                                 preg_match('{^</?(?:'.$enclosing_tag_re.')\b}', $tag))
2014                         {
2015                                 #
2016                                 # Increase/decrease nested tag count.
2017                                 #
2018                                 if ($tag{1} == '/')                                             $depth--;
2019                                 else if ($tag{strlen($tag)-2} != '/')   $depth++;
2020
2021                                 if ($depth < 0) {
2022                                         #
2023                                         # Going out of parent element. Clean up and break so we
2024                                         # return to the calling function.
2025                                         #
2026                                         $text = $tag . $text;
2027                                         break;
2028                                 }
2029
2030                                 $parsed .= $tag;
2031                         }
2032                         else {
2033                                 $parsed .= $tag;
2034                         }
2035                 } while ($depth >= 0);
2036
2037                 return array($parsed, $text);
2038         }
2039         function _hashHTMLBlocks_inHTML($text, $hash_method, $md_attr) {
2040         #
2041         # Parse HTML, calling _HashHTMLBlocks_InMarkdown for block tags.
2042         #
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)
2047         #
2048         # Returns an array of that form: ( processed text , remaining text )
2049         #
2050                 if ($text === '') return array('', '');
2051
2052                 # Regex to match `markdown` attribute inside of a tag.
2053                 $markdown_attr_re = '
2054                         {
2055                                 \s*                     # Eat whitespace before the `markdown` attribute
2056                                 markdown
2057                                 \s*=\s*
2058                                 (?>
2059                                         (["\'])         # $1: quote delimiter
2060                                         (.*?)           # $2: attribute value
2061                                         \1                      # matching delimiter
2062                                 |
2063                                         ([^\s>]*)       # $3: unquoted attribute value
2064                                 )
2065                                 ()                              # $4: make $3 always defined (avoid warnings)
2066                         }xs';
2067
2068                 # Regex to match any tag.
2069                 $tag_re = '{
2070                                 (                                       # $2: Capture hole tag.
2071                                         </?                                     # Any opening or closing tag.
2072                                                 [\w:$]+                 # Tag name.
2073                                                 (?:
2074                                                         (?=[\s"\'/a-zA-Z0-9])   # Allowed characters after tag name.
2075                                                         (?>
2076                                                                 ".*?"           |       # Double quotes (can contain `>`)
2077                                                                 \'.*?\'         |       # Single quotes (can contain `>`)
2078                                                                 .+?                             # Anything but quotes and `>`.
2079                                                         )*?
2080                                                 )?
2081                                         >                                       # End of tag.
2082                                 |
2083                                         <!--    .*?     -->     # HTML Comment
2084                                 |
2085                                         <\?.*?\?> | <%.*?%>     # Processing instruction
2086                                 |
2087                                         <!\[CDATA\[.*?\]\]>     # CData Block
2088                                 )
2089                         }xs';
2090
2091                 $original_text = $text;         # Save original text in case of faliure.
2092
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.
2096
2097                 #
2098                 # Get the name of the starting tag.
2099                 # (This pattern makes $base_tag_name_re safe without quoting.)
2100                 #
2101                 if (preg_match('/^<([\w:$]*)\b/', $text, $matches))
2102                         $base_tag_name_re = $matches[1];
2103
2104                 #
2105                 # Loop through every tag until we find the corresponding closing tag.
2106                 #
2107                 do {
2108                         #
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
2112                         # by the pattern.
2113                         #
2114                         $parts = preg_split($tag_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE);
2115
2116                         if (count($parts) < 3) {
2117                                 #
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
2121                                 # parent function.
2122                                 #
2123                                 return array($original_text{0}, substr($original_text, 1));
2124                         }
2125
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.
2129
2130                         #
2131                         # Check for: Auto-close tag (like <hr/>)
2132                         #                        Comments and Processing Instructions.
2133                         #
2134                         if (preg_match('{^</?(?:'.$this->auto_close_tags_re.')\b}', $tag) ||
2135                                 $tag{1} == '!' || $tag{1} == '?')
2136                         {
2137                                 # Just add the tag to the block as if it was text.
2138                                 $block_text .= $tag;
2139                         }
2140                         else {
2141                                 #
2142                                 # Increase/decrease nested tag count. Only do so if
2143                                 # the tag's name match base tag's.
2144                                 #
2145                                 if (preg_match('{^</?'.$base_tag_name_re.'\b}', $tag)) {
2146                                         if ($tag{1} == '/')                                             $depth--;
2147                                         else if ($tag{strlen($tag)-2} != '/')   $depth++;
2148                                 }
2149
2150                                 #
2151                                 # Check for `markdown="1"` attribute and handle it.
2152                                 #
2153                                 if ($md_attr &&
2154                                         preg_match($markdown_attr_re, $tag, $attr_m) &&
2155                                         preg_match('/^1|block|span$/', $attr_m[2] . $attr_m[3]))
2156                                 {
2157                                         # Remove `markdown` attribute from opening tag.
2158                                         $tag = preg_replace($markdown_attr_re, '', $tag);
2159
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);
2164
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');
2169                                         } else {
2170                                                 $indent = 0;
2171                                         }
2172
2173                                         # End preceding block with this tag.
2174                                         $block_text .= $tag;
2175                                         $parsed .= $this->$hash_method($block_text);
2176
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];
2181
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);
2186
2187                                         # Outdent markdown text.
2188                                         if ($indent > 0) {
2189                                                 $block_text = preg_replace("/^[ ]{1,$indent}/m", "",
2190                                                                                                         $block_text);
2191                                         }
2192
2193                                         # Append tag content to parsed text.
2194                                         if (!$span_mode)        $parsed .= "\n\n$block_text\n\n";
2195                                         else                            $parsed .= "$block_text";
2196
2197                                         # Start over a new block.
2198                                         $block_text = "";
2199                                 }
2200                                 else $block_text .= $tag;
2201                         }
2202
2203                 } while ($depth > 0);
2204
2205                 #
2206                 # Hash last block text that wasn't processed inside the loop.
2207                 #
2208                 $parsed .= $this->$hash_method($block_text);
2209
2210                 return array($parsed, $text);
2211         }
2212
2213
2214         function hashClean($text) {
2215         #
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.
2219         #
2220                 return $this->hashPart($text, 'C');
2221         }
2222
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];
2228
2229                 $url = $this->encodeAttribute($url);
2230
2231                 $result = "<a href=\"$url\"";
2232                 if (isset($title)) {
2233                         $title = $this->encodeAttribute($title);
2234                         $result .=  " title=\"$title\"";
2235                 }
2236
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"';
2240                         }
2241
2242                         if ($this->el_css_class) {
2243                                 $result .= ' class="'.$this->el_css_class.'"';
2244                         }
2245                 }
2246
2247                 $link_text = $this->runSpanGamut($link_text);
2248                 $result .= ">$link_text</a>";
2249
2250                 return $this->hashPart($result);
2251         }
2252
2253         function _doAnchors_reference_callback($matches) {
2254                 $whole_match =  $matches[1];
2255                 $link_text   =  $matches[2];
2256                 $link_id     =& $matches[3];
2257                 $result      =  '';
2258
2259                 if ($link_id == "") {
2260                         # for shortcut links like [this][] or [this].
2261                         $link_id = $link_text;
2262                 }
2263
2264                 # lower-case and turn embedded newlines into spaces
2265                 $link_id = strtolower($link_id);
2266                 $link_id = preg_replace('{[ ]?\n}', ' ', $link_id);
2267
2268                 if (isset($this->urls[$link_id])) {
2269                         $url = $this->urls[$link_id];
2270                         $url = $this->encodeAttribute($url);
2271
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\"";
2277                         }
2278
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"';
2282                                 }
2283
2284                                 if ($this->el_css_class) {
2285                                         $result .= ' class="'.$this->el_css_class.'"';
2286                                 }
2287                         }
2288
2289                         $link_text = $this->runSpanGamut($link_text);
2290                         $result .= ">$link_text</a>";
2291                         $result = $this->hashPart($result);
2292                 }
2293                 else {
2294                         $result = $whole_match;
2295                 }
2296                 return $result;
2297         }
2298
2299         function doHeaders($text) {
2300         #
2301         # Redefined to add id attribute support.
2302         #
2303                 # Setext-style headers:
2304                 #         Header 1  {#header1}
2305                 #         ========
2306                 #
2307                 #         Header 2  {#header2}
2308                 #         --------
2309                 #
2310                 $text = preg_replace_callback(
2311                         '{
2312                                 (^.+?)                                                          # $1: Header text
2313                                 (?:[ ]+\{\#([-_:a-zA-Z0-9]+)\})?        # $2: Id attribute
2314                                 [ ]*\n(=+|-+)[ ]*\n+                            # $3: Header footer
2315                         }mx',
2316                         array(&$this, '_doHeaders_callback_setext'), $text);
2317
2318                 # atx-style headers:
2319                 #       # Header 1        {#header1}
2320                 #       ## Header 2       {#header2}
2321                 #       ## Header 2 with closing hashes ##  {#header3}
2322                 #       ...
2323                 #       ###### Header 6   {#header2}
2324                 #
2325                 $text = preg_replace_callback('{
2326                                 ^(\#{1,6})      # $1 = string of #\'s
2327                                 [ ]*
2328                                 (.+?)           # $2 = Header text
2329                                 [ ]*
2330                                 \#*                     # optional closing #\'s (not counted)
2331                                 (?:[ ]+\{\#([-_:a-zA-Z0-9]+)\})? # id attribute
2332                                 [ ]*
2333                                 \n+
2334                         }xm',
2335                         array(&$this, '_doHeaders_callback_atx'), $text);
2336
2337                 return $text;
2338         }
2339         function _doHeaders_attr($attr) {
2340                 if (empty($attr))  return "";
2341                 return " id=\"$attr\"";
2342         }
2343         function _doHeaders_callback_setext($matches) {
2344                 if ($matches[3] == '-' && preg_match('{^- }', $matches[1]))
2345                         return $matches[0];
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);
2350
2351                 $block = "<h$level$attr>$body</h$level>";
2352                 return "\n" . $this->hashBlock($block) . "\n\n";
2353         }
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);
2359
2360                 $block = "<h$level$attr>$body</h$level>";
2361                 return "\n" . $this->hashBlock($block) . "\n\n";
2362         }
2363         function _doHeaders_selflink($id, $body) {
2364                 if (!empty($id)) {
2365                         $link = '<a href="#'.$id.'"';
2366
2367                         if ($this->ha_class) {
2368                                 $link .= ' class="'.$this->ha_class.'"';
2369                         }
2370
2371                         $link .= '>'.$this->ha_text.'</a>';
2372
2373                         $body .= $link;
2374                 }
2375
2376                 return $body;
2377         }
2378
2379
2380         function doTables($text) {
2381         #
2382         # Form HTML tables.
2383         #
2384                 $less_than_tab = $this->tab_width - 1;
2385                 #
2386                 # Find tables with leading pipe.
2387                 #
2388                 #       | Header 1 | Header 2
2389                 #       | -------- | --------
2390                 #       | Cell 1   | Cell 2
2391                 #       | Cell 3   | Cell 4
2392                 #
2393                 $text = preg_replace_callback('
2394                         {
2395                                 ^                                                       # Start of a line
2396                                 [ ]{0,'.$less_than_tab.'}       # Allowed whitespace.
2397                                 [|]                                                     # Optional leading pipe (present)
2398                                 (.+) \n                                         # $1: Header row (at least one pipe)
2399
2400                                 [ ]{0,'.$less_than_tab.'}       # Allowed whitespace.
2401                                 [|] ([ ]*[-:]+[-| :]*) \n       # $2: Header underline
2402
2403                                 (                                                       # $3: Cells
2404                                         (?>
2405                                                 [ ]*                            # Allowed whitespace.
2406                                                 [|] .* \n                       # Row content.
2407                                         )*
2408                                 )
2409                                 (?=\n|\Z)                                       # Stop at final double newline.
2410                         }xm',
2411                         array(&$this, '_doTable_leadingPipe_callback'), $text);
2412
2413                 #
2414                 # Find tables without leading pipe.
2415                 #
2416                 #       Header 1 | Header 2
2417                 #       -------- | --------
2418                 #       Cell 1   | Cell 2
2419                 #       Cell 3   | Cell 4
2420                 #
2421                 $text = preg_replace_callback('
2422                         {
2423                                 ^                                                       # Start of a line
2424                                 [ ]{0,'.$less_than_tab.'}       # Allowed whitespace.
2425                                 (\S.*[|].*) \n                          # $1: Header row (at least one pipe)
2426
2427                                 [ ]{0,'.$less_than_tab.'}       # Allowed whitespace.
2428                                 ([-:]+[ ]*[|][-| :]*) \n        # $2: Header underline
2429
2430                                 (                                                       # $3: Cells
2431                                         (?>
2432                                                 .* [|] .* \n            # Row content
2433                                         )*
2434                                 )
2435                                 (?=\n|\Z)                                       # Stop at final double newline.
2436                         }xm',
2437                         array(&$this, '_DoTable_callback'), $text);
2438
2439                 return $text;
2440         }
2441         function _doTable_leadingPipe_callback($matches) {
2442                 $head           = $matches[1];
2443                 $underline      = $matches[2];
2444                 $content        = $matches[3];
2445
2446                 # Remove leading pipe for each row.
2447                 $content        = preg_replace('/^ *[|]/m', '', $content);
2448
2449                 return $this->_doTable_callback(array($matches[0], $head, $underline, $content));
2450         }
2451         function _doTable_callback($matches) {
2452                 $head           = $matches[1];
2453                 $underline      = $matches[2];
2454                 $content        = $matches[3];
2455
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);
2460
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] = '';
2468                 }
2469
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);
2475
2476                 # Write column headers.
2477                 $text = "<table>\n";
2478                 $text .= "<thead>\n";
2479                 $text .= "<tr>\n";
2480                 foreach ($headers as $n => $header)
2481                         $text .= "  <th$attr[$n]>".$this->runSpanGamut(trim($header))."</th>\n";
2482                 $text .= "</tr>\n";
2483                 $text .= "</thead>\n";
2484
2485                 # Split content by row.
2486                 $rows = explode("\n", trim($content, "\n"));
2487
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);
2493
2494                         # Split row by cell.
2495                         $row_cells = preg_split('/ *[|] */', $row, $col_count);
2496                         $row_cells = array_pad($row_cells, $col_count, '');
2497
2498                         $text .= "<tr>\n";
2499                         foreach ($row_cells as $n => $cell)
2500                                 $text .= "  <td$attr[$n]>".$this->runSpanGamut(trim($cell))."</td>\n";
2501                         $text .= "</tr>\n";
2502                 }
2503                 $text .= "</tbody>\n";
2504                 $text .= "</table>";
2505
2506                 return $this->hashBlock($text) . "\n";
2507         }
2508
2509
2510         function doDefLists($text) {
2511         #
2512         # Form HTML definition lists.
2513         #
2514                 $less_than_tab = $this->tab_width - 1;
2515
2516                 # Re-usable pattern to match any entire dl list:
2517                 $whole_list_re = '(?>
2518                         (                                                               # $1 = whole list
2519                           (                                                             # $2
2520                                 [ ]{0,'.$less_than_tab.'}
2521                                 ((?>.*\S.*\n)+)                         # $3 = defined term
2522                                 \n?
2523                                 [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition
2524                           )
2525                           (?s:.+?)
2526                           (                                                             # $4
2527                                   \z
2528                                 |
2529                                   \n{2,}
2530                                   (?=\S)
2531                                   (?!                                           # Negative lookahead for another term
2532                                         [ ]{0,'.$less_than_tab.'}
2533                                         (?: \S.*\n )+?                  # defined term
2534                                         \n?
2535                                         [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition
2536                                   )
2537                                   (?!                                           # Negative lookahead for another definition
2538                                         [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition
2539                                   )
2540                           )
2541                         )
2542                 )'; // mx
2543
2544                 $text = preg_replace_callback('{
2545                                 (?>\A\n?|(?<=\n\n))
2546                                 '.$whole_list_re.'
2547                         }mx',
2548                         array(&$this, '_doDefLists_callback'), $text);
2549
2550                 return $text;
2551         }
2552         function _doDefLists_callback($matches) {
2553                 # Re-usable patterns to match list item bullets and number markers:
2554                 $list = $matches[1];
2555
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";
2561         }
2562
2563
2564         function processDefListItems($list_str) {
2565         #
2566         #       Process the contents of a single definition list, splitting it
2567         #       into individual term and definition list items.
2568         #
2569                 $less_than_tab = $this->tab_width - 1;
2570
2571                 # trim trailing blank lines:
2572                 $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str);
2573
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).
2582                         )
2583                         (?=\n?[ ]{0,3}:[ ])                             # lookahead for following line feed
2584                                                                                         #   with a definition mark.
2585                         }xm',
2586                         array(&$this, '_processDefListItems_callback_dt'), $list_str);
2587
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)
2594                         )
2595                         ((?s:.+?))                                              # definition text = $3
2596                         (?= \n+                                                 # stop at next definition mark,
2597                                 (?:                                                     # next term or end of text
2598                                         [ ]{0,'.$less_than_tab.'} [:][ ]        |
2599                                         <dt | \z
2600                                 )
2601                         )
2602                         }xm',
2603                         array(&$this, '_processDefListItems_callback_dd'), $list_str);
2604
2605                 return $list_str;
2606         }
2607         function _processDefListItems_callback_dt($matches) {
2608                 $anchor_regexp = '/\{\#([-_:a-zA-Z0-9]+)\}/';
2609                 $terms = explode("\n", trim($matches[1]));
2610                 $text = '';
2611                 $id = array();
2612
2613                 foreach ($terms as $term) {
2614                         $id = '';
2615                         if (preg_match($anchor_regexp, $term, $id) > 0) {
2616                                 $term = preg_replace($anchor_regexp, '', $term);
2617                                 $id = ' id="'.trim($id[1]).'"';
2618                         }
2619
2620                         if (count($id) === 0) {
2621                                 $id = '';
2622                         }
2623
2624                         $term = $this->runSpanGamut(trim($term));
2625                         $text .= "\n<dt$id>" . $term . "</dt>";
2626                 }
2627                 return $text . "\n";
2628         }
2629         function _processDefListItems_callback_dd($matches) {
2630                 $leading_line   = $matches[1];
2631                 $marker_space   = $matches[2];
2632                 $def                    = $matches[3];
2633
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";
2639                 }
2640                 else {
2641                         $def = rtrim($def);
2642                         $def = $this->runSpanGamut($this->outdent($def));
2643                 }
2644
2645                 return "\n<dd>" . $def . "</dd>\n";
2646         }
2647
2648
2649         function doFencedCodeBlocks($text) {
2650         #
2651         # Adding the fenced code block syntax to regular Markdown:
2652         #
2653         # ~~~
2654         # Code block
2655         # ~~~
2656         #
2657                 $less_than_tab = $this->tab_width;
2658
2659                 $text = preg_replace_callback('{
2660                                 (?:\n|\A)
2661                                 # 1: Opening marker
2662                                 (
2663                                         ~{3,} # Marker: three tilde or more.
2664                                 )
2665                                 [ ]* \n # Whitespace and newline following marker.
2666
2667                                 # 2: Content
2668                                 (
2669                                         (?>
2670                                                 (?!\1 [ ]* \n)  # Not a closing marker.
2671                                                 .*\n+
2672                                         )+
2673                                 )
2674
2675                                 # Closing marker.
2676                                 \1 [ ]* \n
2677                         }xm',
2678                         array(&$this, '_doFencedCodeBlocks_callback'), $text);
2679
2680                 return $text;
2681         }
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";
2689         }
2690         function _doFencedCodeBlocks_newlines($matches) {
2691                 return str_repeat("<br$this->empty_element_suffix",
2692                         strlen($matches[0]));
2693         }
2694
2695
2696         #
2697         # Redefining emphasis markers so that emphasis by underscore does not
2698         # work in the middle of a word.
2699         #
2700         var $em_relist = array(
2701                 ''  => '(?:(?<!\*)\*(?!\*)|(?<![a-zA-Z0-9_])_(?!_))(?=\S)(?![.,:;]\s)',
2702                 '*' => '(?<=\S)(?<!\*)\*(?!\*)',
2703                 '_' => '(?<=\S)(?<!_)_(?![a-zA-Z0-9_])',
2704                 );
2705         var $strong_relist = array(
2706                 ''   => '(?:(?<!\*)\*\*(?!\*)|(?<![a-zA-Z0-9_])__(?!_))(?=\S)(?![.,:;]\s)',
2707                 '**' => '(?<=\S)(?<!\*)\*\*(?!\*)',
2708                 '__' => '(?<=\S)(?<!_)__(?![a-zA-Z0-9_])',
2709                 );
2710         var $em_strong_relist = array(
2711                 ''    => '(?:(?<!\*)\*\*\*(?!\*)|(?<![a-zA-Z0-9_])___(?!_))(?=\S)(?![.,:;]\s)',
2712                 '***' => '(?<=\S)(?<!\*)\*\*\*(?!\*)',
2713                 '___' => '(?<=\S)(?<!_)___(?![a-zA-Z0-9_])',
2714                 );
2715
2716
2717         function formParagraphs($text) {
2718         #
2719         #       Params:
2720         #               $text - string to process with html <p> tags
2721         #
2722                 # Strip leading and trailing lines:
2723                 $text = preg_replace('/\A\n+|\n+\z/', '', $text);
2724
2725                 $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY);
2726
2727                 #
2728                 # Wrap <p> tags and unhashify HTML blocks
2729                 #
2730                 foreach ($grafs as $key => $value) {
2731                         $value = trim($this->runSpanGamut($value));
2732
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);
2736
2737                         if ($is_p) {
2738                                 $value = "<p>$value</p>";
2739                         }
2740                         $grafs[$key] = $value;
2741                 }
2742
2743                 # Join grafs in one text, then unhash HTML tags.
2744                 $text = implode("\n\n", $grafs);
2745
2746                 # Finish by removing any tag hashes still present in $text.
2747                 $text = $this->unhash($text);
2748
2749                 return $text;
2750         }
2751
2752
2753         ### Footnotes
2754
2755         function stripFootnotes($text) {
2756         #
2757         # Strips link definitions from text, stores the URLs and titles in
2758         # hash references.
2759         #
2760                 $less_than_tab = $this->tab_width - 1;
2761
2762                 # Link defs are in the form: [^id]: url "optional title"
2763                 $text = preg_replace_callback('{
2764                         ^[ ]{0,'.$less_than_tab.'}\[\^(.+?)\][ ]?:      # note_id = $1
2765                           [ ]*
2766                           \n?                                   # maybe *one* newline
2767                         (                                               # text = $2 (no blank lines allowed)
2768                                 (?:
2769                                         .+                              # actual text
2770                                 |
2771                                         \n                              # newlines but
2772                                         (?!\[\^.+?\]:\s)# negative lookahead for footnote marker.
2773                                         (?!\n+[ ]{0,3}\S)# ensure line is not blank and followed
2774                                                                         # by non-indented content
2775                                 )*
2776                         )
2777                         }xm',
2778                         array(&$this, '_stripFootnotes_callback'),
2779                         $text);
2780                 return $text;
2781         }
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
2786         }
2787
2788
2789         function doFootnotes($text) {
2790         #
2791         # Replace footnote references in $text [^id] with a special text-token
2792         # which will be replaced by the actual footnote marker in appendFootnotes.
2793         #
2794                 if (!$this->in_anchor) {
2795                         $text = preg_replace('{\[\^(.+?)\]}', "F\x1Afn:\\1\x1A:", $text);
2796                 }
2797                 return $text;
2798         }
2799
2800
2801         function appendFootnotes($text) {
2802         #
2803         # Append footnote list to text.
2804         #
2805                 $text = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}',
2806                         array(&$this, '_appendFootnotes_callback'), $text);
2807
2808                 if (!empty($this->footnotes_ordered)) {
2809                         $text .= "\n\n";
2810                         $text .= "<div class=\"footnotes\">\n";
2811                         $text .= "<hr". MARKDOWN_EMPTY_ELEMENT_SUFFIX ."\n";
2812                         $text .= "<ol>\n\n";
2813
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\"";
2819                         }
2820                         if ($this->fn_backlink_title != "") {
2821                                 $title = $this->fn_backlink_title;
2822                                 $title = $this->encodeAttribute($title);
2823                                 $attr .= " title=\"$title\"";
2824                         }
2825                         $num = 0;
2826
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]);
2831
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);
2836
2837                                 $attr = str_replace("%%", ++$num, $attr);
2838                                 $note_id = $this->encodeAttribute($note_id);
2839
2840                                 # Add backlink to last paragraph; create new paragraph if needed.
2841                                 $backlink = "<a href=\"#fnref:$note_id\"$attr>&#8617;</a>";
2842                                 if (preg_match('{</p>$}', $footnote)) {
2843                                         $footnote = substr($footnote, 0, -4) . "&#160;$backlink</p>";
2844                                 } else {
2845                                         $footnote .= "\n\n<p>$backlink</p>";
2846                                 }
2847
2848                                 $text .= "<li id=\"fn:$note_id\">\n";
2849                                 $text .= $footnote . "\n";
2850                                 $text .= "</li>\n\n";
2851                         }
2852
2853                         $text .= "</ol>\n";
2854                         $text .= "</div>";
2855                 }
2856                 return $text;
2857         }
2858         function _appendFootnotes_callback($matches) {
2859                 $node_id = $this->fn_id_prefix . $matches[1];
2860
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]);
2867
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\"";
2874                         }
2875                         if ($this->fn_link_title != "") {
2876                                 $title = $this->fn_link_title;
2877                                 $title = $this->encodeAttribute($title);
2878                                 $attr .= " title=\"$title\"";
2879                         }
2880
2881                         $attr = str_replace("%%", $num, $attr);
2882                         $node_id = $this->encodeAttribute($node_id);
2883
2884                         return
2885                                 "<sup id=\"fnref:$node_id\">".
2886                                 "<a href=\"#fn:$node_id\"$attr>$num</a>".
2887                                 "</sup>";
2888                 }
2889
2890                 return "[^".$matches[1]."]";
2891         }
2892
2893
2894         ### Abbreviations ###
2895
2896         function stripAbbreviations($text) {
2897         #
2898         # Strips abbreviations from text, stores titles in hash references.
2899         #
2900                 $less_than_tab = $this->tab_width - 1;
2901
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)
2906                         }xm',
2907                         array(&$this, '_stripAbbreviations_callback'),
2908                         $text);
2909                 return $text;
2910         }
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
2919         }
2920
2921
2922         function doAbbreviations($text) {
2923         #
2924         # Find defined abbreviations in text and wrap them in <abbr> elements.
2925         #
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('{'.
2930                                 '(?<![\w\x1A])'.
2931                                 '(?:'.$this->abbr_word_re.')'.
2932                                 '(?![\w\x1A])'.
2933                                 '}',
2934                                 array(&$this, '_doAbbreviations_callback'), $text);
2935                 }
2936                 return $text;
2937         }
2938         function _doAbbreviations_callback($matches) {
2939                 $abbr = $matches[0];
2940                 if (isset($this->abbr_desciptions[$abbr])) {
2941                         $desc = $this->abbr_desciptions[$abbr];
2942                         if (empty($desc)) {
2943                                 return $this->hashPart("<abbr>$abbr</abbr>");
2944                         } else {
2945                                 $desc = $this->encodeAttribute($desc);
2946                                 return $this->hashPart("<abbr title=\"$desc\">$abbr</abbr>");
2947                         }
2948                 } else {
2949                         return $matches[0];
2950                 }
2951         }
2952
2953 }
2954
2955
2956 /*
2957
2958 PHP Markdown Extra
2959 ==================
2960
2961 Description
2962 -----------
2963
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.
2968
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.
2973
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).
2978
2979 For more information about Markdown's syntax, see:
2980
2981 <http://daringfireball.net/projects/markdown/>
2982
2983
2984 Bugs
2985 ----
2986
2987 To file bug reports please send email to:
2988
2989 <michel.fortin@michelf.com>
2990
2991 Please include with your report: (1) the example input; (2) the output you
2992 expected; (3) the output Markdown actually produced.
2993
2994
2995 Version History
2996 ---------------
2997
2998 See the readme file for detailed release notes for this version.
2999
3000
3001 Copyright and License
3002 ---------------------
3003
3004 PHP Markdown & Extra
3005 Copyright (c) 2004-2008 Michel Fortin
3006 <http://www.michelf.com/>
3007 All rights reserved.
3008
3009 Based on Markdown
3010 Copyright (c) 2003-2006 John Gruber
3011 <http://daringfireball.net/>
3012 All rights reserved.
3013
3014 Redistribution and use in source and binary forms, with or without
3015 modification, are permitted provided that the following conditions are
3016 met:
3017
3018 *       Redistributions of source code must retain the above copyright notice,
3019         this list of conditions and the following disclaimer.
3020
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.
3024
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.
3028
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.
3040
3041 */
3042 ?>