PageRenderTime 66ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 1ms

/system/vendor/Markdown.php

https://github.com/jarinudom/three20.info
PHP | 2873 lines | 1854 code | 305 blank | 714 comment | 167 complexity | eec98f2f737ead4288c364c7e5b086cb MD5 | raw file

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

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

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