PageRenderTime 77ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 0ms

/plugins/Markdown.php

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