PageRenderTime 77ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/kirby/parsers/markdown.extra.php

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