PageRenderTime 59ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/modules/userguide/vendor/markdown/markdown.php

https://bitbucket.org/seyar/ari100krat.local
PHP | 2909 lines | 1846 code | 324 blank | 739 comment | 179 complexity | 8320ec55eab3a91d90b014b16f99a9b2 MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-2.1

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

Large files files are truncated, but you can click here to view the full file