PageRenderTime 54ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Milk/Utils/Markup.php

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