PageRenderTime 31ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/bundles/docs/libraries/markdown.php

https://bitbucket.org/Maron1/taqman
PHP | 1793 lines | 1204 code | 207 blank | 382 comment | 85 complexity | 415850eb95d21c51e64f78a647552a8a MD5 | raw file
  1. <?php
  2. #
  3. # Markdown Extra - A text-to-HTML conversion tool for web writers
  4. #
  5. # PHP Markdown & Extra
  6. # Copyright (c) 2004-2012 Michel Fortin
  7. # <http://michelf.com/projects/php-markdown/>
  8. #
  9. # Original Markdown
  10. # Copyright (c) 2004-2006 John Gruber
  11. # <http://daringfireball.net/projects/markdown/>
  12. #
  13. define( 'MARKDOWN_VERSION', "1.0.1o" ); # Sun 8 Jan 2012
  14. define( 'MARKDOWNEXTRA_VERSION', "1.2.5" ); # Sun 8 Jan 2012
  15. #
  16. # Global default settings:
  17. #
  18. # Change to ">" for HTML output
  19. @define( 'MARKDOWN_EMPTY_ELEMENT_SUFFIX', " />");
  20. # Define the width of a tab for code blocks.
  21. @define( 'MARKDOWN_TAB_WIDTH', 4 );
  22. # Optional title attribute for footnote links and backlinks.
  23. @define( 'MARKDOWN_FN_LINK_TITLE', "" );
  24. @define( 'MARKDOWN_FN_BACKLINK_TITLE', "" );
  25. # Optional class attribute for footnote links and backlinks.
  26. @define( 'MARKDOWN_FN_LINK_CLASS', "" );
  27. @define( 'MARKDOWN_FN_BACKLINK_CLASS', "" );
  28. #
  29. # WordPress settings:
  30. #
  31. # Change to false to remove Markdown from posts and/or comments.
  32. @define( 'MARKDOWN_WP_POSTS', true );
  33. @define( 'MARKDOWN_WP_COMMENTS', true );
  34. ### Standard Function Interface ###
  35. @define( 'MARKDOWN_PARSER_CLASS', 'MarkdownExtra_Parser' );
  36. function Markdown($text) {
  37. #
  38. # Initialize the parser and return the result of its transform method.
  39. #
  40. # Setup static parser variable.
  41. static $parser;
  42. if (!isset($parser)) {
  43. $parser_class = MARKDOWN_PARSER_CLASS;
  44. $parser = new $parser_class;
  45. }
  46. # Transform text using parser.
  47. return $parser->transform($text);
  48. }
  49. ### WordPress Plugin Interface ###
  50. /*
  51. Plugin Name: Markdown Extra
  52. Plugin URI: http://michelf.com/projects/php-markdown/
  53. 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>
  54. Version: 1.2.5
  55. Author: Michel Fortin
  56. Author URI: http://michelf.com/
  57. */
  58. if (isset($wp_version)) {
  59. # More details about how it works here:
  60. # <http://michelf.com/weblog/2005/wordpress-text-flow-vs-markdown/>
  61. # Post content and excerpts
  62. # - Remove WordPress paragraph generator.
  63. # - Run Markdown on excerpt, then remove all tags.
  64. # - Add paragraph tag around the excerpt, but remove it for the excerpt rss.
  65. if (MARKDOWN_WP_POSTS) {
  66. remove_filter('the_content', 'wpautop');
  67. remove_filter('the_content_rss', 'wpautop');
  68. remove_filter('the_excerpt', 'wpautop');
  69. add_filter('the_content', 'mdwp_MarkdownPost', 6);
  70. add_filter('the_content_rss', 'mdwp_MarkdownPost', 6);
  71. add_filter('get_the_excerpt', 'mdwp_MarkdownPost', 6);
  72. add_filter('get_the_excerpt', 'trim', 7);
  73. add_filter('the_excerpt', 'mdwp_add_p');
  74. add_filter('the_excerpt_rss', 'mdwp_strip_p');
  75. remove_filter('content_save_pre', 'balanceTags', 50);
  76. remove_filter('excerpt_save_pre', 'balanceTags', 50);
  77. add_filter('the_content', 'balanceTags', 50);
  78. add_filter('get_the_excerpt', 'balanceTags', 9);
  79. }
  80. # Add a footnote id prefix to posts when inside a loop.
  81. function mdwp_MarkdownPost($text) {
  82. static $parser;
  83. if (!$parser) {
  84. $parser_class = MARKDOWN_PARSER_CLASS;
  85. $parser = new $parser_class;
  86. }
  87. if (is_single() || is_page() || is_feed()) {
  88. $parser->fn_id_prefix = "";
  89. } else {
  90. $parser->fn_id_prefix = get_the_ID() . ".";
  91. }
  92. return $parser->transform($text);
  93. }
  94. # Comments
  95. # - Remove WordPress paragraph generator.
  96. # - Remove WordPress auto-link generator.
  97. # - Scramble important tags before passing them to the kses filter.
  98. # - Run Markdown on excerpt then remove paragraph tags.
  99. if (MARKDOWN_WP_COMMENTS) {
  100. remove_filter('comment_text', 'wpautop', 30);
  101. remove_filter('comment_text', 'make_clickable');
  102. add_filter('pre_comment_content', 'Markdown', 6);
  103. add_filter('pre_comment_content', 'mdwp_hide_tags', 8);
  104. add_filter('pre_comment_content', 'mdwp_show_tags', 12);
  105. add_filter('get_comment_text', 'Markdown', 6);
  106. add_filter('get_comment_excerpt', 'Markdown', 6);
  107. add_filter('get_comment_excerpt', 'mdwp_strip_p', 7);
  108. global $mdwp_hidden_tags, $mdwp_placeholders;
  109. $mdwp_hidden_tags = explode(' ',
  110. '<p> </p> <pre> </pre> <ol> </ol> <ul> </ul> <li> </li>');
  111. $mdwp_placeholders = explode(' ', str_rot13(
  112. 'pEj07ZbbBZ U1kqgh4w4p pre2zmeN6K QTi31t9pre ol0MP1jzJR '.
  113. 'ML5IjmbRol ulANi1NsGY J7zRLJqPul liA8ctl16T K9nhooUHli'));
  114. }
  115. function mdwp_add_p($text) {
  116. if (!preg_match('{^$|^<(p|ul|ol|dl|pre|blockquote)>}i', $text)) {
  117. $text = '<p>'.$text.'</p>';
  118. $text = preg_replace('{\n{2,}}', "</p>\n\n<p>", $text);
  119. }
  120. return $text;
  121. }
  122. function mdwp_strip_p($t) { return preg_replace('{</?p>}i', '', $t); }
  123. function mdwp_hide_tags($text) {
  124. global $mdwp_hidden_tags, $mdwp_placeholders;
  125. return str_replace($mdwp_hidden_tags, $mdwp_placeholders, $text);
  126. }
  127. function mdwp_show_tags($text) {
  128. global $mdwp_hidden_tags, $mdwp_placeholders;
  129. return str_replace($mdwp_placeholders, $mdwp_hidden_tags, $text);
  130. }
  131. }
  132. ### bBlog Plugin Info ###
  133. function identify_modifier_markdown() {
  134. return array(
  135. 'name' => 'markdown',
  136. 'type' => 'modifier',
  137. 'nicename' => 'PHP Markdown Extra',
  138. 'description' => 'A text-to-HTML conversion tool for web writers',
  139. 'authors' => 'Michel Fortin and John Gruber',
  140. 'licence' => 'GPL',
  141. 'version' => MARKDOWNEXTRA_VERSION,
  142. '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>',
  143. );
  144. }
  145. ### Smarty Modifier Interface ###
  146. function smarty_modifier_markdown($text) {
  147. return Markdown($text);
  148. }
  149. ### Textile Compatibility Mode ###
  150. # Rename this file to "classTextile.php" and it can replace Textile everywhere.
  151. if (strcasecmp(substr(__FILE__, -16), "classTextile.php") == 0) {
  152. # Try to include PHP SmartyPants. Should be in the same directory.
  153. @include_once 'smartypants.php';
  154. # Fake Textile class. It calls Markdown instead.
  155. class Textile {
  156. function TextileThis($text, $lite='', $encode='') {
  157. if ($lite == '' && $encode == '') $text = Markdown($text);
  158. if (function_exists('SmartyPants')) $text = SmartyPants($text);
  159. return $text;
  160. }
  161. # Fake restricted version: restrictions are not supported for now.
  162. function TextileRestricted($text, $lite='', $noimage='') {
  163. return $this->TextileThis($text, $lite);
  164. }
  165. # Workaround to ensure compatibility with TextPattern 4.0.3.
  166. function blockLite($text) { return $text; }
  167. }
  168. }
  169. #
  170. # Markdown Parser Class
  171. #
  172. class Markdown_Parser {
  173. # Regex to match balanced [brackets].
  174. # Needed to insert a maximum bracked depth while converting to PHP.
  175. var $nested_brackets_depth = 6;
  176. var $nested_brackets_re;
  177. var $nested_url_parenthesis_depth = 4;
  178. var $nested_url_parenthesis_re;
  179. # Table of hash values for escaped characters:
  180. var $escape_chars = '\`*_{}[]()>#+-.!';
  181. var $escape_chars_re;
  182. # Change to ">" for HTML output.
  183. var $empty_element_suffix = MARKDOWN_EMPTY_ELEMENT_SUFFIX;
  184. var $tab_width = MARKDOWN_TAB_WIDTH;
  185. # Change to `true` to disallow markup or entities.
  186. var $no_markup = false;
  187. var $no_entities = false;
  188. # Predefined urls and titles for reference links and images.
  189. var $predef_urls = array();
  190. var $predef_titles = array();
  191. function Markdown_Parser() {
  192. #
  193. # Constructor function. Initialize appropriate member variables.
  194. #
  195. $this->_initDetab();
  196. $this->prepareItalicsAndBold();
  197. $this->nested_brackets_re =
  198. str_repeat('(?>[^\[\]]+|\[', $this->nested_brackets_depth).
  199. str_repeat('\])*', $this->nested_brackets_depth);
  200. $this->nested_url_parenthesis_re =
  201. str_repeat('(?>[^()\s]+|\(', $this->nested_url_parenthesis_depth).
  202. str_repeat('(?>\)))*', $this->nested_url_parenthesis_depth);
  203. $this->escape_chars_re = '['.preg_quote($this->escape_chars).']';
  204. # Sort document, block, and span gamut in ascendent priority order.
  205. asort($this->document_gamut);
  206. asort($this->block_gamut);
  207. asort($this->span_gamut);
  208. }
  209. # Internal hashes used during transformation.
  210. var $urls = array();
  211. var $titles = array();
  212. var $html_hashes = array();
  213. # Status flag to avoid invalid nesting.
  214. var $in_anchor = false;
  215. function setup() {
  216. #
  217. # Called before the transformation process starts to setup parser
  218. # states.
  219. #
  220. # Clear global hashes.
  221. $this->urls = $this->predef_urls;
  222. $this->titles = $this->predef_titles;
  223. $this->html_hashes = array();
  224. $in_anchor = false;
  225. }
  226. function teardown() {
  227. #
  228. # Called after the transformation process to clear any variable
  229. # which may be taking up memory unnecessarly.
  230. #
  231. $this->urls = array();
  232. $this->titles = array();
  233. $this->html_hashes = array();
  234. }
  235. function transform($text) {
  236. #
  237. # Main function. Performs some preprocessing on the input text
  238. # and pass it through the document gamut.
  239. #
  240. $this->setup();
  241. # Remove UTF-8 BOM and marker character in input, if present.
  242. $text = preg_replace('{^\xEF\xBB\xBF|\x1A}', '', $text);
  243. # Standardize line endings:
  244. # DOS to Unix and Mac to Unix
  245. $text = preg_replace('{\r\n?}', "\n", $text);
  246. # Make sure $text ends with a couple of newlines:
  247. $text .= "\n\n";
  248. # Convert all tabs to spaces.
  249. $text = $this->detab($text);
  250. # Turn block-level HTML blocks into hash entries
  251. $text = $this->hashHTMLBlocks($text);
  252. # Strip any lines consisting only of spaces and tabs.
  253. # This makes subsequent regexen easier to write, because we can
  254. # match consecutive blank lines with /\n+/ instead of something
  255. # contorted like /[ ]*\n+/ .
  256. $text = preg_replace('/^[ ]+$/m', '', $text);
  257. # Run document gamut methods.
  258. foreach ($this->document_gamut as $method => $priority) {
  259. $text = $this->$method($text);
  260. }
  261. $this->teardown();
  262. return $text . "\n";
  263. }
  264. var $document_gamut = array(
  265. # Strip link definitions, store in hashes.
  266. "stripLinkDefinitions" => 20,
  267. "runBasicBlockGamut" => 30,
  268. );
  269. function stripLinkDefinitions($text) {
  270. #
  271. # Strips link definitions from text, stores the URLs and titles in
  272. # hash references.
  273. #
  274. $less_than_tab = $this->tab_width - 1;
  275. # Link defs are in the form: ^[id]: url "optional title"
  276. $text = preg_replace_callback('{
  277. ^[ ]{0,'.$less_than_tab.'}\[(.+)\][ ]?: # id = $1
  278. [ ]*
  279. \n? # maybe *one* newline
  280. [ ]*
  281. (?:
  282. <(.+?)> # url = $2
  283. |
  284. (\S+?) # url = $3
  285. )
  286. [ ]*
  287. \n? # maybe one newline
  288. [ ]*
  289. (?:
  290. (?<=\s) # lookbehind for whitespace
  291. ["(]
  292. (.*?) # title = $4
  293. [")]
  294. [ ]*
  295. )? # title is optional
  296. (?:\n+|\Z)
  297. }xm',
  298. array(&$this, '_stripLinkDefinitions_callback'),
  299. $text);
  300. return $text;
  301. }
  302. function _stripLinkDefinitions_callback($matches) {
  303. $link_id = strtolower($matches[1]);
  304. $url = $matches[2] == '' ? $matches[3] : $matches[2];
  305. $this->urls[$link_id] = $url;
  306. $this->titles[$link_id] =& $matches[4];
  307. return ''; # String that will replace the block
  308. }
  309. function hashHTMLBlocks($text) {
  310. if ($this->no_markup) return $text;
  311. $less_than_tab = $this->tab_width - 1;
  312. # Hashify HTML blocks:
  313. # We only want to do this for block-level HTML tags, such as headers,
  314. # lists, and tables. That's because we still want to wrap <p>s around
  315. # "paragraphs" that are wrapped in non-block-level tags, such as anchors,
  316. # phrase emphasis, and spans. The list of tags we're looking for is
  317. # hard-coded:
  318. #
  319. # * List "a" is made of tags which can be both inline or block-level.
  320. # These will be treated block-level when the start tag is alone on
  321. # its line, otherwise they're not matched here and will be taken as
  322. # inline later.
  323. # * List "b" is made of tags which are always block-level;
  324. #
  325. $block_tags_a_re = 'ins|del';
  326. $block_tags_b_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|'.
  327. 'script|noscript|form|fieldset|iframe|math';
  328. # Regular expression for the content of a block tag.
  329. $nested_tags_level = 4;
  330. $attr = '
  331. (?> # optional tag attributes
  332. \s # starts with whitespace
  333. (?>
  334. [^>"/]+ # text outside quotes
  335. |
  336. /+(?!>) # slash not followed by ">"
  337. |
  338. "[^"]*" # text inside double quotes (tolerate ">")
  339. |
  340. \'[^\']*\' # text inside single quotes (tolerate ">")
  341. )*
  342. )?
  343. ';
  344. $content =
  345. str_repeat('
  346. (?>
  347. [^<]+ # content without tag
  348. |
  349. <\2 # nested opening tag
  350. '.$attr.' # attributes
  351. (?>
  352. />
  353. |
  354. >', $nested_tags_level). # end of opening tag
  355. '.*?'. # last level nested tag content
  356. str_repeat('
  357. </\2\s*> # closing nested tag
  358. )
  359. |
  360. <(?!/\2\s*> # other tags with a different name
  361. )
  362. )*',
  363. $nested_tags_level);
  364. $content2 = str_replace('\2', '\3', $content);
  365. # First, look for nested blocks, e.g.:
  366. # <div>
  367. # <div>
  368. # tags for inner block must be indented.
  369. # </div>
  370. # </div>
  371. #
  372. # The outermost tags must start at the left margin for this to match, and
  373. # the inner nested divs must be indented.
  374. # We need to do this before the next, more liberal match, because the next
  375. # match will start at the first `<div>` and stop at the first `</div>`.
  376. $text = preg_replace_callback('{(?>
  377. (?>
  378. (?<=\n\n) # Starting after a blank line
  379. | # or
  380. \A\n? # the beginning of the doc
  381. )
  382. ( # save in $1
  383. # Match from `\n<tag>` to `</tag>\n`, handling nested tags
  384. # in between.
  385. [ ]{0,'.$less_than_tab.'}
  386. <('.$block_tags_b_re.')# start tag = $2
  387. '.$attr.'> # attributes followed by > and \n
  388. '.$content.' # content, support nesting
  389. </\2> # the matching end tag
  390. [ ]* # trailing spaces/tabs
  391. (?=\n+|\Z) # followed by a newline or end of document
  392. | # Special version for tags of group a.
  393. [ ]{0,'.$less_than_tab.'}
  394. <('.$block_tags_a_re.')# start tag = $3
  395. '.$attr.'>[ ]*\n # attributes followed by >
  396. '.$content2.' # content, support nesting
  397. </\3> # the matching end tag
  398. [ ]* # trailing spaces/tabs
  399. (?=\n+|\Z) # followed by a newline or end of document
  400. | # Special case just for <hr />. It was easier to make a special
  401. # case than to make the other regex more complicated.
  402. [ ]{0,'.$less_than_tab.'}
  403. <(hr) # start tag = $2
  404. '.$attr.' # attributes
  405. /?> # the matching end tag
  406. [ ]*
  407. (?=\n{2,}|\Z) # followed by a blank line or end of document
  408. | # Special case for standalone HTML comments:
  409. [ ]{0,'.$less_than_tab.'}
  410. (?s:
  411. <!-- .*? -->
  412. )
  413. [ ]*
  414. (?=\n{2,}|\Z) # followed by a blank line or end of document
  415. | # PHP and ASP-style processor instructions (<? and <%)
  416. [ ]{0,'.$less_than_tab.'}
  417. (?s:
  418. <([?%]) # $2
  419. .*?
  420. \2>
  421. )
  422. [ ]*
  423. (?=\n{2,}|\Z) # followed by a blank line or end of document
  424. )
  425. )}Sxmi',
  426. array(&$this, '_hashHTMLBlocks_callback'),
  427. $text);
  428. return $text;
  429. }
  430. function _hashHTMLBlocks_callback($matches) {
  431. $text = $matches[1];
  432. $key = $this->hashBlock($text);
  433. return "\n\n$key\n\n";
  434. }
  435. function hashPart($text, $boundary = 'X') {
  436. #
  437. # Called whenever a tag must be hashed when a function insert an atomic
  438. # element in the text stream. Passing $text to through this function gives
  439. # a unique text-token which will be reverted back when calling unhash.
  440. #
  441. # The $boundary argument specify what character should be used to surround
  442. # the token. By convension, "B" is used for block elements that needs not
  443. # to be wrapped into paragraph tags at the end, ":" is used for elements
  444. # that are word separators and "X" is used in the general case.
  445. #
  446. # Swap back any tag hash found in $text so we do not have to `unhash`
  447. # multiple times at the end.
  448. $text = $this->unhash($text);
  449. # Then hash the block.
  450. static $i = 0;
  451. $key = "$boundary\x1A" . ++$i . $boundary;
  452. $this->html_hashes[$key] = $text;
  453. return $key; # String that will replace the tag.
  454. }
  455. function hashBlock($text) {
  456. #
  457. # Shortcut function for hashPart with block-level boundaries.
  458. #
  459. return $this->hashPart($text, 'B');
  460. }
  461. var $block_gamut = array(
  462. #
  463. # These are all the transformations that form block-level
  464. # tags like paragraphs, headers, and list items.
  465. #
  466. "doHeaders" => 10,
  467. "doHorizontalRules" => 20,
  468. "doLists" => 40,
  469. "doCodeBlocks" => 50,
  470. "doBlockQuotes" => 60,
  471. );
  472. function runBlockGamut($text) {
  473. #
  474. # Run block gamut tranformations.
  475. #
  476. # We need to escape raw HTML in Markdown source before doing anything
  477. # else. This need to be done for each block, and not only at the
  478. # begining in the Markdown function since hashed blocks can be part of
  479. # list items and could have been indented. Indented blocks would have
  480. # been seen as a code block in a previous pass of hashHTMLBlocks.
  481. $text = $this->hashHTMLBlocks($text);
  482. return $this->runBasicBlockGamut($text);
  483. }
  484. function runBasicBlockGamut($text) {
  485. #
  486. # Run block gamut tranformations, without hashing HTML blocks. This is
  487. # useful when HTML blocks are known to be already hashed, like in the first
  488. # whole-document pass.
  489. #
  490. foreach ($this->block_gamut as $method => $priority) {
  491. $text = $this->$method($text);
  492. }
  493. # Finally form paragraph and restore hashed blocks.
  494. $text = $this->formParagraphs($text);
  495. return $text;
  496. }
  497. function doHorizontalRules($text) {
  498. # Do Horizontal Rules:
  499. return preg_replace(
  500. '{
  501. ^[ ]{0,3} # Leading space
  502. ([-*_]) # $1: First marker
  503. (?> # Repeated marker group
  504. [ ]{0,2} # Zero, one, or two spaces.
  505. \1 # Marker character
  506. ){2,} # Group repeated at least twice
  507. [ ]* # Tailing spaces
  508. $ # End of line.
  509. }mx',
  510. "\n".$this->hashBlock("<hr$this->empty_element_suffix")."\n",
  511. $text);
  512. }
  513. var $span_gamut = array(
  514. #
  515. # These are all the transformations that occur *within* block-level
  516. # tags like paragraphs, headers, and list items.
  517. #
  518. # Process character escapes, code spans, and inline HTML
  519. # in one shot.
  520. "parseSpan" => -30,
  521. # Process anchor and image tags. Images must come first,
  522. # because ![foo][f] looks like an anchor.
  523. "doImages" => 10,
  524. "doAnchors" => 20,
  525. # Make links out of things like `<http://example.com/>`
  526. # Must come after doAnchors, because you can use < and >
  527. # delimiters in inline links like [this](<url>).
  528. "doAutoLinks" => 30,
  529. "encodeAmpsAndAngles" => 40,
  530. "doItalicsAndBold" => 50,
  531. "doHardBreaks" => 60,
  532. );
  533. function runSpanGamut($text) {
  534. #
  535. # Run span gamut tranformations.
  536. #
  537. foreach ($this->span_gamut as $method => $priority) {
  538. $text = $this->$method($text);
  539. }
  540. return $text;
  541. }
  542. function doHardBreaks($text) {
  543. # Do hard breaks:
  544. return preg_replace_callback('/ {2,}\n/',
  545. array(&$this, '_doHardBreaks_callback'), $text);
  546. }
  547. function _doHardBreaks_callback($matches) {
  548. return $this->hashPart("<br$this->empty_element_suffix\n");
  549. }
  550. function doAnchors($text) {
  551. #
  552. # Turn Markdown link shortcuts into XHTML <a> tags.
  553. #
  554. if ($this->in_anchor) return $text;
  555. $this->in_anchor = true;
  556. #
  557. # First, handle reference-style links: [link text] [id]
  558. #
  559. $text = preg_replace_callback('{
  560. ( # wrap whole match in $1
  561. \[
  562. ('.$this->nested_brackets_re.') # link text = $2
  563. \]
  564. [ ]? # one optional space
  565. (?:\n[ ]*)? # one optional newline followed by spaces
  566. \[
  567. (.*?) # id = $3
  568. \]
  569. )
  570. }xs',
  571. array(&$this, '_doAnchors_reference_callback'), $text);
  572. #
  573. # Next, inline-style links: [link text](url "optional title")
  574. #
  575. $text = preg_replace_callback('{
  576. ( # wrap whole match in $1
  577. \[
  578. ('.$this->nested_brackets_re.') # link text = $2
  579. \]
  580. \( # literal paren
  581. [ \n]*
  582. (?:
  583. <(.+?)> # href = $3
  584. |
  585. ('.$this->nested_url_parenthesis_re.') # href = $4
  586. )
  587. [ \n]*
  588. ( # $5
  589. ([\'"]) # quote char = $6
  590. (.*?) # Title = $7
  591. \6 # matching quote
  592. [ \n]* # ignore any spaces/tabs between closing quote and )
  593. )? # title is optional
  594. \)
  595. )
  596. }xs',
  597. array(&$this, '_doAnchors_inline_callback'), $text);
  598. #
  599. # Last, handle reference-style shortcuts: [link text]
  600. # These must come last in case you've also got [link text][1]
  601. # or [link text](/foo)
  602. #
  603. $text = preg_replace_callback('{
  604. ( # wrap whole match in $1
  605. \[
  606. ([^\[\]]+) # link text = $2; can\'t contain [ or ]
  607. \]
  608. )
  609. }xs',
  610. array(&$this, '_doAnchors_reference_callback'), $text);
  611. $this->in_anchor = false;
  612. return $text;
  613. }
  614. function _doAnchors_reference_callback($matches) {
  615. $whole_match = $matches[1];
  616. $link_text = $matches[2];
  617. $link_id =& $matches[3];
  618. if ($link_id == "") {
  619. # for shortcut links like [this][] or [this].
  620. $link_id = $link_text;
  621. }
  622. # lower-case and turn embedded newlines into spaces
  623. $link_id = strtolower($link_id);
  624. $link_id = preg_replace('{[ ]?\n}', ' ', $link_id);
  625. if (isset($this->urls[$link_id])) {
  626. $url = $this->urls[$link_id];
  627. $url = URL::to($url);
  628. $url = $this->encodeAttribute($url);
  629. $result = "<a href=\"$url\"";
  630. if ( isset( $this->titles[$link_id] ) ) {
  631. $title = $this->titles[$link_id];
  632. $title = $this->encodeAttribute($title);
  633. $result .= " title=\"$title\"";
  634. }
  635. $link_text = $this->runSpanGamut($link_text);
  636. $result .= ">$link_text</a>";
  637. $result = $this->hashPart($result);
  638. }
  639. else {
  640. $result = $whole_match;
  641. }
  642. return $result;
  643. }
  644. function _doAnchors_inline_callback($matches) {
  645. $whole_match = $matches[1];
  646. $link_text = $this->runSpanGamut($matches[2]);
  647. $url = $matches[3] == '' ? $matches[4] : $matches[3];
  648. $title =& $matches[7];
  649. $url = URL::to($url);
  650. $url = $this->encodeAttribute($url);
  651. $result = "<a href=\"$url\"";
  652. if (isset($title)) {
  653. $title = $this->encodeAttribute($title);
  654. $result .= " title=\"$title\"";
  655. }
  656. $link_text = $this->runSpanGamut($link_text);
  657. $result .= ">$link_text</a>";
  658. return $this->hashPart($result);
  659. }
  660. function doImages($text) {
  661. #
  662. # Turn Markdown image shortcuts into <img> tags.
  663. #
  664. #
  665. # First, handle reference-style labeled images: ![alt text][id]
  666. #
  667. $text = preg_replace_callback('{
  668. ( # wrap whole match in $1
  669. !\[
  670. ('.$this->nested_brackets_re.') # alt text = $2
  671. \]
  672. [ ]? # one optional space
  673. (?:\n[ ]*)? # one optional newline followed by spaces
  674. \[
  675. (.*?) # id = $3
  676. \]
  677. )
  678. }xs',
  679. array(&$this, '_doImages_reference_callback'), $text);
  680. #
  681. # Next, handle inline images: ![alt text](url "optional title")
  682. # Don't forget: encode * and _
  683. #
  684. $text = preg_replace_callback('{
  685. ( # wrap whole match in $1
  686. !\[
  687. ('.$this->nested_brackets_re.') # alt text = $2
  688. \]
  689. \s? # One optional whitespace character
  690. \( # literal paren
  691. [ \n]*
  692. (?:
  693. <(\S*)> # src url = $3
  694. |
  695. ('.$this->nested_url_parenthesis_re.') # src url = $4
  696. )
  697. [ \n]*
  698. ( # $5
  699. ([\'"]) # quote char = $6
  700. (.*?) # title = $7
  701. \6 # matching quote
  702. [ \n]*
  703. )? # title is optional
  704. \)
  705. )
  706. }xs',
  707. array(&$this, '_doImages_inline_callback'), $text);
  708. return $text;
  709. }
  710. function _doImages_reference_callback($matches) {
  711. $whole_match = $matches[1];
  712. $alt_text = $matches[2];
  713. $link_id = strtolower($matches[3]);
  714. if ($link_id == "") {
  715. $link_id = strtolower($alt_text); # for shortcut links like ![this][].
  716. }
  717. $alt_text = $this->encodeAttribute($alt_text);
  718. if (isset($this->urls[$link_id])) {
  719. $url = $this->encodeAttribute($this->urls[$link_id]);
  720. $result = "<img src=\"$url\" alt=\"$alt_text\"";
  721. if (isset($this->titles[$link_id])) {
  722. $title = $this->titles[$link_id];
  723. $title = $this->encodeAttribute($title);
  724. $result .= " title=\"$title\"";
  725. }
  726. $result .= $this->empty_element_suffix;
  727. $result = $this->hashPart($result);
  728. }
  729. else {
  730. # If there's no such link ID, leave intact:
  731. $result = $whole_match;
  732. }
  733. return $result;
  734. }
  735. function _doImages_inline_callback($matches) {
  736. $whole_match = $matches[1];
  737. $alt_text = $matches[2];
  738. $url = $matches[3] == '' ? $matches[4] : $matches[3];
  739. $title =& $matches[7];
  740. $alt_text = $this->encodeAttribute($alt_text);
  741. $url = $this->encodeAttribute($url);
  742. $result = "<img src=\"$url\" alt=\"$alt_text\"";
  743. if (isset($title)) {
  744. $title = $this->encodeAttribute($title);
  745. $result .= " title=\"$title\""; # $title already quoted
  746. }
  747. $result .= $this->empty_element_suffix;
  748. return $this->hashPart($result);
  749. }
  750. function doHeaders($text) {
  751. # Setext-style headers:
  752. # Header 1
  753. # ========
  754. #
  755. # Header 2
  756. # --------
  757. #
  758. $text = preg_replace_callback('{ ^(.+?)[ ]*\n(=+|-+)[ ]*\n+ }mx',
  759. array(&$this, '_doHeaders_callback_setext'), $text);
  760. # atx-style headers:
  761. # # Header 1
  762. # ## Header 2
  763. # ## Header 2 with closing hashes ##
  764. # ...
  765. # ###### Header 6
  766. #
  767. $text = preg_replace_callback('{
  768. ^(\#{1,6}) # $1 = string of #\'s
  769. [ ]*
  770. (.+?) # $2 = Header text
  771. [ ]*
  772. \#* # optional closing #\'s (not counted)
  773. \n+
  774. }xm',
  775. array(&$this, '_doHeaders_callback_atx'), $text);
  776. return $text;
  777. }
  778. function _doHeaders_callback_setext($matches) {
  779. # Terrible hack to check we haven't found an empty list item.
  780. if ($matches[2] == '-' && preg_match('{^-(?: |$)}', $matches[1]))
  781. return $matches[0];
  782. $level = $matches[2]{0} == '=' ? 1 : 2;
  783. $block = "<h$level>".$this->runSpanGamut($matches[1])."</h$level>";
  784. return "\n" . $this->hashBlock($block) . "\n\n";
  785. }
  786. function _doHeaders_callback_atx($matches) {
  787. $level = strlen($matches[1]);
  788. $block = "<h$level>".$this->runSpanGamut($matches[2])."</h$level>";
  789. return "\n" . $this->hashBlock($block) . "\n\n";
  790. }
  791. function doLists($text) {
  792. #
  793. # Form HTML ordered (numbered) and unordered (bulleted) lists.
  794. #
  795. $less_than_tab = $this->tab_width - 1;
  796. # Re-usable patterns to match list item bullets and number markers:
  797. $marker_ul_re = '[*+-]';
  798. $marker_ol_re = '\d+[\.]';
  799. $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)";
  800. $markers_relist = array(
  801. $marker_ul_re => $marker_ol_re,
  802. $marker_ol_re => $marker_ul_re,
  803. );
  804. foreach ($markers_relist as $marker_re => $other_marker_re) {
  805. # Re-usable pattern to match any entirel ul or ol list:
  806. $whole_list_re = '
  807. ( # $1 = whole list
  808. ( # $2
  809. ([ ]{0,'.$less_than_tab.'}) # $3 = number of spaces
  810. ('.$marker_re.') # $4 = first list item marker
  811. [ ]+
  812. )
  813. (?s:.+?)
  814. ( # $5
  815. \z
  816. |
  817. \n{2,}
  818. (?=\S)
  819. (?! # Negative lookahead for another list item marker
  820. [ ]*
  821. '.$marker_re.'[ ]+
  822. )
  823. |
  824. (?= # Lookahead for another kind of list
  825. \n
  826. \3 # Must have the same indentation
  827. '.$other_marker_re.'[ ]+
  828. )
  829. )
  830. )
  831. '; // mx
  832. # We use a different prefix before nested lists than top-level lists.
  833. # See extended comment in _ProcessListItems().
  834. if ($this->list_level) {
  835. $text = preg_replace_callback('{
  836. ^
  837. '.$whole_list_re.'
  838. }mx',
  839. array(&$this, '_doLists_callback'), $text);
  840. }
  841. else {
  842. $text = preg_replace_callback('{
  843. (?:(?<=\n)\n|\A\n?) # Must eat the newline
  844. '.$whole_list_re.'
  845. }mx',
  846. array(&$this, '_doLists_callback'), $text);
  847. }
  848. }
  849. return $text;
  850. }
  851. function _doLists_callback($matches) {
  852. # Re-usable patterns to match list item bullets and number markers:
  853. $marker_ul_re = '[*+-]';
  854. $marker_ol_re = '\d+[\.]';
  855. $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)";
  856. $list = $matches[1];
  857. $list_type = preg_match("/$marker_ul_re/", $matches[4]) ? "ul" : "ol";
  858. $marker_any_re = ( $list_type == "ul" ? $marker_ul_re : $marker_ol_re );
  859. $list .= "\n";
  860. $result = $this->processListItems($list, $marker_any_re);
  861. $result = $this->hashBlock("<$list_type>\n" . $result . "</$list_type>");
  862. return "\n". $result ."\n\n";
  863. }
  864. var $list_level = 0;
  865. function processListItems($list_str, $marker_any_re) {
  866. #
  867. # Process the contents of a single ordered or unordered list, splitting it
  868. # into individual list items.
  869. #
  870. # The $this->list_level global keeps track of when we're inside a list.
  871. # Each time we enter a list, we increment it; when we leave a list,
  872. # we decrement. If it's zero, we're not in a list anymore.
  873. #
  874. # We do this because when we're not inside a list, we want to treat
  875. # something like this:
  876. #
  877. # I recommend upgrading to version
  878. # 8. Oops, now this line is treated
  879. # as a sub-list.
  880. #
  881. # As a single paragraph, despite the fact that the second line starts
  882. # with a digit-period-space sequence.
  883. #
  884. # Whereas when we're inside a list (or sub-list), that line will be
  885. # treated as the start of a sub-list. What a kludge, huh? This is
  886. # an aspect of Markdown's syntax that's hard to parse perfectly
  887. # without resorting to mind-reading. Perhaps the solution is to
  888. # change the syntax rules such that sub-lists must start with a
  889. # starting cardinal number; e.g. "1." or "a.".
  890. $this->list_level++;
  891. # trim trailing blank lines:
  892. $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str);
  893. $list_str = preg_replace_callback('{
  894. (\n)? # leading line = $1
  895. (^[ ]*) # leading whitespace = $2
  896. ('.$marker_any_re.' # list marker and space = $3
  897. (?:[ ]+|(?=\n)) # space only required if item is not empty
  898. )
  899. ((?s:.*?)) # list item text = $4
  900. (?:(\n+(?=\n))|\n) # tailing blank line = $5
  901. (?= \n* (\z | \2 ('.$marker_any_re.') (?:[ ]+|(?=\n))))
  902. }xm',
  903. array(&$this, '_processListItems_callback'), $list_str);
  904. $this->list_level--;
  905. return $list_str;
  906. }
  907. function _processListItems_callback($matches) {
  908. $item = $matches[4];
  909. $leading_line =& $matches[1];
  910. $leading_space =& $matches[2];
  911. $marker_space = $matches[3];
  912. $tailing_blank_line =& $matches[5];
  913. if ($leading_line || $tailing_blank_line ||
  914. preg_match('/\n{2,}/', $item))
  915. {
  916. # Replace marker with the appropriate whitespace indentation
  917. $item = $leading_space . str_repeat(' ', strlen($marker_space)) . $item;
  918. $item = $this->runBlockGamut($this->outdent($item)."\n");
  919. }
  920. else {
  921. # Recursion for sub-lists:
  922. $item = $this->doLists($this->outdent($item));
  923. $item = preg_replace('/\n+$/', '', $item);
  924. $item = $this->runSpanGamut($item);
  925. }
  926. return "<li>" . $item . "</li>\n";
  927. }
  928. function doCodeBlocks($text) {
  929. #
  930. # Process Markdown `<pre><code>` blocks.
  931. #
  932. $text = preg_replace_callback('{
  933. (?:\n\n|\A\n?)
  934. ( # $1 = the code block -- one or more lines, starting with a space/tab
  935. (?>
  936. [ ]{'.$this->tab_width.'} # Lines must start with a tab or a tab-width of spaces
  937. .*\n+
  938. )+
  939. )
  940. ((?=^[ ]{0,'.$this->tab_width.'}\S)|\Z) # Lookahead for non-space at line-start, or end of doc
  941. }xm',
  942. array(&$this, '_doCodeBlocks_callback'), $text);
  943. return $text;
  944. }
  945. function _doCodeBlocks_callback($matches) {
  946. $codeblock = $matches[1];
  947. $codeblock = $this->outdent($codeblock);
  948. $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES);
  949. # trim leading newlines and trailing newlines
  950. $codeblock = preg_replace('/\A\n+|\n+\z/', '', $codeblock);
  951. $codeblock = "<pre class=\"prettyprint linenums\">$codeblock\n</pre>";
  952. return "\n\n".$this->hashBlock($codeblock)."\n\n";
  953. }
  954. function makeCodeSpan($code) {
  955. #
  956. # Create a code span markup for $code. Called from handleSpanToken.
  957. #
  958. $code = htmlspecialchars(trim($code), ENT_NOQUOTES);
  959. return $this->hashPart("<code>$code</code>");
  960. }
  961. var $em_relist = array(
  962. '' => '(?:(?<!\*)\*(?!\*)|(?<!_)_(?!_))(?=\S|$)(?![\.,:;]\s)',
  963. '*' => '(?<=\S|^)(?<!\*)\*(?!\*)',
  964. '_' => '(?<=\S|^)(?<!_)_(?!_)',
  965. );
  966. var $strong_relist = array(
  967. '' => '(?:(?<!\*)\*\*(?!\*)|(?<!_)__(?!_))(?=\S|$)(?![\.,:;]\s)',
  968. '**' => '(?<=\S|^)(?<!\*)\*\*(?!\*)',
  969. '__' => '(?<=\S|^)(?<!_)__(?!_)',
  970. );
  971. var $em_strong_relist = array(
  972. '' => '(?:(?<!\*)\*\*\*(?!\*)|(?<!_)___(?!_))(?=\S|$)(?![\.,:;]\s)',
  973. '***' => '(?<=\S|^)(?<!\*)\*\*\*(?!\*)',
  974. '___' => '(?<=\S|^)(?<!_)___(?!_)',
  975. );
  976. var $em_strong_prepared_relist;
  977. function prepareItalicsAndBold() {
  978. #
  979. # Prepare regular expressions for searching emphasis tokens in any
  980. # context.
  981. #
  982. foreach ($this->em_relist as $em => $em_re) {
  983. foreach ($this->strong_relist as $strong => $strong_re) {
  984. # Construct list of allowed token expressions.
  985. $token_relist = array();
  986. if (isset($this->em_strong_relist["$em$strong"])) {
  987. $token_relist[] = $this->em_strong_relist["$em$strong"];
  988. }
  989. $token_relist[] = $em_re;
  990. $token_relist[] = $strong_re;
  991. # Construct master expression from list.
  992. $token_re = '{('. implode('|', $token_relist) .')}';
  993. $this->em_strong_prepared_relist["$em$strong"] = $token_re;
  994. }
  995. }
  996. }
  997. function doItalicsAndBold($text) {
  998. $token_stack = array('');
  999. $text_stack = array('');
  1000. $em = '';
  1001. $strong = '';
  1002. $tree_char_em = false;
  1003. while (1) {
  1004. #
  1005. # Get prepared regular expression for seraching emphasis tokens
  1006. # in current context.
  1007. #
  1008. $token_re = $this->em_strong_prepared_relist["$em$strong"];
  1009. #
  1010. # Each loop iteration search for the next emphasis token.
  1011. # Each token is then passed to handleSpanToken.
  1012. #
  1013. $parts = preg_split($token_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE);
  1014. $text_stack[0] .= $parts[0];
  1015. $token =& $parts[1];
  1016. $text =& $parts[2];
  1017. if (empty($token)) {
  1018. # Reached end of text span: empty stack without emitting.
  1019. # any more emphasis.
  1020. while ($token_stack[0]) {
  1021. $text_stack[1] .= array_shift($token_stack);
  1022. $text_stack[0] .= array_shift($text_stack);
  1023. }
  1024. break;
  1025. }
  1026. $token_len = strlen($token);
  1027. if ($tree_char_em) {
  1028. # Reached closing marker while inside a three-char emphasis.
  1029. if ($token_len == 3) {
  1030. # Three-char closing marker, close em and strong.
  1031. array_shift($token_stack);
  1032. $span = array_shift($text_stack);
  1033. $span = $this->runSpanGamut($span);
  1034. $span = "<strong><em>$span</em></strong>";
  1035. $text_stack[0] .= $this->hashPart($span);
  1036. $em = '';
  1037. $strong = '';
  1038. } else {
  1039. # Other closing marker: close one em or strong and
  1040. # change current token state to match the other
  1041. $token_stack[0] = str_repeat($token{0}, 3-$token_len);
  1042. $tag = $token_len == 2 ? "strong" : "em";
  1043. $span = $text_stack[0];
  1044. $span = $this->runSpanGamut($span);
  1045. $span = "<$tag>$span</$tag>";
  1046. $text_stack[0] = $this->hashPart($span);
  1047. $$tag = ''; # $$tag stands for $em or $strong
  1048. }
  1049. $tree_char_em = false;
  1050. } else if ($token_len == 3) {
  1051. if ($em) {
  1052. # Reached closing marker for both em and strong.
  1053. # Closing strong marker:
  1054. for ($i = 0; $i < 2; ++$i) {
  1055. $shifted_token = array_shift($token_stack);
  1056. $tag = strlen($shifted_token) == 2 ? "strong" : "em";
  1057. $span = array_shift($text_stack);
  1058. $span = $this->runSpanGamut($span);
  1059. $span = "<$tag>$span</$tag>";
  1060. $text_stack[0] .= $this->hashPart($span);
  1061. $$tag = ''; # $$tag stands for $em or $strong
  1062. }
  1063. } else {
  1064. # Reached opening three-char emphasis marker. Push on token
  1065. # stack; will be handled by the special condition above.
  1066. $em = $token{0};
  1067. $strong = "$em$em";
  1068. array_unshift($token_stack, $token);
  1069. array_unshift($text_stack, '');
  1070. $tree_char_em = true;
  1071. }
  1072. } else if ($token_len == 2) {
  1073. if ($strong) {
  1074. # Unwind any dangling emphasis marker:
  1075. if (strlen($token_stack[0]) == 1) {
  1076. $text_stack[1] .= array_shift($token_stack);
  1077. $text_stack[0] .= array_shift($text_stack);
  1078. }
  1079. # Closing strong marker:
  1080. array_shift($token_stack);
  1081. $span = array_shift($text_stack);
  1082. $span = $this->runSpanGamut($span);
  1083. $span = "<strong>$span</strong>";
  1084. $text_stack[0] .= $this->hashPart($span);
  1085. $strong = '';
  1086. } else {
  1087. array_unshift($token_stack, $token);
  1088. array_unshift($text_stack, '');
  1089. $strong = $token;
  1090. }
  1091. } else {
  1092. # Here $token_len == 1
  1093. if ($em) {
  1094. if (strlen($token_stack[0]) == 1) {
  1095. # Closing emphasis marker:
  1096. array_shift($token_stack);
  1097. $span = array_shift($text_stack);
  1098. $span = $this->runSpanGamut($span);
  1099. $span = "<em>$span</em>";
  1100. $text_stack[0] .= $this->hashPart($span);
  1101. $em = '';
  1102. } else {
  1103. $text_stack[0] .= $token;
  1104. }
  1105. } else {
  1106. array_unshift($token_stack, $token);
  1107. array_unshift($text_stack, '');
  1108. $em = $token;
  1109. }
  1110. }
  1111. }
  1112. return $text_stack[0];
  1113. }
  1114. function doBlockQuotes($text) {
  1115. $text = preg_replace_callback('/
  1116. ( # Wrap whole match in $1
  1117. (?>
  1118. ^[ ]*>[ ]? # ">" at the start of a line
  1119. .+\n # rest of the first line
  1120. (.+\n)* # subsequent consecutive lines
  1121. \n* # blanks
  1122. )+
  1123. )
  1124. /xm',
  1125. array(&$this, '_doBlockQuotes_callback'), $text);
  1126. return $text;
  1127. }
  1128. function _doBlockQuotes_callback($matches) {
  1129. $bq = $matches[1];
  1130. # trim one level of quoting - trim whitespace-only lines
  1131. $bq = preg_replace('/^[ ]*>[ ]?|^[ ]+$/m', '', $bq);
  1132. $bq = $this->runBlockGamut($bq); # recurse
  1133. $bq = preg_replace('/^/m', " ", $bq);
  1134. # These leading spaces cause problem with <pre> content,
  1135. # so we need to fix that:
  1136. $bq = preg_replace_callback('{(\s*<pre>.+?</pre>)}sx',
  1137. array(&$this, '_doBlockQuotes_callback2'), $bq);
  1138. return "\n". $this->hashBlock("<blockquote>\n$bq\n</blockquote>")."\n\n";
  1139. }
  1140. function _doBlockQuotes_callback2($matches) {
  1141. $pre = $matches[1];
  1142. $pre = preg_replace('/^ /m', '', $pre);
  1143. return $pre;
  1144. }
  1145. function formParagraphs($text) {
  1146. #
  1147. # Params:
  1148. # $text - string to process with html <p> tags
  1149. #
  1150. # Strip leading and trailing lines:
  1151. $text = preg_replace('/\A\n+|\n+\z/', '', $text);
  1152. $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY);
  1153. #
  1154. # Wrap <p> tags and unhashify HTML blocks
  1155. #
  1156. foreach ($grafs as $key => $value) {
  1157. if (!preg_match('/^B\x1A[0-9]+B$/', $value)) {
  1158. # Is a paragraph.
  1159. $value = $this->runSpanGamut($value);
  1160. $value = preg_replace('/^([ ]*)/', "<p>", $value);
  1161. $value .= "</p>";
  1162. $grafs[$key] = $this->unhash($value);
  1163. }
  1164. else {
  1165. # Is a block.
  1166. # Modify elements of @grafs in-place...
  1167. $graf = $value;
  1168. $block = $this->html_hashes[$graf];
  1169. $graf = $block;
  1170. // if (preg_match('{
  1171. // \A
  1172. // ( # $1 = <div> tag
  1173. // <div \s+
  1174. // [^>]*
  1175. // \b
  1176. // markdown\s*=\s* ([\'"]) # $2 = attr quote char
  1177. // 1
  1178. // \2
  1179. // [^>]*
  1180. // >
  1181. // )
  1182. // ( # $3 = contents
  1183. // .*
  1184. // )
  1185. // (</div>) # $4 = closing tag
  1186. // \z
  1187. // }xs', $block, $matches))
  1188. // {
  1189. // list(, $div_open, , $div_content, $div_close) = $matches;
  1190. //
  1191. // # We can't call Markdown(), because that resets the hash;
  1192. // # that initialization code should be pulled into its own sub, though.
  1193. // $div_content = $this->hashHTMLBlocks($div_content);
  1194. //
  1195. // # Run document gamut methods on the content.
  1196. // foreach ($this->document_gamut as $method => $priority) {
  1197. // $div_content = $this->$method($div_content);
  1198. // }
  1199. //
  1200. // $div_open = preg_replace(
  1201. // '{\smarkdown\s*=\s*([\'"]).+?\1}', '', $div_open);
  1202. //
  1203. // $graf = $div_open . "\n" . $div_content . "\n" . $div_close;
  1204. // }
  1205. $grafs[$key] = $graf;
  1206. }
  1207. }
  1208. return implode("\n\n", $grafs);
  1209. }
  1210. function encodeAttribute($text) {
  1211. #
  1212. # Encode text for a double-quoted HTML attribute. This function
  1213. # is *not* suitable for attributes enclosed in single quotes.
  1214. #
  1215. $text = $this->encodeAmpsAndAngles($text);
  1216. $text = str_replace('"', '&quot;', $text);
  1217. return $text;
  1218. }
  1219. function encodeAmpsAndAngles($text) {
  1220. #
  1221. # Smart processing for ampersands and angle brackets that need to
  1222. # be encoded. Valid character entities are left alone unless the
  1223. # no-entities mode is set.
  1224. #
  1225. if ($this->no_entities) {
  1226. $text = str_replace('&', '&amp;', $text);
  1227. } else {
  1228. # Ampersand-encoding based entirely on Nat Irons's Amputator
  1229. # MT plugin: <http://bumppo.net/projects/amputator/>
  1230. $text = preg_replace('/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/',
  1231. '&amp;', $text);;
  1232. }
  1233. # Encode remaining <'s
  1234. $text = str_replace('<', '&lt;', $text);
  1235. return $text;
  1236. }
  1237. function doAutoLinks($text) {
  1238. $text = preg_replace_callback('{<((https?|ftp|dict):[^\'">\s]+)>}i',
  1239. array(&$this, '_doAutoLinks_url_callback'), $text);
  1240. # Email addresses: <address@domain.foo>
  1241. $text = preg_replace_callback('{
  1242. <
  1243. (?:mailto:)?
  1244. (
  1245. (?:
  1246. [-!#$%&\'*+/=?^_`.{|}~\w\x80-\xFF]+
  1247. |
  1248. ".*?"
  1249. )
  1250. \@
  1251. (?:
  1252. [-a-z0-9\x80-\xFF]+(\.[-a-z0-9\x80-\xFF]+)*\.[a-z]+
  1253. |
  1254. \[[\d.a-fA-F:]+\] # IPv4 & IPv6
  1255. )
  1256. )
  1257. >
  1258. }xi',
  1259. array(&$this, '_doAutoLinks_email_callback'), $text);
  1260. return $text;
  1261. }
  1262. function _doAutoLinks_url_callback($matches) {
  1263. $url = $this->encodeAttribute($matches[1]);
  1264. $link = "<a href=\"$url\">$url</a>";
  1265. return $this->hashPart($link);
  1266. }
  1267. function _doAutoLinks_email_callback($matches) {
  1268. $address = $matches[1];
  1269. $link = $this->encodeEmailAddress($address);
  1270. return $this->hashPart($link);
  1271. }
  1272. function encodeEmailAddress($addr) {
  1273. #
  1274. # Input: an email address, e.g. "foo@example.com"
  1275. #
  1276. # Output: the email address as a mailto link, with each character
  1277. # of the address encoded as either a decimal or hex entity, in
  1278. # the hopes of foiling most address harvesting spam bots. E.g.:
  1279. #
  1280. # <p><a href="&#109;&#x61;&#105;&#x6c;&#116;&#x6f;&#58;&#x66;o&#111;
  1281. # &#x40;&#101;&#x78;&#97;&#x6d;&#112;&#x6c;&#101;&#46;&#x63;&#111;
  1282. # &#x6d;">&#x66;o&#111;&#x40;&#101;&#x78;&#97;&#x6d;&#112;&#x6c;
  1283. # &#101;&#46;&#x63;&#111;&#x6d;</a></p>
  1284. #
  1285. # Based by a filter by Matthew Wickline, posted to BBEdit-Talk.
  1286. # With some optimizations by Milian Wolff.
  1287. #
  1288. $addr = "mailto:" . $addr;
  1289. $chars = preg_split('/(?<!^)(?!$)/', $addr);
  1290. $seed = (int)abs(crc32($addr) / strlen($addr)); # Deterministic seed.
  1291. foreach ($chars as $key => $char) {
  1292. $ord = ord($char);
  1293. # Ignore non-ascii chars.
  1294. if ($ord < 128) {
  1295. $r = ($seed * (1 + $key)) % 100; # Pseudo-random function.
  1296. # roughly 10% raw, 45% hex, 45% dec
  1297. # '@' *must* be encoded. I insist.
  1298. if ($r > 90 && $char != '@') /* do nothing */;
  1299. else if ($r < 45) $chars[$key] = '&#x'.dechex($ord).';';
  1300. else $chars[$key] = '&#'.$ord.';';
  1301. }
  1302. }
  1303. $addr = implode('', $chars);
  1304. $text = implode('', array_slice($chars, 7)); # text without `mailto:`
  1305. $addr = "<a href=\"$addr\">$text</a>";
  1306. return $addr;
  1307. }
  1308. function parseSpan($str) {
  1309. #
  1310. # Take the string $str and parse it into tokens, hashing embeded HTML,
  1311. # escaped characters and handling code spans.
  1312. #
  1313. $output = '';
  1314. $span_re = '{
  1315. (
  1316. \\\\'.$this->escape_chars_re.'
  1317. |
  1318. (?<![`\\\\])
  1319. `+ # code span marker
  1320. '.( $this->no_markup ? '' : '
  1321. |
  1322. <!-- .*? --> # comment
  1323. |
  1324. <\?.*?\?> | <%.*?%> # processing instruction
  1325. |
  1326. <[/!$]?[-a-zA-Z0-9:_]+ # regular tags
  1327. (?>
  1328. \s
  1329. (?>[^"\'>]+|"[^"]*"|\'[^\']*\')*
  1330. )?
  1331. >
  1332. ').'
  1333. )
  1334. }xs';
  1335. while (1) {
  1336. #
  1337. # Each loop iteration seach for either the next tag, the next
  1338. # openning code span marker, or the next escaped character.
  1339. # Each token is then passed to handleSpanToken.
  1340. #
  1341. $parts = preg_split($span_re, $str, 2, PREG_SPLIT_DELIM_CAPTURE);
  1342. # Create token from text preceding tag.
  1343. if ($parts[0] != "") {
  1344. $output .= $parts[0];
  1345. }
  1346. # Check if we reach the end.
  1347. if (isset($parts[1])) {
  1348. $output .= $this->handleSpanToken($parts[1], $parts[2]);
  1349. $str = $parts[2];
  1350. }
  1351. else {
  1352. break;
  1353. }
  1354. }
  1355. return $output;
  1356. }
  1357. function handleSpanToken($token, &$str) {
  1358. #
  1359. # Handle $token provided by parseSpan by determining its nature and
  1360. # returning the corresponding value that should replace it.
  1361. #
  1362. switch ($token{0}) {
  1363. case "\\":
  1364. return $this->hashPart("&#". ord($token{1}). ";");
  1365. case "`":
  1366. # Search for end marker in remaining text.
  1367. if (preg_match('/^(.*?[^`])'.preg_quote($token).'(?!`)(.*)$/sm',
  1368. $str, $matches))
  1369. {
  1370. $str = $matches[2];
  1371. $codespan = $this->makeCodeSpan($matches[1]);
  1372. return $this->hashPart($codespan);
  1373. }
  1374. return $token; // return as text since no ending marker found.
  1375. default:
  1376. return $this->hashPart($token);
  1377. }
  1378. }
  1379. function outdent($text) {
  1380. #
  1381. # Remove one level of line-leading tabs or spaces
  1382. #
  1383. return preg_replace('/^(\t|[ ]{1,'.$this->tab_width.'})/m', '', $text);
  1384. }
  1385. # String length function for detab. `_initDetab` will create a function to
  1386. # hanlde UTF-8 if the default function does not exist.
  1387. var $utf8_strlen = 'mb_strlen';
  1388. function detab($text) {
  1389. #
  1390. # Replace tabs with the appropriate amount of space.
  1391. #
  1392. # For each line we separate the line in blocks delemited by
  1393. # tab characters. Then we reconstruct every line by adding the
  1394. # appropriate number of space between each blocks.
  1395. $text = preg_replace_callback('/^.*\t.*$/m',
  1396. array(&$this, '_detab_callback'), $text);
  1397. return $text;
  1398. }
  1399. function _detab_callback($matches) {
  1400. $line = $matches[0];
  1401. $strlen = $this->utf8_strlen; # strlen function for UTF-8.
  1402. # Split in blocks.
  1403. $blocks = explode("\t", $line);
  1404. # Add each blocks to the line.
  1405. $line = $blocks[0];
  1406. unset($blocks[0]); # Do not add first block twice.
  1407. foreach ($blocks as $block) {
  1408. # Calculate amount of space, insert spaces, insert block.
  1409. $amount = $this->tab_width -
  1410. $strlen($line, 'UTF-8') % $this->tab_width;
  1411. $line .= str_repeat(" ", $amount) . $block;
  1412. }
  1413. return $line;
  1414. }
  1415. function _initDetab() {
  1416. #
  1417. # Check for the availability of the function in the `utf8_strlen` property
  1418. # (initially `mb_strlen`). If the function is not available, create a
  1419. # function that will loosely count the number of UTF-8 characters with a
  1420. # regular expression.
  1421. #
  1422. if (function_exists($this->utf8_strlen)) return;
  1423. $this->utf8_strlen = create_function('$text', 'return preg_match_all(
  1424. "/[\\\\x00-\\\\xBF]|[\\\\xC0-\\\\xFF][\\\\x80-\\\\xBF]*/",
  1425. $text, $m);');
  1426. }
  1427. function unhash($text) {
  1428. #
  1429. # Swap back in all the tags hashed by _HashHTMLBlocks.
  1430. #
  1431. return preg_replace_callback('/(.)\x1A[0-9]+\1/',
  1432. array(&$this, '_unhash_callback'), $text);
  1433. }
  1434. function _unhash_callback($matches) {
  1435. return $this->html_hashes[$matches[0]];
  1436. }
  1437. }
  1438. #
  1439. # Markdown Extra Parser Class
  1440. #
  1441. class MarkdownExtra_Parser extends Markdown_Parser {
  1442. # Prefix for footnote ids.
  1443. var $fn_id_prefix = "";
  1444. # Optional title attribute for footnote links and backlinks.
  1445. var $fn_link_title = MARKDOWN_FN_LINK_TITLE;
  1446. var $fn_backlink_title = MARKDOWN_FN_BACKLINK_TITLE;
  1447. # Optional class attribute for footnote links and backlinks.
  1448. var $fn_link_class = MARKDOWN_FN_LINK_CLASS;
  1449. var $fn_backlink_class = MARKDOWN_FN_BACKLINK_CLASS;
  1450. # Predefined abbreviations.
  1451. var $predef_abbr = array();
  1452. function MarkdownExtra_Parser() {
  1453. #
  1454. # Constructor function. Initialize the parser object.
  1455. #
  1456. # Add extra escapable characters before parent constructor
  1457. # initialize the table.
  1458. $this->escape_chars .= ':|';
  1459. # Insert extra document, block, and span transformations.
  1460. # Parent constructor will do the sorting.
  1461. $this->document_gamut += array(
  1462. "doFencedCodeBlocks" => 5,
  1463. "stripFootnotes" => 15,
  1464. "stripAbbreviations" => 25,
  1465. "appendFootnotes" => 50,
  1466. );
  1467. $this->block_gamut += array(
  1468. "doFencedCodeBlocks" => 5,
  1469. "doTables" => 15,
  1470. "doDefLists" => 45,
  1471. );
  1472. $this->span_gamut += array(
  1473. "doFootnotes" => 5,
  1474. "doAbbreviations" => 70,
  1475. );
  1476. parent::Markdown_Parser();
  1477. }
  1478. # Extra variables used during extra transformations.
  1479. var $footnotes = array();
  1480. var $footnotes_ordered = array();
  1481. var $abbr_desciptions = array();
  1482. var $abbr_word_re = '';
  1483. # Give the current footnote number.
  1484. var $footnote_counter = 1;
  1485. function setup() {
  1486. #
  1487. # Setting up Extra-specific variables.
  1488. #
  1489. parent::setup();
  1490. $this->footnotes = array();
  1491. $this->footnotes_ordered = array();
  1492. $this->abbr_desciptions = array();
  1493. $this->abbr_word_re = '';
  1494. $this->footnote_counter = 1;
  1495. foreach ($this->predef_abbr as $abbr_word => $abbr_desc) {
  1496. if ($this->abbr_word_re)
  1497. $this->abbr_word_re .= '|';
  1498. $this->abbr_word_re .= preg_quote($abbr_word);
  1499. $this->abbr_desciptions[$abbr_word] = trim($abbr_desc);
  1500. }
  1501. }
  1502. function teardown() {
  1503. #
  1504. # Clearing Extra-specific variables.
  1505. #
  1506. $this->footnotes = array();
  1507. $this->footnotes_ordered = array();
  1508. $this->abbr_desciptions = array();
  1509. $this->abbr_word_re = '';
  1510. parent::teardown();
  1511. }
  1512. ### HTML Block Parser ###
  1513. # Tags that are always treated as block tags:
  1514. var $block_tags_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|form|fieldset|iframe|hr|legend';
  1515. # Tags treated as block tags only if the opening tag is alone on it's line:
  1516. var $context_block_tags_re = 'script|noscript|math|ins|del';
  1517. # Tags where markdown="1" default to span mode:
  1518. var $contain_span_tags_re = 'p|h[1-6]|li|dd|dt|td|th|legend|address';
  1519. # Tags which must not have their contents modified, no matter where
  1520. # they appear:
  1521. var $clean_tags_re = 'script|math';
  1522. # Tags that do not need to be closed.
  1523. var $auto_close_tags_re = 'hr|img';
  1524. function hashHTMLBlocks($text) {
  1525. #
  1526. # Hashify HTML Blocks and "clean tags".
  1527. #
  1528. # We only want to do this for block-level HTML tags, such as headers,
  1529. # lists, and tables. That's because we still want