PageRenderTime 60ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/kirby/parsers/markdown.php

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