PageRenderTime 577ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 2ms

/system/vendor/Markdown.php

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