"Fossies" - the Fresh Open Source Software Archive

Member "yii-1.1.22.bf1d26/framework/vendors/markdown/markdown.php" (16 Jan 2020, 73555 Bytes) of package /linux/www/yii-1.1.22.bf1d26.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) PHP source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "markdown.php" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes report: 1.1.21.733ac5_vs_1.1.22.bf1d26.

    1 <?php
    2 #
    3 # Markdown Extra  -  A text-to-HTML conversion tool for web writers
    4 #
    5 # PHP Markdown & Extra
    6 # Copyright (c) 2004-2012 Michel Fortin  
    7 # <http://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 # Markdown Parser Class
   16 #
   17 
   18 class Markdown_Parser {
   19 
   20     # Regex to match balanced [brackets].
   21     # Needed to insert a maximum bracked depth while converting to PHP.
   22     public $nested_brackets_depth = 6;
   23     public $nested_brackets_re;
   24 
   25     public $nested_url_parenthesis_depth = 4;
   26     public $nested_url_parenthesis_re;
   27 
   28     # Table of hash values for escaped characters:
   29     public $escape_chars = '\`*_{}[]()>#+-.!';
   30     public $escape_chars_re;
   31 
   32     # Change to ">" for HTML output.
   33     public $empty_element_suffix = ' />';
   34     public $tab_width = 4;
   35 
   36     # Change to `true` to disallow markup or entities.
   37     public $no_markup = false;
   38     public $no_entities = false;
   39 
   40     # Predefined urls and titles for reference links and images.
   41     public $predef_urls = array();
   42     public $predef_titles = array();
   43 
   44     public function __construct() {
   45     #
   46     # Constructor function. Initialize appropriate member variables.
   47     #
   48         $this->prepareItalicsAndBold();
   49 
   50         $this->nested_brackets_re =
   51             str_repeat('(?>[^\[\]]+|\[', $this->nested_brackets_depth).
   52             str_repeat('\])*', $this->nested_brackets_depth);
   53 
   54         $this->nested_url_parenthesis_re =
   55             str_repeat('(?>[^()\s]+|\(', $this->nested_url_parenthesis_depth).
   56             str_repeat('(?>\)))*', $this->nested_url_parenthesis_depth);
   57 
   58         $this->escape_chars_re = '['.preg_quote($this->escape_chars).']';
   59 
   60         # Sort document, block, and span gamut in ascendent priority order.
   61         asort($this->document_gamut);
   62         asort($this->block_gamut);
   63         asort($this->span_gamut);
   64     }
   65 
   66 
   67     # Internal hashes used during transformation.
   68     public $urls = array();
   69     public $titles = array();
   70     public $html_hashes = array();
   71 
   72     # Status flag to avoid invalid nesting.
   73     public $in_anchor = false;
   74 
   75 
   76     public function setup() {
   77     #
   78     # Called before the transformation process starts to setup parser
   79     # states.
   80     #
   81         # Clear global hashes.
   82         $this->urls = $this->predef_urls;
   83         $this->titles = $this->predef_titles;
   84         $this->html_hashes = array();
   85 
   86         $in_anchor = false;
   87     }
   88 
   89     public function teardown() {
   90     #
   91     # Called after the transformation process to clear any variable
   92     # which may be taking up memory unnecessarly.
   93     #
   94         $this->urls = array();
   95         $this->titles = array();
   96         $this->html_hashes = array();
   97     }
   98 
   99 
  100     public function transform($text) {
  101     #
  102     # Main function. Performs some preprocessing on the input text
  103     # and pass it through the document gamut.
  104     #
  105         $this->setup();
  106 
  107         # Remove UTF-8 BOM and marker character in input, if present.
  108         $text = preg_replace('{^\xEF\xBB\xBF|\x1A}', '', $text);
  109 
  110         # Standardize line endings:
  111         #   DOS to Unix and Mac to Unix
  112         $text = preg_replace('{\r\n?}', "\n", $text);
  113 
  114         # Make sure $text ends with a couple of newlines:
  115         $text .= "\n\n";
  116 
  117         # Convert all tabs to spaces.
  118         $text = $this->detab($text);
  119 
  120         # Turn block-level HTML blocks into hash entries
  121         $text = $this->hashHTMLBlocks($text);
  122 
  123         # Strip any lines consisting only of spaces and tabs.
  124         # This makes subsequent regexen easier to write, because we can
  125         # match consecutive blank lines with /\n+/ instead of something
  126         # contorted like /[ ]*\n+/ .
  127         $text = preg_replace('/^[ ]+$/m', '', $text);
  128 
  129         # Run document gamut methods.
  130         foreach ($this->document_gamut as $method => $priority) {
  131             $text = $this->$method($text);
  132         }
  133 
  134         $this->teardown();
  135 
  136         return $text . "\n";
  137     }
  138 
  139     public $document_gamut = array(
  140         # Strip link definitions, store in hashes.
  141         "stripLinkDefinitions" => 20,
  142 
  143         "runBasicBlockGamut"   => 30,
  144         );
  145 
  146 
  147     public function stripLinkDefinitions($text) {
  148     #
  149     # Strips link definitions from text, stores the URLs and titles in
  150     # hash references.
  151     #
  152         $less_than_tab = $this->tab_width - 1;
  153 
  154         # Link defs are in the form: ^[id]: url "optional title"
  155         $text = preg_replace_callback('{
  156                             ^[ ]{0,'.$less_than_tab.'}\[(.+)\][ ]?: # id = $1
  157                               [ ]*
  158                               \n?               # maybe *one* newline
  159                               [ ]*
  160                             (?:
  161                               <(.+?)>           # url = $2
  162                             |
  163                               (\S+?)            # url = $3
  164                             )
  165                               [ ]*
  166                               \n?               # maybe one newline
  167                               [ ]*
  168                             (?:
  169                                 (?<=\s)         # lookbehind for whitespace
  170                                 ["(]
  171                                 (.*?)           # title = $4
  172                                 [")]
  173                                 [ ]*
  174                             )?  # title is optional
  175                             (?:\n+|\Z)
  176             }xm',
  177             array(&$this, '_stripLinkDefinitions_callback'),
  178             $text);
  179         return $text;
  180     }
  181     public function _stripLinkDefinitions_callback($matches) {
  182         $link_id = strtolower($matches[1]);
  183         $url = $matches[2] == '' ? $matches[3] : $matches[2];
  184         $this->urls[$link_id] = $url;
  185         $this->titles[$link_id] =& $matches[4];
  186         return ''; # String that will replace the block
  187     }
  188 
  189 
  190     public function hashHTMLBlocks($text) {
  191         if ($this->no_markup)  return $text;
  192 
  193         $less_than_tab = $this->tab_width - 1;
  194 
  195         # Hashify HTML blocks:
  196         # We only want to do this for block-level HTML tags, such as headers,
  197         # lists, and tables. That's because we still want to wrap <p>s around
  198         # "paragraphs" that are wrapped in non-block-level tags, such as anchors,
  199         # phrase emphasis, and spans. The list of tags we're looking for is
  200         # hard-coded:
  201         #
  202         # *  List "a" is made of tags which can be both inline or block-level.
  203         #    These will be treated block-level when the start tag is alone on
  204         #    its line, otherwise they're not matched here and will be taken as
  205         #    inline later.
  206         # *  List "b" is made of tags which are always block-level;
  207         #
  208         $block_tags_a_re = 'ins|del';
  209         $block_tags_b_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|'.
  210                            'script|noscript|form|fieldset|iframe|math';
  211 
  212         # Regular expression for the content of a block tag.
  213         $nested_tags_level = 4;
  214         $attr = '
  215             (?>             # optional tag attributes
  216               \s            # starts with whitespace
  217               (?>
  218                 [^>"/]+     # text outside quotes
  219               |
  220                 /+(?!>)     # slash not followed by ">"
  221               |
  222                 "[^"]*"     # text inside double quotes (tolerate ">")
  223               |
  224                 \'[^\']*\'  # text inside single quotes (tolerate ">")
  225               )*
  226             )?
  227             ';
  228         $content =
  229             str_repeat('
  230                 (?>
  231                   [^<]+         # content without tag
  232                 |
  233                   <\2           # nested opening tag
  234                     '.$attr.'   # attributes
  235                     (?>
  236                       />
  237                     |
  238                       >', $nested_tags_level).  # end of opening tag
  239                       '.*?'.                    # last level nested tag content
  240             str_repeat('
  241                       </\2\s*>  # closing nested tag
  242                     )
  243                   |
  244                     <(?!/\2\s*> # other tags with a different name
  245                   )
  246                 )*',
  247                 $nested_tags_level);
  248         $content2 = str_replace('\2', '\3', $content);
  249 
  250         # First, look for nested blocks, e.g.:
  251         #   <div>
  252         #       <div>
  253         #       tags for inner block must be indented.
  254         #       </div>
  255         #   </div>
  256         #
  257         # The outermost tags must start at the left margin for this to match, and
  258         # the inner nested divs must be indented.
  259         # We need to do this before the next, more liberal match, because the next
  260         # match will start at the first `<div>` and stop at the first `</div>`.
  261         $text = preg_replace_callback('{(?>
  262             (?>
  263                 (?<=\n\n)       # Starting after a blank line
  264                 |               # or
  265                 \A\n?           # the beginning of the doc
  266             )
  267             (                       # save in $1
  268 
  269               # Match from `\n<tag>` to `</tag>\n`, handling nested tags
  270               # in between.
  271 
  272                         [ ]{0,'.$less_than_tab.'}
  273                         <('.$block_tags_b_re.')# start tag = $2
  274                         '.$attr.'>          # attributes followed by > and \n
  275                         '.$content.'        # content, support nesting
  276                         </\2>               # the matching end tag
  277                         [ ]*                # trailing spaces/tabs
  278                         (?=\n+|\Z)  # followed by a newline or end of document
  279 
  280             | # Special version for tags of group a.
  281 
  282                         [ ]{0,'.$less_than_tab.'}
  283                         <('.$block_tags_a_re.')# start tag = $3
  284                         '.$attr.'>[ ]*\n    # attributes followed by >
  285                         '.$content2.'       # content, support nesting
  286                         </\3>               # the matching end tag
  287                         [ ]*                # trailing spaces/tabs
  288                         (?=\n+|\Z)  # followed by a newline or end of document
  289 
  290             | # Special case just for <hr />. It was easier to make a special
  291               # case than to make the other regex more complicated.
  292 
  293                         [ ]{0,'.$less_than_tab.'}
  294                         <(hr)               # start tag = $2
  295                         '.$attr.'           # attributes
  296                         /?>                 # the matching end tag
  297                         [ ]*
  298                         (?=\n{2,}|\Z)       # followed by a blank line or end of document
  299 
  300             | # Special case for standalone HTML comments:
  301 
  302                     [ ]{0,'.$less_than_tab.'}
  303                     (?s:
  304                         <!-- .*? -->
  305                     )
  306                     [ ]*
  307                     (?=\n{2,}|\Z)       # followed by a blank line or end of document
  308 
  309             | # PHP and ASP-style processor instructions (<? and <%)
  310 
  311                     [ ]{0,'.$less_than_tab.'}
  312                     (?s:
  313                         <([?%])         # $2
  314                         .*?
  315                         \2>
  316                     )
  317                     [ ]*
  318                     (?=\n{2,}|\Z)       # followed by a blank line or end of document
  319 
  320             )
  321             )}Sxmi',
  322             array(&$this, '_hashHTMLBlocks_callback'),
  323             $text);
  324 
  325         return $text;
  326     }
  327     public function _hashHTMLBlocks_callback($matches) {
  328         $text = $matches[1];
  329         $key  = $this->hashBlock($text);
  330         return "\n\n$key\n\n";
  331     }
  332 
  333 
  334     public function hashPart($text, $boundary = 'X') {
  335     #
  336     # Called whenever a tag must be hashed when a function insert an atomic
  337     # element in the text stream. Passing $text to through this function gives
  338     # a unique text-token which will be reverted back when calling unhash.
  339     #
  340     # The $boundary argument specify what character should be used to surround
  341     # the token. By convension, "B" is used for block elements that needs not
  342     # to be wrapped into paragraph tags at the end, ":" is used for elements
  343     # that are word separators and "X" is used in the general case.
  344     #
  345         # Swap back any tag hash found in $text so we do not have to `unhash`
  346         # multiple times at the end.
  347         $text = $this->unhash($text);
  348 
  349         # Then hash the block.
  350         static $i = 0;
  351         $key = "$boundary\x1A" . ++$i . $boundary;
  352         $this->html_hashes[$key] = $text;
  353         return $key; # String that will replace the tag.
  354     }
  355 
  356 
  357     public function hashBlock($text) {
  358     #
  359     # Shortcut function for hashPart with block-level boundaries.
  360     #
  361         return $this->hashPart($text, 'B');
  362     }
  363 
  364 
  365     public $block_gamut = array(
  366     #
  367     # These are all the transformations that form block-level
  368     # tags like paragraphs, headers, and list items.
  369     #
  370         "doHeaders"         => 10,
  371         "doHorizontalRules" => 20,
  372 
  373         "doLists"           => 40,
  374         "doCodeBlocks"      => 50,
  375         "doBlockQuotes"     => 60,
  376         );
  377 
  378     public function runBlockGamut($text) {
  379     #
  380     # Run block gamut tranformations.
  381     #
  382         # We need to escape raw HTML in Markdown source before doing anything
  383         # else. This need to be done for each block, and not only at the
  384         # begining in the Markdown function since hashed blocks can be part of
  385         # list items and could have been indented. Indented blocks would have
  386         # been seen as a code block in a previous pass of hashHTMLBlocks.
  387         $text = $this->hashHTMLBlocks($text);
  388 
  389         return $this->runBasicBlockGamut($text);
  390     }
  391 
  392     public function runBasicBlockGamut($text) {
  393     #
  394     # Run block gamut tranformations, without hashing HTML blocks. This is
  395     # useful when HTML blocks are known to be already hashed, like in the first
  396     # whole-document pass.
  397     #
  398         foreach ($this->block_gamut as $method => $priority) {
  399             $text = $this->$method($text);
  400         }
  401 
  402         # Finally form paragraph and restore hashed blocks.
  403         $text = $this->formParagraphs($text);
  404 
  405         return $text;
  406     }
  407 
  408 
  409     public function doHorizontalRules($text) {
  410         # Do Horizontal Rules:
  411         return preg_replace(
  412             '{
  413                 ^[ ]{0,3}   # Leading space
  414                 ([-*_])     # $1: First marker
  415                 (?>         # Repeated marker group
  416                     [ ]{0,2}    # Zero, one, or two spaces.
  417                     \1          # Marker character
  418                 ){2,}       # Group repeated at least twice
  419                 [ ]*        # Tailing spaces
  420                 $           # End of line.
  421             }mx',
  422             "\n".$this->hashBlock("<hr$this->empty_element_suffix")."\n",
  423             $text);
  424     }
  425 
  426 
  427     public $span_gamut = array(
  428     #
  429     # These are all the transformations that occur *within* block-level
  430     # tags like paragraphs, headers, and list items.
  431     #
  432         # Process character escapes, code spans, and inline HTML
  433         # in one shot.
  434         "parseSpan"           => -30,
  435 
  436         # Process anchor and image tags. Images must come first,
  437         # because ![foo][f] looks like an anchor.
  438         "doImages"            =>  10,
  439         "doAnchors"           =>  20,
  440 
  441         # Make links out of things like `<http://example.com/>`
  442         # Must come after doAnchors, because you can use < and >
  443         # delimiters in inline links like [this](<url>).
  444         "doAutoLinks"         =>  30,
  445         "encodeAmpsAndAngles" =>  40,
  446 
  447         "doItalicsAndBold"    =>  50,
  448         "doHardBreaks"        =>  60,
  449         );
  450 
  451     public function runSpanGamut($text) {
  452     #
  453     # Run span gamut tranformations.
  454     #
  455         foreach ($this->span_gamut as $method => $priority) {
  456             $text = $this->$method($text);
  457         }
  458 
  459         return $text;
  460     }
  461 
  462 
  463     public function doHardBreaks($text) {
  464         # Do hard breaks:
  465         return preg_replace_callback('/ {2,}\n/',
  466             array(&$this, '_doHardBreaks_callback'), $text);
  467     }
  468     public function _doHardBreaks_callback($matches) {
  469         return $this->hashPart("<br$this->empty_element_suffix\n");
  470     }
  471 
  472 
  473     public function doAnchors($text) {
  474     #
  475     # Turn Markdown link shortcuts into XHTML <a> tags.
  476     #
  477         if ($this->in_anchor) return $text;
  478         $this->in_anchor = true;
  479 
  480         #
  481         # First, handle reference-style links: [link text] [id]
  482         #
  483         $text = preg_replace_callback('{
  484             (                   # wrap whole match in $1
  485               \[
  486                 ('.$this->nested_brackets_re.') # link text = $2
  487               \]
  488 
  489               [ ]?              # one optional space
  490               (?:\n[ ]*)?       # one optional newline followed by spaces
  491 
  492               \[
  493                 (.*?)       # id = $3
  494               \]
  495             )
  496             }xs',
  497             array(&$this, '_doAnchors_reference_callback'), $text);
  498 
  499         #
  500         # Next, inline-style links: [link text](url "optional title")
  501         #
  502         $text = preg_replace_callback('{
  503             (               # wrap whole match in $1
  504               \[
  505                 ('.$this->nested_brackets_re.') # link text = $2
  506               \]
  507               \(            # literal paren
  508                 [ \n]*
  509                 (?:
  510                     <(.+?)> # href = $3
  511                 |
  512                     ('.$this->nested_url_parenthesis_re.')  # href = $4
  513                 )
  514                 [ \n]*
  515                 (           # $5
  516                   ([\'"])   # quote char = $6
  517                   (.*?)     # Title = $7
  518                   \6        # matching quote
  519                   [ \n]*    # ignore any spaces/tabs between closing quote and )
  520                 )?          # title is optional
  521               \)
  522             )
  523             }xs',
  524             array(&$this, '_doAnchors_inline_callback'), $text);
  525 
  526         #
  527         # Last, handle reference-style shortcuts: [link text]
  528         # These must come last in case you've also got [link text][1]
  529         # or [link text](/foo)
  530         #
  531         $text = preg_replace_callback('{
  532             (                   # wrap whole match in $1
  533               \[
  534                 ([^\[\]]+)      # link text = $2; can\'t contain [ or ]
  535               \]
  536             )
  537             }xs',
  538             array(&$this, '_doAnchors_reference_callback'), $text);
  539 
  540         $this->in_anchor = false;
  541         return $text;
  542     }
  543     public function _doAnchors_reference_callback($matches) {
  544         $whole_match =  $matches[1];
  545         $link_text   =  $matches[2];
  546         $link_id     =& $matches[3];
  547 
  548         if ($link_id == "") {
  549             # for shortcut links like [this][] or [this].
  550             $link_id = $link_text;
  551         }
  552 
  553         # lower-case and turn embedded newlines into spaces
  554         $link_id = strtolower($link_id);
  555         $link_id = preg_replace('{[ ]?\n}', ' ', $link_id);
  556 
  557         if (isset($this->urls[$link_id])) {
  558             $url = $this->urls[$link_id];
  559             $url = $this->encodeAttribute($url);
  560 
  561             $result = "<a href=\"$url\"";
  562             if ( isset( $this->titles[$link_id] ) ) {
  563                 $title = $this->titles[$link_id];
  564                 $title = $this->encodeAttribute($title);
  565                 $result .=  " title=\"$title\"";
  566             }
  567 
  568             $link_text = $this->runSpanGamut($link_text);
  569             $result .= ">$link_text</a>";
  570             $result = $this->hashPart($result);
  571         }
  572         else {
  573             $result = $whole_match;
  574         }
  575         return $result;
  576     }
  577     public function _doAnchors_inline_callback($matches) {
  578         $whole_match    =  $matches[1];
  579         $link_text      =  $this->runSpanGamut($matches[2]);
  580         $url            =  $matches[3] == '' ? $matches[4] : $matches[3];
  581         $title          =& $matches[7];
  582 
  583         $url = $this->encodeAttribute($url);
  584 
  585         $result = "<a href=\"$url\"";
  586         if (isset($title)) {
  587             $title = $this->encodeAttribute($title);
  588             $result .=  " title=\"$title\"";
  589         }
  590 
  591         $link_text = $this->runSpanGamut($link_text);
  592         $result .= ">$link_text</a>";
  593 
  594         return $this->hashPart($result);
  595     }
  596 
  597 
  598     public function doImages($text) {
  599     #
  600     # Turn Markdown image shortcuts into <img> tags.
  601     #
  602         #
  603         # First, handle reference-style labeled images: ![alt text][id]
  604         #
  605         $text = preg_replace_callback('{
  606             (               # wrap whole match in $1
  607               !\[
  608                 ('.$this->nested_brackets_re.')     # alt text = $2
  609               \]
  610 
  611               [ ]?              # one optional space
  612               (?:\n[ ]*)?       # one optional newline followed by spaces
  613 
  614               \[
  615                 (.*?)       # id = $3
  616               \]
  617 
  618             )
  619             }xs',
  620             array(&$this, '_doImages_reference_callback'), $text);
  621 
  622         #
  623         # Next, handle inline images:  ![alt text](url "optional title")
  624         # Don't forget: encode * and _
  625         #
  626         $text = preg_replace_callback('{
  627             (               # wrap whole match in $1
  628               !\[
  629                 ('.$this->nested_brackets_re.')     # alt text = $2
  630               \]
  631               \s?           # One optional whitespace character
  632               \(            # literal paren
  633                 [ \n]*
  634                 (?:
  635                     <(\S*)> # src url = $3
  636                 |
  637                     ('.$this->nested_url_parenthesis_re.')  # src url = $4
  638                 )
  639                 [ \n]*
  640                 (           # $5
  641                   ([\'"])   # quote char = $6
  642                   (.*?)     # title = $7
  643                   \6        # matching quote
  644                   [ \n]*
  645                 )?          # title is optional
  646               \)
  647             )
  648             }xs',
  649             array(&$this, '_doImages_inline_callback'), $text);
  650 
  651         return $text;
  652     }
  653     public function _doImages_reference_callback($matches) {
  654         $whole_match = $matches[1];
  655         $alt_text    = $matches[2];
  656         $link_id     = strtolower($matches[3]);
  657 
  658         if ($link_id == "") {
  659             $link_id = strtolower($alt_text); # for shortcut links like ![this][].
  660         }
  661 
  662         $alt_text = $this->encodeAttribute($alt_text);
  663         if (isset($this->urls[$link_id])) {
  664             $url = $this->encodeAttribute($this->urls[$link_id]);
  665             $result = "<img src=\"$url\" alt=\"$alt_text\"";
  666             if (isset($this->titles[$link_id])) {
  667                 $title = $this->titles[$link_id];
  668                 $title = $this->encodeAttribute($title);
  669                 $result .=  " title=\"$title\"";
  670             }
  671             $result .= $this->empty_element_suffix;
  672             $result = $this->hashPart($result);
  673         }
  674         else {
  675             # If there's no such link ID, leave intact:
  676             $result = $whole_match;
  677         }
  678 
  679         return $result;
  680     }
  681     public function _doImages_inline_callback($matches) {
  682         $whole_match    = $matches[1];
  683         $alt_text       = $matches[2];
  684         $url            = $matches[3] == '' ? $matches[4] : $matches[3];
  685         $title          =& $matches[7];
  686 
  687         $alt_text = $this->encodeAttribute($alt_text);
  688         $url = $this->encodeAttribute($url);
  689         $result = "<img src=\"$url\" alt=\"$alt_text\"";
  690         if (isset($title)) {
  691             $title = $this->encodeAttribute($title);
  692             $result .=  " title=\"$title\""; # $title already quoted
  693         }
  694         $result .= $this->empty_element_suffix;
  695 
  696         return $this->hashPart($result);
  697     }
  698 
  699 
  700     public function doHeaders($text) {
  701         # Setext-style headers:
  702         #     Header 1
  703         #     ========
  704         #
  705         #     Header 2
  706         #     --------
  707         #
  708         $text = preg_replace_callback('{ ^(.+?)[ ]*\n(=+|-+)[ ]*\n+ }mx',
  709             array(&$this, '_doHeaders_callback_setext'), $text);
  710 
  711         # atx-style headers:
  712         #   # Header 1
  713         #   ## Header 2
  714         #   ## Header 2 with closing hashes ##
  715         #   ...
  716         #   ###### Header 6
  717         #
  718         $text = preg_replace_callback('{
  719                 ^(\#{1,6})  # $1 = string of #\'s
  720                 [ ]*
  721                 (.+?)       # $2 = Header text
  722                 [ ]*
  723                 \#*         # optional closing #\'s (not counted)
  724                 \n+
  725             }xm',
  726             array(&$this, '_doHeaders_callback_atx'), $text);
  727 
  728         return $text;
  729     }
  730     public function _doHeaders_callback_setext($matches) {
  731         # Terrible hack to check we haven't found an empty list item.
  732         if ($matches[2] == '-' && preg_match('{^-(?: |$)}', $matches[1]))
  733             return $matches[0];
  734 
  735         $level = $matches[2][0] == '=' ? 1 : 2;
  736         $block = "<h$level>".$this->runSpanGamut($matches[1])."</h$level>";
  737         return "\n" . $this->hashBlock($block) . "\n\n";
  738     }
  739     public function _doHeaders_callback_atx($matches) {
  740         $level = strlen($matches[1]);
  741         $block = "<h$level>".$this->runSpanGamut($matches[2])."</h$level>";
  742         return "\n" . $this->hashBlock($block) . "\n\n";
  743     }
  744 
  745 
  746     public function doLists($text) {
  747     #
  748     # Form HTML ordered (numbered) and unordered (bulleted) lists.
  749     #
  750         $less_than_tab = $this->tab_width - 1;
  751 
  752         # Re-usable patterns to match list item bullets and number markers:
  753         $marker_ul_re  = '[*+-]';
  754         $marker_ol_re  = '\d+[\.]';
  755         $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)";
  756 
  757         $markers_relist = array(
  758             $marker_ul_re => $marker_ol_re,
  759             $marker_ol_re => $marker_ul_re,
  760             );
  761 
  762         foreach ($markers_relist as $marker_re => $other_marker_re) {
  763             # Re-usable pattern to match any entirel ul or ol list:
  764             $whole_list_re = '
  765                 (                               # $1 = whole list
  766                   (                             # $2
  767                     ([ ]{0,'.$less_than_tab.'}) # $3 = number of spaces
  768                     ('.$marker_re.')            # $4 = first list item marker
  769                     [ ]+
  770                   )
  771                   (?s:.+?)
  772                   (                             # $5
  773                       \z
  774                     |
  775                       \n{2,}
  776                       (?=\S)
  777                       (?!                       # Negative lookahead for another list item marker
  778                         [ ]*
  779                         '.$marker_re.'[ ]+
  780                       )
  781                     |
  782                       (?=                       # Lookahead for another kind of list
  783                         \n
  784                         \3                      # Must have the same indentation
  785                         '.$other_marker_re.'[ ]+
  786                       )
  787                   )
  788                 )
  789             '; // mx
  790 
  791             # We use a different prefix before nested lists than top-level lists.
  792             # See extended comment in _ProcessListItems().
  793 
  794             if ($this->list_level) {
  795                 $text = preg_replace_callback('{
  796                         ^
  797                         '.$whole_list_re.'
  798                     }mx',
  799                     array(&$this, '_doLists_callback'), $text);
  800             }
  801             else {
  802                 $text = preg_replace_callback('{
  803                         (?:(?<=\n)\n|\A\n?) # Must eat the newline
  804                         '.$whole_list_re.'
  805                     }mx',
  806                     array(&$this, '_doLists_callback'), $text);
  807             }
  808         }
  809 
  810         return $text;
  811     }
  812     
  813     public function _doLists_callback($matches) {
  814         # Re-usable patterns to match list item bullets and number markers:
  815         $marker_ul_re  = '[*+-]';
  816         $marker_ol_re  = '\d+[\.]';
  817         $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)";
  818         
  819         $list = $matches[1];
  820         $list_type = preg_match("/$marker_ul_re/", $matches[4]) ? "ul" : "ol";
  821         
  822         $marker_any_re = ( $list_type == "ul" ? $marker_ul_re : $marker_ol_re );
  823         
  824         $list .= "\n";
  825         $result = $this->processListItems($list, $marker_any_re);
  826         
  827         $result = $this->hashBlock("<$list_type>\n" . $result . "</$list_type>");
  828         return "\n". $result ."\n\n";
  829     }
  830 
  831     var $list_level = 0;
  832 
  833     public function processListItems($list_str, $marker_any_re) {
  834     #
  835     #   Process the contents of a single ordered or unordered list, splitting it
  836     #   into individual list items.
  837     #
  838         # The $this->list_level global keeps track of when we're inside a list.
  839         # Each time we enter a list, we increment it; when we leave a list,
  840         # we decrement. If it's zero, we're not in a list anymore.
  841         #
  842         # We do this because when we're not inside a list, we want to treat
  843         # something like this:
  844         #
  845         #       I recommend upgrading to version
  846         #       8. Oops, now this line is treated
  847         #       as a sub-list.
  848         #
  849         # As a single paragraph, despite the fact that the second line starts
  850         # with a digit-period-space sequence.
  851         #
  852         # Whereas when we're inside a list (or sub-list), that line will be
  853         # treated as the start of a sub-list. What a kludge, huh? This is
  854         # an aspect of Markdown's syntax that's hard to parse perfectly
  855         # without resorting to mind-reading. Perhaps the solution is to
  856         # change the syntax rules such that sub-lists must start with a
  857         # starting cardinal number; e.g. "1." or "a.".
  858 
  859         $this->list_level++;
  860 
  861         # trim trailing blank lines:
  862         $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str);
  863 
  864         $list_str = preg_replace_callback('{
  865             (\n)?                           # leading line = $1
  866             (^[ ]*)                         # leading whitespace = $2
  867             ('.$marker_any_re.'             # list marker and space = $3
  868                 (?:[ ]+|(?=\n)) # space only required if item is not empty
  869             )
  870             ((?s:.*?))                      # list item text   = $4
  871             (?:(\n+(?=\n))|\n)              # tailing blank line = $5
  872             (?= \n* (\z | \2 ('.$marker_any_re.') (?:[ ]+|(?=\n))))
  873             }xm',
  874             array(&$this, '_processListItems_callback'), $list_str);
  875 
  876         $this->list_level--;
  877         return $list_str;
  878     }
  879     public function _processListItems_callback($matches) {
  880         $item = $matches[4];
  881         $leading_line =& $matches[1];
  882         $leading_space =& $matches[2];
  883         $marker_space = $matches[3];
  884         $tailing_blank_line =& $matches[5];
  885 
  886         if ($leading_line || $tailing_blank_line ||
  887             preg_match('/\n{2,}/', $item))
  888         {
  889             # Replace marker with the appropriate whitespace indentation
  890             $item = $leading_space . str_repeat(' ', strlen($marker_space)) . $item;
  891             $item = $this->runBlockGamut($this->outdent($item)."\n");
  892         }
  893         else {
  894             # Recursion for sub-lists:
  895             $item = $this->doLists($this->outdent($item));
  896             $item = preg_replace('/\n+$/', '', $item);
  897             $item = $this->runSpanGamut($item);
  898         }
  899 
  900         return "<li>" . $item . "</li>\n";
  901     }
  902 
  903 
  904     public function doCodeBlocks($text) {
  905     #
  906     #   Process Markdown `<pre><code>` blocks.
  907     #
  908         $text = preg_replace_callback('{
  909                 (?:\n\n|\A\n?)
  910                 (               # $1 = the code block -- one or more lines, starting with a space/tab
  911                   (?>
  912                     [ ]{'.$this->tab_width.'}  # Lines must start with a tab or a tab-width of spaces
  913                     .*\n+
  914                   )+
  915                 )
  916                 ((?=^[ ]{0,'.$this->tab_width.'}\S)|\Z) # Lookahead for non-space at line-start, or end of doc
  917             }xm',
  918             array(&$this, '_doCodeBlocks_callback'), $text);
  919 
  920         return $text;
  921     }
  922     public function _doCodeBlocks_callback($matches) {
  923         $codeblock = $matches[1];
  924 
  925         $codeblock = $this->outdent($codeblock);
  926         $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES);
  927 
  928         # trim leading newlines and trailing newlines
  929         $codeblock = preg_replace('/\A\n+|\n+\z/', '', $codeblock);
  930 
  931         $codeblock = "<pre><code>$codeblock\n</code></pre>";
  932         return "\n\n".$this->hashBlock($codeblock)."\n\n";
  933     }
  934 
  935 
  936     public function makeCodeSpan($code) {
  937     #
  938     # Create a code span markup for $code. Called from handleSpanToken.
  939     #
  940         $code = htmlspecialchars(trim($code), ENT_NOQUOTES);
  941         return $this->hashPart("<code>$code</code>");
  942     }
  943 
  944 
  945     public $em_relist = array(
  946         ''  => '(?:(?<!\*)\*(?!\*)|(?<!_)_(?!_))(?=\S|$)(?![\.,:;]\s)',
  947         '*' => '(?<=\S|^)(?<!\*)\*(?!\*)',
  948         '_' => '(?<=\S|^)(?<!_)_(?!_)',
  949         );
  950     public $strong_relist = array(
  951         ''   => '(?:(?<!\*)\*\*(?!\*)|(?<!_)__(?!_))(?=\S|$)(?![\.,:;]\s)',
  952         '**' => '(?<=\S|^)(?<!\*)\*\*(?!\*)',
  953         '__' => '(?<=\S|^)(?<!_)__(?!_)',
  954         );
  955     public $em_strong_relist = array(
  956         ''    => '(?:(?<!\*)\*\*\*(?!\*)|(?<!_)___(?!_))(?=\S|$)(?![\.,:;]\s)',
  957         '***' => '(?<=\S|^)(?<!\*)\*\*\*(?!\*)',
  958         '___' => '(?<=\S|^)(?<!_)___(?!_)',
  959         );
  960     public $em_strong_prepared_relist;
  961     
  962     public function prepareItalicsAndBold() {
  963     #
  964     # Prepare regular expressions for searching emphasis tokens in any
  965     # context.
  966     #
  967         foreach ($this->em_relist as $em => $em_re) {
  968             foreach ($this->strong_relist as $strong => $strong_re) {
  969                 # Construct list of allowed token expressions.
  970                 $token_relist = array();
  971                 if (isset($this->em_strong_relist["$em$strong"])) {
  972                     $token_relist[] = $this->em_strong_relist["$em$strong"];
  973                 }
  974                 $token_relist[] = $em_re;
  975                 $token_relist[] = $strong_re;
  976                 
  977                 # Construct master expression from list.
  978                 $token_re = '{('. implode('|', $token_relist) .')}';
  979                 $this->em_strong_prepared_relist["$em$strong"] = $token_re;
  980             }
  981         }
  982     }
  983     
  984     public function doItalicsAndBold($text) {
  985         $token_stack = array('');
  986         $text_stack = array('');
  987         $em = '';
  988         $strong = '';
  989         $tree_char_em = false;
  990         
  991         while (1) {
  992             #
  993             # Get prepared regular expression for seraching emphasis tokens
  994             # in current context.
  995             #
  996             $token_re = $this->em_strong_prepared_relist["$em$strong"];
  997             
  998             #
  999             # Each loop iteration search for the next emphasis token. 
 1000             # Each token is then passed to handleSpanToken.
 1001             #
 1002             $parts = preg_split($token_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE);
 1003             $text_stack[0] .= $parts[0];
 1004             $token =& $parts[1];
 1005             $text =& $parts[2];
 1006             
 1007             if (empty($token)) {
 1008                 # Reached end of text span: empty stack without emitting.
 1009                 # any more emphasis.
 1010                 while ($token_stack[0]) {
 1011                     $text_stack[1] .= array_shift($token_stack);
 1012                     $text_stack[0] .= array_shift($text_stack);
 1013                 }
 1014                 break;
 1015             }
 1016 
 1017             $token_len = strlen($token);
 1018             if ($tree_char_em) {
 1019                 # Reached closing marker while inside a three-char emphasis.
 1020                 if ($token_len == 3) {
 1021                     # Three-char closing marker, close em and strong.
 1022                     array_shift($token_stack);
 1023                     $span = array_shift($text_stack);
 1024                     $span = $this->runSpanGamut($span);
 1025                     $span = "<strong><em>$span</em></strong>";
 1026                     $text_stack[0] .= $this->hashPart($span);
 1027                     $em = '';
 1028                     $strong = '';
 1029                 } else {
 1030                     # Other closing marker: close one em or strong and
 1031                     # change current token state to match the other
 1032                     $token_stack[0] = str_repeat($token[0], 3-$token_len);
 1033                     $tag = $token_len == 2 ? "strong" : "em";
 1034                     $span = $text_stack[0];
 1035                     $span = $this->runSpanGamut($span);
 1036                     $span = "<$tag>$span</$tag>";
 1037                     $text_stack[0] = $this->hashPart($span);
 1038                     $$tag = ''; # $$tag stands for $em or $strong
 1039                 }
 1040                 $tree_char_em = false;
 1041             } else if ($token_len == 3) {
 1042                 if ($em) {
 1043                     # Reached closing marker for both em and strong.
 1044                     # Closing strong marker:
 1045                     for ($i = 0; $i < 2; ++$i) {
 1046                         $shifted_token = array_shift($token_stack);
 1047                         $tag = strlen($shifted_token) == 2 ? "strong" : "em";
 1048                         $span = array_shift($text_stack);
 1049                         $span = $this->runSpanGamut($span);
 1050                         $span = "<$tag>$span</$tag>";
 1051                         $text_stack[0] .= $this->hashPart($span);
 1052                         $$tag = ''; # $$tag stands for $em or $strong
 1053                     }
 1054                 } else {
 1055                     # Reached opening three-char emphasis marker. Push on token
 1056                     # stack; will be handled by the special condition above.
 1057                     $em = $token[0];
 1058                     $strong = "$em$em";
 1059                     array_unshift($token_stack, $token);
 1060                     array_unshift($text_stack, '');
 1061                     $tree_char_em = true;
 1062                 }
 1063             } else if ($token_len == 2) {
 1064                 if ($strong) {
 1065                     # Unwind any dangling emphasis marker:
 1066                     if (strlen($token_stack[0]) == 1) {
 1067                         $text_stack[1] .= array_shift($token_stack);
 1068                         $text_stack[0] .= array_shift($text_stack);
 1069                     }
 1070                     # Closing strong marker:
 1071                     array_shift($token_stack);
 1072                     $span = array_shift($text_stack);
 1073                     $span = $this->runSpanGamut($span);
 1074                     $span = "<strong>$span</strong>";
 1075                     $text_stack[0] .= $this->hashPart($span);
 1076                     $strong = '';
 1077                 } else {
 1078                     array_unshift($token_stack, $token);
 1079                     array_unshift($text_stack, '');
 1080                     $strong = $token;
 1081                 }
 1082             } else {
 1083                 # Here $token_len == 1
 1084                 if ($em) {
 1085                     if (strlen($token_stack[0]) == 1) {
 1086                         # Closing emphasis marker:
 1087                         array_shift($token_stack);
 1088                         $span = array_shift($text_stack);
 1089                         $span = $this->runSpanGamut($span);
 1090                         $span = "<em>$span</em>";
 1091                         $text_stack[0] .= $this->hashPart($span);
 1092                         $em = '';
 1093                     } else {
 1094                         $text_stack[0] .= $token;
 1095                     }
 1096                 } else {
 1097                     array_unshift($token_stack, $token);
 1098                     array_unshift($text_stack, '');
 1099                     $em = $token;
 1100                 }
 1101             }
 1102         }
 1103         return $text_stack[0];
 1104     }
 1105 
 1106 
 1107     public function doBlockQuotes($text) {
 1108         $text = preg_replace_callback('/
 1109               (                             # Wrap whole match in $1
 1110                 (?>
 1111                   ^[ ]*>[ ]?            # ">" at the start of a line
 1112                     .+\n                    # rest of the first line
 1113                   (.+\n)*                   # subsequent consecutive lines
 1114                   \n*                       # blanks
 1115                 )+
 1116               )
 1117             /xm',
 1118             array(&$this, '_doBlockQuotes_callback'), $text);
 1119 
 1120         return $text;
 1121     }
 1122     
 1123     public function _doBlockQuotes_callback($matches) {
 1124         $bq = $matches[1];
 1125         # trim one level of quoting - trim whitespace-only lines
 1126         $bq = preg_replace('/^[ ]*>[ ]?|^[ ]+$/m', '', $bq);
 1127         $bq = $this->runBlockGamut($bq);        # recurse
 1128 
 1129         $bq = preg_replace('/^/m', "  ", $bq);
 1130         # These leading spaces cause problem with <pre> content, 
 1131         # so we need to fix that:
 1132         $bq = preg_replace_callback('{(\s*<pre>.+?</pre>)}sx', 
 1133             array(&$this, '_doBlockQuotes_callback2'), $bq);
 1134 
 1135         return "\n". $this->hashBlock("<blockquote>\n$bq\n</blockquote>")."\n\n";
 1136     }
 1137     
 1138     public function _doBlockQuotes_callback2($matches) {
 1139         $pre = $matches[1];
 1140         $pre = preg_replace('/^  /m', '', $pre);
 1141         return $pre;
 1142     }
 1143 
 1144 
 1145     public function formParagraphs($text) {
 1146     #
 1147     #   Params:
 1148     #       $text - string to process with html <p> tags
 1149     #
 1150         # Strip leading and trailing lines:
 1151         $text = preg_replace('/\A\n+|\n+\z/', '', $text);
 1152 
 1153         $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY);
 1154 
 1155         #
 1156         # Wrap <p> tags and unhashify HTML blocks
 1157         #
 1158         foreach ($grafs as $key => $value) {
 1159             if (!preg_match('/^B\x1A[0-9]+B$/', $value)) {
 1160                 # Is a paragraph.
 1161                 $value = $this->runSpanGamut($value);
 1162                 $value = preg_replace('/^([ ]*)/', "<p>", $value);
 1163                 $value .= "</p>";
 1164                 $grafs[$key] = $this->unhash($value);
 1165             }
 1166             else {
 1167                 # Is a block.
 1168                 # Modify elements of @grafs in-place...
 1169                 $graf = $value;
 1170                 $block = $this->html_hashes[$graf];
 1171                 $graf = $block;
 1172 //              if (preg_match('{
 1173 //                  \A
 1174 //                  (                           # $1 = <div> tag
 1175 //                    <div  \s+
 1176 //                    [^>]*
 1177 //                    \b
 1178 //                    markdown\s*=\s*  ([\'"])  #   $2 = attr quote char
 1179 //                    1
 1180 //                    \2
 1181 //                    [^>]*
 1182 //                    >
 1183 //                  )
 1184 //                  (                           # $3 = contents
 1185 //                  .*
 1186 //                  )
 1187 //                  (</div>)                    # $4 = closing tag
 1188 //                  \z
 1189 //                  }xs', $block, $matches))
 1190 //              {
 1191 //                  list(, $div_open, , $div_content, $div_close) = $matches;
 1192 //
 1193 //                  # We can't call Markdown(), because that resets the hash;
 1194 //                  # that initialization code should be pulled into its own sub, though.
 1195 //                  $div_content = $this->hashHTMLBlocks($div_content);
 1196 //
 1197 //                  # Run document gamut methods on the content.
 1198 //                  foreach ($this->document_gamut as $method => $priority) {
 1199 //                      $div_content = $this->$method($div_content);
 1200 //                  }
 1201 //
 1202 //                  $div_open = preg_replace(
 1203 //                      '{\smarkdown\s*=\s*([\'"]).+?\1}', '', $div_open);
 1204 //
 1205 //                  $graf = $div_open . "\n" . $div_content . "\n" . $div_close;
 1206 //              }
 1207                 $grafs[$key] = $graf;
 1208             }
 1209         }
 1210 
 1211         return implode("\n\n", $grafs);
 1212     }
 1213 
 1214 
 1215     public function encodeAttribute($text) {
 1216     #
 1217     # Encode text for a double-quoted HTML attribute. This function
 1218     # is *not* suitable for attributes enclosed in single quotes.
 1219     #
 1220         $text = $this->encodeAmpsAndAngles($text);
 1221         $text = str_replace('"', '&quot;', $text);
 1222         return $text;
 1223     }
 1224 
 1225 
 1226     public function encodeAmpsAndAngles($text) {
 1227     #
 1228     # Smart processing for ampersands and angle brackets that need to
 1229     # be encoded. Valid character entities are left alone unless the
 1230     # no-entities mode is set.
 1231     #
 1232         if ($this->no_entities) {
 1233             $text = str_replace('&', '&amp;', $text);
 1234         } else {
 1235             # Ampersand-encoding based entirely on Nat Irons's Amputator
 1236             # MT plugin: <http://bumppo.net/projects/amputator/>
 1237             $text = preg_replace('/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/',
 1238                                 '&amp;', $text);;
 1239         }
 1240         # Encode remaining <'s
 1241         $text = str_replace('<', '&lt;', $text);
 1242 
 1243         return $text;
 1244     }
 1245 
 1246 
 1247     public function doAutoLinks($text) {
 1248         $text = preg_replace_callback('{<((https?|ftp|dict):[^\'">\s]+)>}i',
 1249             array(&$this, '_doAutoLinks_url_callback'), $text);
 1250 
 1251         # Email addresses: <address@domain.foo>
 1252         $text = preg_replace_callback('{
 1253             <
 1254             (?:mailto:)?
 1255             (
 1256                 (?:
 1257                     [-!#$%&\'*+/=?^_`.{|}~\w\x80-\xFF]+
 1258                 |
 1259                     ".*?"
 1260                 )
 1261                 \@
 1262                 (?:
 1263                     [-a-z0-9\x80-\xFF]+(\.[-a-z0-9\x80-\xFF]+)*\.[a-z]+
 1264                 |
 1265                     \[[\d.a-fA-F:]+\]   # IPv4 & IPv6
 1266                 )
 1267             )
 1268             >
 1269             }xi',
 1270             array(&$this, '_doAutoLinks_email_callback'), $text);
 1271 
 1272         return $text;
 1273     }
 1274     public function _doAutoLinks_url_callback($matches) {
 1275         $url = $this->encodeAttribute($matches[1]);
 1276         $link = "<a href=\"$url\">$url</a>";
 1277         return $this->hashPart($link);
 1278     }
 1279     public function _doAutoLinks_email_callback($matches) {
 1280         $address = $matches[1];
 1281         $link = $this->encodeEmailAddress($address);
 1282         return $this->hashPart($link);
 1283     }
 1284 
 1285 
 1286     public function encodeEmailAddress($addr) {
 1287     #
 1288     #   Input: an email address, e.g. "foo@example.com"
 1289     #
 1290     #   Output: the email address as a mailto link, with each character
 1291     #       of the address encoded as either a decimal or hex entity, in
 1292     #       the hopes of foiling most address harvesting spam bots. E.g.:
 1293     #
 1294     #     <p><a href="&#109;&#x61;&#105;&#x6c;&#116;&#x6f;&#58;&#x66;o&#111;
 1295     #        &#x40;&#101;&#x78;&#97;&#x6d;&#112;&#x6c;&#101;&#46;&#x63;&#111;
 1296     #        &#x6d;">&#x66;o&#111;&#x40;&#101;&#x78;&#97;&#x6d;&#112;&#x6c;
 1297     #        &#101;&#46;&#x63;&#111;&#x6d;</a></p>
 1298     #
 1299     #   Based by a filter by Matthew Wickline, posted to BBEdit-Talk.
 1300     #   With some optimizations by Milian Wolff.
 1301     #
 1302         $addr = "mailto:" . $addr;
 1303         $chars = preg_split('/(?<!^)(?!$)/', $addr);
 1304         $seed = (int)abs(crc32($addr) / strlen($addr)); # Deterministic seed.
 1305 
 1306         foreach ($chars as $key => $char) {
 1307             $ord = ord($char);
 1308             # Ignore non-ascii chars.
 1309             if ($ord < 128) {
 1310                 $r = ($seed * (1 + $key)) % 100; # Pseudo-random function.
 1311                 # roughly 10% raw, 45% hex, 45% dec
 1312                 # '@' *must* be encoded. I insist.
 1313                 if ($r > 90 && $char != '@') /* do nothing */;
 1314                 else if ($r < 45) $chars[$key] = '&#x'.dechex($ord).';';
 1315                 else              $chars[$key] = '&#'.$ord.';';
 1316             }
 1317         }
 1318 
 1319         $addr = implode('', $chars);
 1320         $text = implode('', array_slice($chars, 7)); # text without `mailto:`
 1321         $addr = "<a href=\"$addr\">$text</a>";
 1322 
 1323         return $addr;
 1324     }
 1325 
 1326 
 1327     public function parseSpan($str) {
 1328     #
 1329     # Take the string $str and parse it into tokens, hashing embeded HTML,
 1330     # escaped characters and handling code spans.
 1331     #
 1332         $output = '';
 1333 
 1334         $span_re = '{
 1335                 (
 1336                     \\\\'.$this->escape_chars_re.'
 1337                 |
 1338                     (?<![`\\\\])
 1339                     `+                      # code span marker
 1340             '.( $this->no_markup ? '' : '
 1341                 |
 1342                     <!--    .*?     -->     # comment
 1343                 |
 1344                     <\?.*?\?> | <%.*?%>     # processing instruction
 1345                 |
 1346                     <[/!$]?[-a-zA-Z0-9:_]+  # regular tags
 1347                     (?>
 1348                         \s
 1349                         (?>[^"\'>]+|"[^"]*"|\'[^\']*\')*
 1350                     )?
 1351                     >
 1352             ').'
 1353                 )
 1354                 }xs';
 1355 
 1356         while (1) {
 1357             #
 1358             # Each loop iteration seach for either the next tag, the next
 1359             # openning code span marker, or the next escaped character.
 1360             # Each token is then passed to handleSpanToken.
 1361             #
 1362             $parts = preg_split($span_re, $str, 2, PREG_SPLIT_DELIM_CAPTURE);
 1363 
 1364             # Create token from text preceding tag.
 1365             if ($parts[0] != "") {
 1366                 $output .= $parts[0];
 1367             }
 1368 
 1369             # Check if we reach the end.
 1370             if (isset($parts[1])) {
 1371                 $output .= $this->handleSpanToken($parts[1], $parts[2]);
 1372                 $str = $parts[2];
 1373             }
 1374             else {
 1375                 break;
 1376             }
 1377         }
 1378 
 1379         return $output;
 1380     }
 1381 
 1382 
 1383     public function handleSpanToken($token, &$str) {
 1384     #
 1385     # Handle $token provided by parseSpan by determining its nature and
 1386     # returning the corresponding value that should replace it.
 1387     #
 1388         switch ($token[0]) {
 1389             case "\\":
 1390                 return $this->hashPart("&#". ord($token[1]). ";");
 1391             case "`":
 1392                 # Search for end marker in remaining text.
 1393                 if (preg_match('/^(.*?[^`])'.preg_quote($token).'(?!`)(.*)$/sm',
 1394                     $str, $matches))
 1395                 {
 1396                     $str = $matches[2];
 1397                     $codespan = $this->makeCodeSpan($matches[1]);
 1398                     return $this->hashPart($codespan);
 1399                 }
 1400                 return $token; // return as text since no ending marker found.
 1401             default:
 1402                 return $this->hashPart($token);
 1403         }
 1404     }
 1405 
 1406 
 1407     public function outdent($text) {
 1408     #
 1409     # Remove one level of line-leading tabs or spaces
 1410     #
 1411         return preg_replace('/^(\t|[ ]{1,'.$this->tab_width.'})/m', '', $text);
 1412     }
 1413 
 1414     public function detab($text) {
 1415     #
 1416     # Replace tabs with the appropriate amount of space.
 1417     #
 1418         # For each line we separate the line in blocks delemited by
 1419         # tab characters. Then we reconstruct every line by adding the
 1420         # appropriate number of space between each blocks.
 1421 
 1422         $text = preg_replace_callback('/^.*\t.*$/m',
 1423             array(&$this, '_detab_callback'), $text);
 1424 
 1425         return $text;
 1426     }
 1427     public function _detab_callback($matches) {
 1428         $line = $matches[0];
 1429 
 1430         # Split in blocks.
 1431         $blocks = explode("\t", $line);
 1432         # Add each blocks to the line.
 1433         $line = $blocks[0];
 1434         unset($blocks[0]); # Do not add first block twice.
 1435         foreach ($blocks as $block) {
 1436             # Calculate amount of space, insert spaces, insert block.
 1437             $amount = $this->tab_width -
 1438                 $this->utf8_strlen($line) % $this->tab_width;
 1439             $line .= str_repeat(" ", $amount) . $block;
 1440         }
 1441         return $line;
 1442     }
 1443 
 1444     protected function utf8_strlen($string) {
 1445         if (function_exists('mb_strlen')) {
 1446             return mb_strlen($string, 'UTF-8');
 1447         }
 1448 
 1449         return preg_match_all(
 1450             "/[\x00-\xBF]|[\xC0-\xFF][\x80-\xBF]*/",
 1451             $text,
 1452             $m
 1453         );
 1454     }
 1455 
 1456     public function unhash($text) {
 1457     #
 1458     # Swap back in all the tags hashed by _HashHTMLBlocks.
 1459     #
 1460         return preg_replace_callback('/(.)\x1A[0-9]+\1/',
 1461             array(&$this, '_unhash_callback'), $text);
 1462     }
 1463     public function _unhash_callback($matches) {
 1464         return $this->html_hashes[$matches[0]];
 1465     }
 1466 
 1467 }
 1468 
 1469 
 1470 #
 1471 # Markdown Extra Parser Class
 1472 #
 1473 
 1474 class MarkdownExtra_Parser extends Markdown_Parser {
 1475 
 1476     # Prefix for footnote ids.
 1477     public $fn_id_prefix = "";
 1478 
 1479     # Optional title attribute for footnote links and backlinks.
 1480     public $fn_link_title = '';
 1481     public $fn_backlink_title = '';
 1482 
 1483     # Optional class attribute for footnote links and backlinks.
 1484     public $fn_link_class = '';
 1485     public $fn_backlink_class = '';
 1486 
 1487     # Predefined abbreviations.
 1488     public $predef_abbr = array();
 1489 
 1490 
 1491     public function __construct() {
 1492     #
 1493     # Constructor function. Initialize the parser object.
 1494     #
 1495         # Add extra escapable characters before parent constructor
 1496         # initialize the table.
 1497         $this->escape_chars .= ':|';
 1498 
 1499         # Insert extra document, block, and span transformations.
 1500         # Parent constructor will do the sorting.
 1501         $this->document_gamut += array(
 1502             "doFencedCodeBlocks" => 5,
 1503             "stripFootnotes"     => 15,
 1504             "stripAbbreviations" => 25,
 1505             "appendFootnotes"    => 50,
 1506             );
 1507         $this->block_gamut += array(
 1508             "doFencedCodeBlocks" => 5,
 1509             "doTables"           => 15,
 1510             "doDefLists"         => 45,
 1511             );
 1512         $this->span_gamut += array(
 1513             "doFootnotes"        => 5,
 1514             "doAbbreviations"    => 70,
 1515             );
 1516 
 1517         parent::__construct();
 1518     }
 1519 
 1520 
 1521     # Extra variables used during extra transformations.
 1522     public $footnotes = array();
 1523     public $footnotes_ordered = array();
 1524     public $abbr_desciptions = array();
 1525     public $abbr_word_re = '';
 1526 
 1527     # Give the current footnote number.
 1528     public $footnote_counter = 1;
 1529 
 1530 
 1531     public function setup() {
 1532     #
 1533     # Setting up Extra-specific variables.
 1534     #
 1535         parent::setup();
 1536 
 1537         $this->footnotes = array();
 1538         $this->footnotes_ordered = array();
 1539         $this->abbr_desciptions = array();
 1540         $this->abbr_word_re = '';
 1541         $this->footnote_counter = 1;
 1542 
 1543         foreach ($this->predef_abbr as $abbr_word => $abbr_desc) {
 1544             if ($this->abbr_word_re)
 1545                 $this->abbr_word_re .= '|';
 1546             $this->abbr_word_re .= preg_quote($abbr_word);
 1547             $this->abbr_desciptions[$abbr_word] = trim($abbr_desc);
 1548         }
 1549     }
 1550 
 1551     public function teardown() {
 1552     #
 1553     # Clearing Extra-specific variables.
 1554     #
 1555         $this->footnotes = array();
 1556         $this->footnotes_ordered = array();
 1557         $this->abbr_desciptions = array();
 1558         $this->abbr_word_re = '';
 1559 
 1560         parent::teardown();
 1561     }
 1562 
 1563 
 1564     ### HTML Block Parser ###
 1565 
 1566     # Tags that are always treated as block tags:
 1567     public $block_tags_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|form|fieldset|iframe|hr|legend';
 1568 
 1569     # Tags treated as block tags only if the opening tag is alone on it's line:
 1570     public $context_block_tags_re = 'script|noscript|math|ins|del';
 1571 
 1572     # Tags where markdown="1" default to span mode:
 1573     public $contain_span_tags_re = 'p|h[1-6]|li|dd|dt|td|th|legend|address';
 1574 
 1575     # Tags which must not have their contents modified, no matter where
 1576     # they appear:
 1577     public $clean_tags_re = 'script|math';
 1578 
 1579     # Tags that do not need to be closed.
 1580     public $auto_close_tags_re = 'hr|img';
 1581 
 1582 
 1583     public function hashHTMLBlocks($text) {
 1584     #
 1585     # Hashify HTML Blocks and "clean tags".
 1586     #
 1587     # We only want to do this for block-level HTML tags, such as headers,
 1588     # lists, and tables. That's because we still want to wrap <p>s around
 1589     # "paragraphs" that are wrapped in non-block-level tags, such as anchors,
 1590     # phrase emphasis, and spans. The list of tags we're looking for is
 1591     # hard-coded.
 1592     #
 1593     # This works by calling _HashHTMLBlocks_InMarkdown, which then calls
 1594     # _HashHTMLBlocks_InHTML when it encounter block tags. When the markdown="1"
 1595     # attribute is found whitin a tag, _HashHTMLBlocks_InHTML calls back
 1596     #  _HashHTMLBlocks_InMarkdown to handle the Markdown syntax within the tag.
 1597     # These two functions are calling each other. It's recursive!
 1598     #
 1599         #
 1600         # Call the HTML-in-Markdown hasher.
 1601         #
 1602         list($text, ) = $this->_hashHTMLBlocks_inMarkdown($text);
 1603 
 1604         return $text;
 1605     }
 1606     public function _hashHTMLBlocks_inMarkdown($text, $indent = 0,
 1607                                         $enclosing_tag_re = '', $span = false)
 1608     {
 1609     #
 1610     # Parse markdown text, calling _HashHTMLBlocks_InHTML for block tags.
 1611     #
 1612     # *   $indent is the number of space to be ignored when checking for code
 1613     #     blocks. This is important because if we don't take the indent into
 1614     #     account, something like this (which looks right) won't work as expected:
 1615     #
 1616     #     <div>
 1617     #         <div markdown="1">
 1618     #         Hello World.  <-- Is this a Markdown code block or text?
 1619     #         </div>  <-- Is this a Markdown code block or a real tag?
 1620     #     <div>
 1621     #
 1622     #     If you don't like this, just don't indent the tag on which
 1623     #     you apply the markdown="1" attribute.
 1624     #
 1625     # *   If $enclosing_tag_re is not empty, stops at the first unmatched closing
 1626     #     tag with that name. Nested tags supported.
 1627     #
 1628     # *   If $span is true, text inside must treated as span. So any double
 1629     #     newline will be replaced by a single newline so that it does not create
 1630     #     paragraphs.
 1631     #
 1632     # Returns an array of that form: ( processed text , remaining text )
 1633     #
 1634         if ($text === '') return array('', '');
 1635 
 1636         # Regex to check for the presense of newlines around a block tag.
 1637         $newline_before_re = '/(?:^\n?|\n\n)*$/';
 1638         $newline_after_re =
 1639             '{
 1640                 ^                       # Start of text following the tag.
 1641                 (?>[ ]*<!--.*?-->)?     # Optional comment.
 1642                 [ ]*\n                  # Must be followed by newline.
 1643             }xs';
 1644 
 1645         # Regex to match any tag.
 1646         $block_tag_re =
 1647             '{
 1648                 (                   # $2: Capture hole tag.
 1649                     </?                 # Any opening or closing tag.
 1650                         (?>             # Tag name.
 1651                             '.$this->block_tags_re.'            |
 1652                             '.$this->context_block_tags_re.'    |
 1653                             '.$this->clean_tags_re.'            |
 1654                             (?!\s)'.$enclosing_tag_re.'
 1655                         )
 1656                         (?:
 1657                             (?=[\s"\'/a-zA-Z0-9])   # Allowed characters after tag name.
 1658                             (?>
 1659                                 ".*?"       |   # Double quotes (can contain `>`)
 1660                                 \'.*?\'     |   # Single quotes (can contain `>`)
 1661                                 .+?             # Anything but quotes and `>`.
 1662                             )*?
 1663                         )?
 1664                     >                   # End of tag.
 1665                 |
 1666                     <!--    .*?     --> # HTML Comment
 1667                 |
 1668                     <\?.*?\?> | <%.*?%> # Processing instruction
 1669                 |
 1670                     <!\[CDATA\[.*?\]\]> # CData Block
 1671                 |
 1672                     # Code span marker
 1673                     `+
 1674                 '. ( !$span ? ' # If not in span.
 1675                 |
 1676                     # Indented code block
 1677                     (?: ^[ ]*\n | ^ | \n[ ]*\n )
 1678                     [ ]{'.($indent+4).'}[^\n]* \n
 1679                     (?>
 1680                         (?: [ ]{'.($indent+4).'}[^\n]* | [ ]* ) \n
 1681                     )*
 1682                 |
 1683                     # Fenced code block marker
 1684                     (?> ^ | \n )
 1685                     [ ]{0,'.($indent).'}~~~+[ ]*\n
 1686                 ' : '' ). ' # End (if not is span).
 1687                 )
 1688             }xs';
 1689 
 1690 
 1691         $depth = 0;     # Current depth inside the tag tree.
 1692         $parsed = "";   # Parsed text that will be returned.
 1693 
 1694         #
 1695         # Loop through every tag until we find the closing tag of the parent
 1696         # or loop until reaching the end of text if no parent tag specified.
 1697         #
 1698         do {
 1699             #
 1700             # Split the text using the first $tag_match pattern found.
 1701             # Text before  pattern will be first in the array, text after
 1702             # pattern will be at the end, and between will be any catches made
 1703             # by the pattern.
 1704             #
 1705             $parts = preg_split($block_tag_re, $text, 2,
 1706                                 PREG_SPLIT_DELIM_CAPTURE);
 1707 
 1708             # If in Markdown span mode, add a empty-string span-level hash
 1709             # after each newline to prevent triggering any block element.
 1710             if ($span) {
 1711                 $void = $this->hashPart("", ':');
 1712                 $newline = "$void\n";
 1713                 $parts[0] = $void . str_replace("\n", $newline, $parts[0]) . $void;
 1714             }
 1715 
 1716             $parsed .= $parts[0]; # Text before current tag.
 1717 
 1718             # If end of $text has been reached. Stop loop.
 1719             if (count($parts) < 3) {
 1720                 $text = "";
 1721                 break;
 1722             }
 1723 
 1724             $tag  = $parts[1]; # Tag to handle.
 1725             $text = $parts[2]; # Remaining text after current tag.
 1726             $tag_re = preg_quote($tag); # For use in a regular expression.
 1727 
 1728             #
 1729             # Check for: Code span marker
 1730             #
 1731             if ($tag[0] == "`") {
 1732                 # Find corresponding end marker.
 1733                 $tag_re = preg_quote($tag);
 1734                 if (preg_match('{^(?>.+?|\n(?!\n))*?(?<!`)'.$tag_re.'(?!`)}',
 1735                     $text, $matches))
 1736                 {
 1737                     # End marker found: pass text unchanged until marker.
 1738                     $parsed .= $tag . $matches[0];
 1739                     $text = substr($text, strlen($matches[0]));
 1740                 }
 1741                 else {
 1742                     # Unmatched marker: just skip it.
 1743                     $parsed .= $tag;
 1744                 }
 1745             }
 1746             #
 1747             # Check for: Fenced code block marker.
 1748             #
 1749             else if (preg_match('{^\n?[ ]{0,'.($indent+3).'}~}', $tag)) {
 1750                 # Fenced code block marker: find matching end marker.
 1751                 $tag_re = preg_quote(trim($tag));
 1752                 if (preg_match('{^(?>.*\n)+?[ ]{0,'.($indent).'}'.$tag_re.'[ ]*\n}', $text, 
 1753                     $matches)) 
 1754                 {
 1755                     # End marker found: pass text unchanged until marker.
 1756                     $parsed .= $tag . $matches[0];
 1757                     $text = substr($text, strlen($matches[0]));
 1758                 }
 1759                 else {
 1760                     # No end marker: just skip it.
 1761                     $parsed .= $tag;
 1762                 }
 1763             }
 1764             #
 1765             # Check for: Indented code block.
 1766             #
 1767             else if ($tag[0] == "\n" || $tag[0] == " ") {
 1768                 # Indented code block: pass it unchanged, will be handled 
 1769                 # later.
 1770                 $parsed .= $tag;
 1771             }
 1772             #
 1773             # Check for: Opening Block level tag or
 1774             #            Opening Context Block tag (like ins and del)
 1775             #               used as a block tag (tag is alone on it's line).
 1776             #
 1777             else if (preg_match('{^<(?:'.$this->block_tags_re.')\b}', $tag) ||
 1778                 (   preg_match('{^<(?:'.$this->context_block_tags_re.')\b}', $tag) &&
 1779                     preg_match($newline_before_re, $parsed) &&
 1780                     preg_match($newline_after_re, $text)    )
 1781                 )
 1782             {
 1783                 # Need to parse tag and following text using the HTML parser.
 1784                 list($block_text, $text) =
 1785                     $this->_hashHTMLBlocks_inHTML($tag . $text, "hashBlock", true);
 1786 
 1787                 # Make sure it stays outside of any paragraph by adding newlines.
 1788                 $parsed .= "\n\n$block_text\n\n";
 1789             }
 1790             #
 1791             # Check for: Clean tag (like script, math)
 1792             #            HTML Comments, processing instructions.
 1793             #
 1794             else if (preg_match('{^<(?:'.$this->clean_tags_re.')\b}', $tag) ||
 1795                 $tag[1] == '!' || $tag[1] == '?')
 1796             {
 1797                 # Need to parse tag and following text using the HTML parser.
 1798                 # (don't check for markdown attribute)
 1799                 list($block_text, $text) =
 1800                     $this->_hashHTMLBlocks_inHTML($tag . $text, "hashClean", false);
 1801 
 1802                 $parsed .= $block_text;
 1803             }
 1804             #
 1805             # Check for: Tag with same name as enclosing tag.
 1806             #
 1807             else if ($enclosing_tag_re !== '' &&
 1808                 # Same name as enclosing tag.
 1809                 preg_match('{^</?(?:'.$enclosing_tag_re.')\b}', $tag))
 1810             {
 1811                 #
 1812                 # Increase/decrease nested tag count.
 1813                 #
 1814                 if ($tag[1] == '/')                     $depth--;
 1815                 else if ($tag[strlen($tag)-2] != '/')   $depth++;
 1816 
 1817                 if ($depth < 0) {
 1818                     #
 1819                     # Going out of parent element. Clean up and break so we
 1820                     # return to the calling function.
 1821                     #
 1822                     $text = $tag . $text;
 1823                     break;
 1824                 }
 1825 
 1826                 $parsed .= $tag;
 1827             }
 1828             else {
 1829                 $parsed .= $tag;
 1830             }
 1831         } while ($depth >= 0);
 1832 
 1833         return array($parsed, $text);
 1834     }
 1835     public function _hashHTMLBlocks_inHTML($text, $hash_method, $md_attr) {
 1836     #
 1837     # Parse HTML, calling _HashHTMLBlocks_InMarkdown for block tags.
 1838     #
 1839     # *   Calls $hash_method to convert any blocks.
 1840     # *   Stops when the first opening tag closes.
 1841     # *   $md_attr indicate if the use of the `markdown="1"` attribute is allowed.
 1842     #     (it is not inside clean tags)
 1843     #
 1844     # Returns an array of that form: ( processed text , remaining text )
 1845     #
 1846         if ($text === '') return array('', '');
 1847 
 1848         # Regex to match `markdown` attribute inside of a tag.
 1849         $markdown_attr_re = '
 1850             {
 1851                 \s*         # Eat whitespace before the `markdown` attribute
 1852                 markdown
 1853                 \s*=\s*
 1854                 (?>
 1855                     (["\'])     # $1: quote delimiter
 1856                     (.*?)       # $2: attribute value
 1857                     \1          # matching delimiter
 1858                 |
 1859                     ([^\s>]*)   # $3: unquoted attribute value
 1860                 )
 1861                 ()              # $4: make $3 always defined (avoid warnings)
 1862             }xs';
 1863 
 1864         # Regex to match any tag.
 1865         $tag_re = '{
 1866                 (                   # $2: Capture hole tag.
 1867                     </?                 # Any opening or closing tag.
 1868                         [\w:$]+         # Tag name.
 1869                         (?:
 1870                             (?=[\s"\'/a-zA-Z0-9])   # Allowed characters after tag name.
 1871                             (?>
 1872                                 ".*?"       |   # Double quotes (can contain `>`)
 1873                                 \'.*?\'     |   # Single quotes (can contain `>`)
 1874                                 .+?             # Anything but quotes and `>`.
 1875                             )*?
 1876                         )?
 1877                     >                   # End of tag.
 1878                 |
 1879                     <!--    .*?     --> # HTML Comment
 1880                 |
 1881                     <\?.*?\?> | <%.*?%> # Processing instruction
 1882                 |
 1883                     <!\[CDATA\[.*?\]\]> # CData Block
 1884                 )
 1885             }xs';
 1886 
 1887         $original_text = $text;     # Save original text in case of faliure.
 1888 
 1889         $depth      = 0;    # Current depth inside the tag tree.
 1890         $block_text = "";   # Temporary text holder for current text.
 1891         $parsed     = "";   # Parsed text that will be returned.
 1892 
 1893         #
 1894         # Get the name of the starting tag.
 1895         # (This pattern makes $base_tag_name_re safe without quoting.)
 1896         #
 1897         if (preg_match('/^<([\w:$]*)\b/', $text, $matches))
 1898             $base_tag_name_re = $matches[1];
 1899 
 1900         #
 1901         # Loop through every tag until we find the corresponding closing tag.
 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($tag_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE);
 1911 
 1912             if (count($parts) < 3) {
 1913                 #
 1914                 # End of $text reached with unbalenced tag(s).
 1915                 # In that case, we return original text unchanged and pass the
 1916                 # first character as filtered to prevent an infinite loop in the
 1917                 # parent function.
 1918                 #
 1919                 return array($original_text[0], substr($original_text, 1));
 1920             }
 1921 
 1922             $block_text .= $parts[0]; # Text before current tag.
 1923             $tag         = $parts[1]; # Tag to handle.
 1924             $text        = $parts[2]; # Remaining text after current tag.
 1925 
 1926             #
 1927             # Check for: Auto-close tag (like <hr/>)
 1928             #            Comments and Processing Instructions.
 1929             #
 1930             if (preg_match('{^</?(?:'.$this->auto_close_tags_re.')\b}', $tag) ||
 1931                 $tag[1] == '!' || $tag[1] == '?')
 1932             {
 1933                 # Just add the tag to the block as if it was text.
 1934                 $block_text .= $tag;
 1935             }
 1936             else {
 1937                 #
 1938                 # Increase/decrease nested tag count. Only do so if
 1939                 # the tag's name match base tag's.
 1940                 #
 1941                 if (preg_match('{^</?'.$base_tag_name_re.'\b}', $tag)) {
 1942                     if ($tag[1] == '/')                     $depth--;
 1943                     else if ($tag[strlen($tag)-2] != '/')   $depth++;
 1944                 }
 1945 
 1946                 #
 1947                 # Check for `markdown="1"` attribute and handle it.
 1948                 #
 1949                 if ($md_attr &&
 1950                     preg_match($markdown_attr_re, $tag, $attr_m) &&
 1951                     preg_match('/^1|block|span$/', $attr_m[2] . $attr_m[3]))
 1952                 {
 1953                     # Remove `markdown` attribute from opening tag.
 1954                     $tag = preg_replace($markdown_attr_re, '', $tag);
 1955 
 1956                     # Check if text inside this tag must be parsed in span mode.
 1957                     $this->mode = $attr_m[2] . $attr_m[3];
 1958                     $span_mode = $this->mode == 'span' || $this->mode != 'block' &&
 1959                         preg_match('{^<(?:'.$this->contain_span_tags_re.')\b}', $tag);
 1960 
 1961                     # Calculate indent before tag.
 1962                     if (preg_match('/(?:^|\n)( *?)(?! ).*?$/', $block_text, $matches)) {
 1963                         $indent = $this->utf8_strlen($matches[1]);
 1964                     } else {
 1965                         $indent = 0;
 1966                     }
 1967 
 1968                     # End preceding block with this tag.
 1969                     $block_text .= $tag;
 1970                     $parsed .= $this->$hash_method($block_text);
 1971 
 1972                     # Get enclosing tag name for the ParseMarkdown function.
 1973                     # (This pattern makes $tag_name_re safe without quoting.)
 1974                     preg_match('/^<([\w:$]*)\b/', $tag, $matches);
 1975                     $tag_name_re = $matches[1];
 1976 
 1977                     # Parse the content using the HTML-in-Markdown parser.
 1978                     list ($block_text, $text)
 1979                         = $this->_hashHTMLBlocks_inMarkdown($text, $indent,
 1980                             $tag_name_re, $span_mode);
 1981 
 1982                     # Outdent markdown text.
 1983                     if ($indent > 0) {
 1984                         $block_text = preg_replace("/^[ ]{1,$indent}/m", "",
 1985                                                     $block_text);
 1986                     }
 1987 
 1988                     # Append tag content to parsed text.
 1989                     if (!$span_mode)    $parsed .= "\n\n$block_text\n\n";
 1990                     else                $parsed .= "$block_text";
 1991 
 1992                     # Start over a new block.
 1993                     $block_text = "";
 1994                 }
 1995                 else $block_text .= $tag;
 1996             }
 1997 
 1998         } while ($depth > 0);
 1999 
 2000         #
 2001         # Hash last block text that wasn't processed inside the loop.
 2002         #
 2003         $parsed .= $this->$hash_method($block_text);
 2004 
 2005         return array($parsed, $text);
 2006     }
 2007 
 2008 
 2009     public function hashClean($text) {
 2010     #
 2011     # Called whenever a tag must be hashed when a function insert a "clean" tag
 2012     # in $text, it pass through this function and is automaticaly escaped,
 2013     # blocking invalid nested overlap.
 2014     #
 2015         return $this->hashPart($text, 'C');
 2016     }
 2017 
 2018 
 2019     public function doHeaders($text) {
 2020     #
 2021     # Redefined to add id attribute support.
 2022     #
 2023         # Setext-style headers:
 2024         #     Header 1  {#header1}
 2025         #     ========
 2026         #
 2027         #     Header 2  {#header2}
 2028         #     --------
 2029         #
 2030         $text = preg_replace_callback(
 2031             '{
 2032                 (^.+?)                              # $1: Header text
 2033                 (?:[ ]+\{\#([-_:a-zA-Z0-9]+)\})?    # $2: Id attribute
 2034                 [ ]*\n(=+|-+)[ ]*\n+                # $3: Header footer
 2035             }mx',
 2036             array(&$this, '_doHeaders_callback_setext'), $text);
 2037 
 2038         # atx-style headers:
 2039         #   # Header 1        {#header1}
 2040         #   ## Header 2       {#header2}
 2041         #   ## Header 2 with closing hashes ##  {#header3}
 2042         #   ...
 2043         #   ###### Header 6   {#header2}
 2044         #
 2045         $text = preg_replace_callback('{
 2046                 ^(\#{1,6})  # $1 = string of #\'s
 2047                 [ ]*
 2048                 (.+?)       # $2 = Header text
 2049                 [ ]*
 2050                 \#*         # optional closing #\'s (not counted)
 2051                 (?:[ ]+\{\#([-_:a-zA-Z0-9]+)\})? # id attribute
 2052                 [ ]*
 2053                 \n+
 2054             }xm',
 2055             array(&$this, '_doHeaders_callback_atx'), $text);
 2056 
 2057         return $text;
 2058     }
 2059     public function _doHeaders_attr($attr) {
 2060         if (empty($attr))  return "";
 2061         return " id=\"$attr\"";
 2062     }
 2063     public function _doHeaders_callback_setext($matches) {
 2064         if ($matches[3] == '-' && preg_match('{^- }', $matches[1]))
 2065             return $matches[0];
 2066         $level = $matches[3][0] == '=' ? 1 : 2;
 2067         $attr  = $this->_doHeaders_attr($id =& $matches[2]);
 2068         $block = "<h$level$attr>".$this->runSpanGamut($matches[1])."</h$level>";
 2069         return "\n" . $this->hashBlock($block) . "\n\n";
 2070     }
 2071     public function _doHeaders_callback_atx($matches) {
 2072         $level = strlen($matches[1]);
 2073         $attr  = $this->_doHeaders_attr($id =& $matches[3]);
 2074         $block = "<h$level$attr>".$this->runSpanGamut($matches[2])."</h$level>";
 2075         return "\n" . $this->hashBlock($block) . "\n\n";
 2076     }
 2077 
 2078 
 2079     public function doTables($text) {
 2080     #
 2081     # Form HTML tables.
 2082     #
 2083         $less_than_tab = $this->tab_width - 1;
 2084         #
 2085         # Find tables with leading pipe.
 2086         #
 2087         #   | Header 1 | Header 2
 2088         #   | -------- | --------
 2089         #   | Cell 1   | Cell 2
 2090         #   | Cell 3   | Cell 4
 2091         #
 2092         $text = preg_replace_callback('
 2093             {
 2094                 ^                           # Start of a line
 2095                 [ ]{0,'.$less_than_tab.'}   # Allowed whitespace.
 2096                 [|]                         # Optional leading pipe (present)
 2097                 (.+) \n                     # $1: Header row (at least one pipe)
 2098 
 2099                 [ ]{0,'.$less_than_tab.'}   # Allowed whitespace.
 2100                 [|] ([ ]*[-:]+[-| :]*) \n   # $2: Header underline
 2101 
 2102                 (                           # $3: Cells
 2103                     (?>
 2104                         [ ]*                # Allowed whitespace.
 2105                         [|] .* \n           # Row content.
 2106                     )*
 2107                 )
 2108                 (?=\n|\Z)                   # Stop at final double newline.
 2109             }xm',
 2110             array(&$this, '_doTable_leadingPipe_callback'), $text);
 2111 
 2112         #
 2113         # Find tables without leading pipe.
 2114         #
 2115         #   Header 1 | Header 2
 2116         #   -------- | --------
 2117         #   Cell 1   | Cell 2
 2118         #   Cell 3   | Cell 4
 2119         #
 2120         $text = preg_replace_callback('
 2121             {
 2122                 ^                           # Start of a line
 2123                 [ ]{0,'.$less_than_tab.'}   # Allowed whitespace.
 2124                 (\S.*[|].*) \n              # $1: Header row (at least one pipe)
 2125 
 2126                 [ ]{0,'.$less_than_tab.'}   # Allowed whitespace.
 2127                 ([-:]+[ ]*[|][-| :]*) \n    # $2: Header underline
 2128 
 2129                 (                           # $3: Cells
 2130                     (?>
 2131                         .* [|] .* \n        # Row content
 2132                     )*
 2133                 )
 2134                 (?=\n|\Z)                   # Stop at final double newline.
 2135             }xm',
 2136             array(&$this, '_DoTable_callback'), $text);
 2137 
 2138         return $text;
 2139     }
 2140     public function _doTable_leadingPipe_callback($matches) {
 2141         $head       = $matches[1];
 2142         $underline  = $matches[2];
 2143         $content    = $matches[3];
 2144 
 2145         # Remove leading pipe for each row.
 2146         $content    = preg_replace('/^ *[|]/m', '', $content);
 2147 
 2148         return $this->_doTable_callback(array($matches[0], $head, $underline, $content));
 2149     }
 2150     public function _doTable_callback($matches) {
 2151         $head       = $matches[1];
 2152         $underline  = $matches[2];
 2153         $content    = $matches[3];
 2154 
 2155         # Remove any tailing pipes for each line.
 2156         $head       = preg_replace('/[|] *$/m', '', $head);
 2157         $underline  = preg_replace('/[|] *$/m', '', $underline);
 2158         $content    = preg_replace('/[|] *$/m', '', $content);
 2159 
 2160         # Reading alignement from header underline.
 2161         $separators = preg_split('/ *[|] */', $underline);
 2162         foreach ($separators as $n => $s) {
 2163             if (preg_match('/^ *-+: *$/', $s))      $attr[$n] = ' align="right"';
 2164             else if (preg_match('/^ *:-+: *$/', $s))$attr[$n] = ' align="center"';
 2165             else if (preg_match('/^ *:-+ *$/', $s)) $attr[$n] = ' align="left"';
 2166             else                                    $attr[$n] = '';
 2167         }
 2168 
 2169         # Parsing span elements, including code spans, character escapes,
 2170         # and inline HTML tags, so that pipes inside those gets ignored.
 2171         $head       = $this->parseSpan($head);
 2172         $headers    = preg_split('/ *[|] */', $head);
 2173         $col_count  = count($headers);
 2174 
 2175         # Write column headers.
 2176         $text = "<table>\n";
 2177         $text .= "<thead>\n";
 2178         $text .= "<tr>\n";
 2179         foreach ($headers as $n => $header)
 2180             $text .= "  <th$attr[$n]>".$this->runSpanGamut(trim($header))."</th>\n";
 2181         $text .= "</tr>\n";
 2182         $text .= "</thead>\n";
 2183 
 2184         # Split content by row.
 2185         $rows = explode("\n", trim($content, "\n"));
 2186 
 2187         $text .= "<tbody>\n";
 2188         foreach ($rows as $row) {
 2189             # Parsing span elements, including code spans, character escapes,
 2190             # and inline HTML tags, so that pipes inside those gets ignored.
 2191             $row = $this->parseSpan($row);
 2192 
 2193             # Split row by cell.
 2194             $row_cells = preg_split('/ *[|] */', $row, $col_count);
 2195             $row_cells = array_pad($row_cells, $col_count, '');
 2196 
 2197             $text .= "<tr>\n";
 2198             foreach ($row_cells as $n => $cell)
 2199                 $text .= "  <td$attr[$n]>".$this->runSpanGamut(trim($cell))."</td>\n";
 2200             $text .= "</tr>\n";
 2201         }
 2202         $text .= "</tbody>\n";
 2203         $text .= "</table>";
 2204 
 2205         return $this->hashBlock($text) . "\n";
 2206     }
 2207 
 2208 
 2209     public function doDefLists($text) {
 2210     #
 2211     # Form HTML definition lists.
 2212     #
 2213         $less_than_tab = $this->tab_width - 1;
 2214 
 2215         # Re-usable pattern to match any entire dl list:
 2216         $whole_list_re = '(?>
 2217             (                               # $1 = whole list
 2218               (                             # $2
 2219                 [ ]{0,'.$less_than_tab.'}
 2220                 ((?>.*\S.*\n)+)             # $3 = defined term
 2221                 \n?
 2222                 [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition
 2223               )
 2224               (?s:.+?)
 2225               (                             # $4
 2226                   \z
 2227                 |
 2228                   \n{2,}
 2229                   (?=\S)
 2230                   (?!                       # Negative lookahead for another term
 2231                     [ ]{0,'.$less_than_tab.'}
 2232                     (?: \S.*\n )+?          # defined term
 2233                     \n?
 2234                     [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition
 2235                   )
 2236                   (?!                       # Negative lookahead for another definition
 2237                     [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition
 2238                   )
 2239               )
 2240             )
 2241         )'; // mx
 2242 
 2243         $text = preg_replace_callback('{
 2244                 (?>\A\n?|(?<=\n\n))
 2245                 '.$whole_list_re.'
 2246             }mx',
 2247             array(&$this, '_doDefLists_callback'), $text);
 2248 
 2249         return $text;
 2250     }
 2251     public function _doDefLists_callback($matches) {
 2252         # Re-usable patterns to match list item bullets and number markers:
 2253         $list = $matches[1];
 2254 
 2255         # Turn double returns into triple returns, so that we can make a
 2256         # paragraph for the last item in a list, if necessary:
 2257         $result = trim($this->processDefListItems($list));
 2258         $result = "<dl>\n" . $result . "\n</dl>";
 2259         return $this->hashBlock($result) . "\n\n";
 2260     }
 2261 
 2262 
 2263     public function processDefListItems($list_str) {
 2264     #
 2265     #   Process the contents of a single definition list, splitting it
 2266     #   into individual term and definition list items.
 2267     #
 2268         $less_than_tab = $this->tab_width - 1;
 2269 
 2270         # trim trailing blank lines:
 2271         $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str);
 2272 
 2273         # Process definition terms.
 2274         $list_str = preg_replace_callback('{
 2275             (?>\A\n?|\n\n+)                 # leading line
 2276             (                               # definition terms = $1
 2277                 [ ]{0,'.$less_than_tab.'}   # leading whitespace
 2278                 (?![:][ ]|[ ])              # negative lookahead for a definition
 2279                                             #   mark (colon) or more whitespace.
 2280                 (?> \S.* \n)+?              # actual term (not whitespace).
 2281             )
 2282             (?=\n?[ ]{0,3}:[ ])             # lookahead for following line feed
 2283                                             #   with a definition mark.
 2284             }xm',
 2285             array(&$this, '_processDefListItems_callback_dt'), $list_str);
 2286 
 2287         # Process actual definitions.
 2288         $list_str = preg_replace_callback('{
 2289             \n(\n+)?                        # leading line = $1
 2290             (                               # marker space = $2
 2291                 [ ]{0,'.$less_than_tab.'}   # whitespace before colon
 2292                 [:][ ]+                     # definition mark (colon)
 2293             )
 2294             ((?s:.+?))                      # definition text = $3
 2295             (?= \n+                         # stop at next definition mark,
 2296                 (?:                         # next term or end of text
 2297                     [ ]{0,'.$less_than_tab.'} [:][ ]    |
 2298                     <dt> | \z
 2299                 )
 2300             )
 2301             }xm',
 2302             array(&$this, '_processDefListItems_callback_dd'), $list_str);
 2303 
 2304         return $list_str;
 2305     }
 2306     public function _processDefListItems_callback_dt($matches) {
 2307         $terms = explode("\n", trim($matches[1]));
 2308         $text = '';
 2309         foreach ($terms as $term) {
 2310             $term = $this->runSpanGamut(trim($term));
 2311             $text .= "\n<dt>" . $term . "</dt>";
 2312         }
 2313         return $text . "\n";
 2314     }
 2315     public function _processDefListItems_callback_dd($matches) {
 2316         $leading_line   = $matches[1];
 2317         $marker_space   = $matches[2];
 2318         $def            = $matches[3];
 2319 
 2320         if ($leading_line || preg_match('/\n{2,}/', $def)) {
 2321             # Replace marker with the appropriate whitespace indentation
 2322             $def = str_repeat(' ', strlen($marker_space)) . $def;
 2323             $def = $this->runBlockGamut($this->outdent($def . "\n\n"));
 2324             $def = "\n". $def ."\n";
 2325         }
 2326         else {
 2327             $def = rtrim($def);
 2328             $def = $this->runSpanGamut($this->outdent($def));
 2329         }
 2330 
 2331         return "\n<dd>" . $def . "</dd>\n";
 2332     }
 2333 
 2334 
 2335     public function doFencedCodeBlocks($text) {
 2336     #
 2337     # Adding the fenced code block syntax to regular Markdown:
 2338     #
 2339     # ~~~
 2340     # Code block
 2341     # ~~~
 2342     #
 2343         $less_than_tab = $this->tab_width;
 2344 
 2345         $text = preg_replace_callback('{
 2346                 (?:\n|\A)
 2347                 # 1: Opening marker
 2348                 (
 2349                     ~{3,} # Marker: three tilde or more.
 2350                 )
 2351                 [ ]* \n # Whitespace and newline following marker.
 2352 
 2353                 # 2: Content
 2354                 (
 2355                     (?>
 2356                         (?!\1 [ ]* \n)  # Not a closing marker.
 2357                         .*\n+
 2358                     )+
 2359                 )
 2360 
 2361                 # Closing marker.
 2362                 \1 [ ]* \n
 2363             }xm',
 2364             array(&$this, '_doFencedCodeBlocks_callback'), $text);
 2365 
 2366         return $text;
 2367     }
 2368     public function _doFencedCodeBlocks_callback($matches) {
 2369         $codeblock = $matches[2];
 2370         $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES);
 2371         $codeblock = preg_replace_callback('/^\n+/',
 2372             array(&$this, '_doFencedCodeBlocks_newlines'), $codeblock);
 2373         $codeblock = "<pre><code>$codeblock</code></pre>";
 2374         return "\n\n".$this->hashBlock($codeblock)."\n\n";
 2375     }
 2376     public function _doFencedCodeBlocks_newlines($matches) {
 2377         return str_repeat("<br$this->empty_element_suffix",
 2378             strlen($matches[0]));
 2379     }
 2380 
 2381 
 2382     #
 2383     # Redefining emphasis markers so that emphasis by underscore does not
 2384     # work in the middle of a word.
 2385     #
 2386     public $em_relist = array(
 2387         ''  => '(?:(?<!\*)\*(?!\*)|(?<![a-zA-Z0-9_])_(?!_))(?=\S|$)(?![\.,:;]\s)',
 2388         '*' => '(?<=\S|^)(?<!\*)\*(?!\*)',
 2389         '_' => '(?<=\S|^)(?<!_)_(?![a-zA-Z0-9_])',
 2390         );
 2391     public $strong_relist = array(
 2392         ''   => '(?:(?<!\*)\*\*(?!\*)|(?<![a-zA-Z0-9_])__(?!_))(?=\S|$)(?![\.,:;]\s)',
 2393         '**' => '(?<=\S|^)(?<!\*)\*\*(?!\*)',
 2394         '__' => '(?<=\S|^)(?<!_)__(?![a-zA-Z0-9_])',
 2395         );
 2396     public $em_strong_relist = array(
 2397         ''    => '(?:(?<!\*)\*\*\*(?!\*)|(?<![a-zA-Z0-9_])___(?!_))(?=\S|$)(?![\.,:;]\s)',
 2398         '***' => '(?<=\S|^)(?<!\*)\*\*\*(?!\*)',
 2399         '___' => '(?<=\S|^)(?<!_)___(?![a-zA-Z0-9_])',
 2400         );
 2401 
 2402 
 2403     public function formParagraphs($text) {
 2404     #
 2405     #   Params:
 2406     #       $text - string to process with html <p> tags
 2407     #
 2408         # Strip leading and trailing lines:
 2409         $text = preg_replace('/\A\n+|\n+\z/', '', $text);
 2410         
 2411         $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY);
 2412 
 2413         #
 2414         # Wrap <p> tags and unhashify HTML blocks
 2415         #
 2416         foreach ($grafs as $key => $value) {
 2417             $value = trim($this->runSpanGamut($value));
 2418 
 2419             # Check if this should be enclosed in a paragraph.
 2420             # Clean tag hashes & block tag hashes are left alone.
 2421             $is_p = !preg_match('/^B\x1A[0-9]+B|^C\x1A[0-9]+C$/', $value);
 2422 
 2423             if ($is_p) {
 2424                 $value = "<p>$value</p>";
 2425             }
 2426             $grafs[$key] = $value;
 2427         }
 2428 
 2429         # Join grafs in one text, then unhash HTML tags.
 2430         $text = implode("\n\n", $grafs);
 2431 
 2432         # Finish by removing any tag hashes still present in $text.
 2433         $text = $this->unhash($text);
 2434 
 2435         return $text;
 2436     }
 2437 
 2438 
 2439     ### Footnotes
 2440 
 2441     public function stripFootnotes($text) {
 2442     #
 2443     # Strips link definitions from text, stores the URLs and titles in
 2444     # hash references.
 2445     #
 2446         $less_than_tab = $this->tab_width - 1;
 2447 
 2448         # Link defs are in the form: [^id]: url "optional title"
 2449         $text = preg_replace_callback('{
 2450             ^[ ]{0,'.$less_than_tab.'}\[\^(.+?)\][ ]?:  # note_id = $1
 2451               [ ]*
 2452               \n?                   # maybe *one* newline
 2453             (                       # text = $2 (no blank lines allowed)
 2454                 (?:
 2455                     .+              # actual text
 2456                 |
 2457                     \n              # newlines but
 2458                     (?!\[\^.+?\]:\s)# negative lookahead for footnote marker.
 2459                     (?!\n+[ ]{0,3}\S)# ensure line is not blank and followed
 2460                                     # by non-indented content
 2461                 )*
 2462             )
 2463             }xm',
 2464             array(&$this, '_stripFootnotes_callback'),
 2465             $text);
 2466         return $text;
 2467     }
 2468     public function _stripFootnotes_callback($matches) {
 2469         $note_id = $this->fn_id_prefix . $matches[1];
 2470         $this->footnotes[$note_id] = $this->outdent($matches[2]);
 2471         return ''; # String that will replace the block
 2472     }
 2473 
 2474 
 2475     public function doFootnotes($text) {
 2476     #
 2477     # Replace footnote references in $text [^id] with a special text-token
 2478     # which will be replaced by the actual footnote marker in appendFootnotes.
 2479     #
 2480         if (!$this->in_anchor) {
 2481             $text = preg_replace('{\[\^(.+?)\]}', "F\x1Afn:\\1\x1A:", $text);
 2482         }
 2483         return $text;
 2484     }
 2485 
 2486     
 2487     public function appendFootnotes($text) {
 2488     #
 2489     # Append footnote list to text.
 2490     #
 2491         $text = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}', 
 2492             array(&$this, '_appendFootnotes_callback'), $text);
 2493     
 2494         if (!empty($this->footnotes_ordered)) {
 2495             $text .= "\n\n";
 2496             $text .= "<div class=\"footnotes\">\n";
 2497             $text .= "<hr". $this->empty_element_suffix ."\n";
 2498             $text .= "<ol>\n\n";
 2499             
 2500             $attr = " rev=\"footnote\"";
 2501             if ($this->fn_backlink_class != "") {
 2502                 $class = $this->fn_backlink_class;
 2503                 $class = $this->encodeAttribute($class);
 2504                 $attr .= " class=\"$class\"";
 2505             }
 2506             if ($this->fn_backlink_title != "") {
 2507                 $title = $this->fn_backlink_title;
 2508                 $title = $this->encodeAttribute($title);
 2509                 $attr .= " title=\"$title\"";
 2510             }
 2511             $num = 0;
 2512 
 2513             while (!empty($this->footnotes_ordered)) {
 2514                 $footnote = reset($this->footnotes_ordered);
 2515                 $note_id = key($this->footnotes_ordered);
 2516                 unset($this->footnotes_ordered[$note_id]);
 2517 
 2518                 $footnote .= "\n"; # Need to append newline before parsing.
 2519                 $footnote = $this->runBlockGamut("$footnote\n");
 2520                 $footnote = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}',
 2521                     array(&$this, '_appendFootnotes_callback'), $footnote);
 2522 
 2523                 $attr = str_replace("%%", ++$num, $attr);
 2524                 $note_id = $this->encodeAttribute($note_id);
 2525 
 2526                 # Add backlink to last paragraph; create new paragraph if needed.
 2527                 $backlink = "<a href=\"#fnref:$note_id\"$attr>&#8617;</a>";
 2528                 if (preg_match('{</p>$}', $footnote)) {
 2529                     $footnote = substr($footnote, 0, -4) . "&#160;$backlink</p>";
 2530                 } else {
 2531                     $footnote .= "\n\n<p>$backlink</p>";
 2532                 }
 2533 
 2534                 $text .= "<li id=\"fn:$note_id\">\n";
 2535                 $text .= $footnote . "\n";
 2536                 $text .= "</li>\n\n";
 2537             }
 2538 
 2539             $text .= "</ol>\n";
 2540             $text .= "</div>";
 2541         }
 2542         return $text;
 2543     }
 2544     public function _appendFootnotes_callback($matches) {
 2545         $node_id = $this->fn_id_prefix . $matches[1];
 2546 
 2547         # Create footnote marker only if it has a corresponding footnote *and*
 2548         # the footnote hasn't been used by another marker.
 2549         if (isset($this->footnotes[$node_id])) {
 2550             # Transfert footnote content to the ordered list.
 2551             $this->footnotes_ordered[$node_id] = $this->footnotes[$node_id];
 2552             unset($this->footnotes[$node_id]);
 2553 
 2554             $num = $this->footnote_counter++;
 2555             $attr = " rel=\"footnote\"";
 2556             if ($this->fn_link_class != "") {
 2557                 $class = $this->fn_link_class;
 2558                 $class = $this->encodeAttribute($class);
 2559                 $attr .= " class=\"$class\"";
 2560             }
 2561             if ($this->fn_link_title != "") {
 2562                 $title = $this->fn_link_title;
 2563                 $title = $this->encodeAttribute($title);
 2564                 $attr .= " title=\"$title\"";
 2565             }
 2566 
 2567             $attr = str_replace("%%", $num, $attr);
 2568             $node_id = $this->encodeAttribute($node_id);
 2569 
 2570             return
 2571                 "<sup id=\"fnref:$node_id\">".
 2572                 "<a href=\"#fn:$node_id\"$attr>$num</a>".
 2573                 "</sup>";
 2574         }
 2575 
 2576         return "[^".$matches[1]."]";
 2577     }
 2578 
 2579 
 2580     ### Abbreviations ###
 2581 
 2582     public function stripAbbreviations($text) {
 2583     #
 2584     # Strips abbreviations from text, stores titles in hash references.
 2585     #
 2586         $less_than_tab = $this->tab_width - 1;
 2587 
 2588         # Link defs are in the form: [id]*: url "optional title"
 2589         $text = preg_replace_callback('{
 2590             ^[ ]{0,'.$less_than_tab.'}\*\[(.+?)\][ ]?:  # abbr_id = $1
 2591             (.*)                    # text = $2 (no blank lines allowed)
 2592             }xm',
 2593             array(&$this, '_stripAbbreviations_callback'),
 2594             $text);
 2595         return $text;
 2596     }
 2597     public function _stripAbbreviations_callback($matches) {
 2598         $abbr_word = $matches[1];
 2599         $abbr_desc = $matches[2];
 2600         if ($this->abbr_word_re)
 2601             $this->abbr_word_re .= '|';
 2602         $this->abbr_word_re .= preg_quote($abbr_word);
 2603         $this->abbr_desciptions[$abbr_word] = trim($abbr_desc);
 2604         return ''; # String that will replace the block
 2605     }
 2606 
 2607 
 2608     public function doAbbreviations($text) {
 2609     #
 2610     # Find defined abbreviations in text and wrap them in <abbr> elements.
 2611     #
 2612         if ($this->abbr_word_re) {
 2613             // cannot use the /x modifier because abbr_word_re may
 2614             // contain significant spaces:
 2615             $text = preg_replace_callback('{'.
 2616                 '(?<![\w\x1A])'.
 2617                 '(?:'.$this->abbr_word_re.')'.
 2618                 '(?![\w\x1A])'.
 2619                 '}',
 2620                 array(&$this, '_doAbbreviations_callback'), $text);
 2621         }
 2622         return $text;
 2623     }
 2624     public function _doAbbreviations_callback($matches) {
 2625         $abbr = $matches[0];
 2626         if (isset($this->abbr_desciptions[$abbr])) {
 2627             $desc = $this->abbr_desciptions[$abbr];
 2628             if (empty($desc)) {
 2629                 return $this->hashPart("<abbr>$abbr</abbr>");
 2630             } else {
 2631                 $desc = $this->encodeAttribute($desc);
 2632                 return $this->hashPart("<abbr title=\"$desc\">$abbr</abbr>");
 2633             }
 2634         } else {
 2635             return $matches[0];
 2636         }
 2637     }
 2638 
 2639 }