MarkdownExtra.php 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924
  1. <?php
  2. /**
  3. * Markdown Extra - A text-to-HTML conversion tool for web writers
  4. *
  5. * @package php-markdown
  6. * @author Michel Fortin <michel.fortin@michelf.com>
  7. * @copyright 2004-2021 Michel Fortin <https://michelf.com/projects/php-markdown/>
  8. * @copyright (Original Markdown) 2004-2006 John Gruber <https://daringfireball.net/projects/markdown/>
  9. */
  10. namespace Michelf;
  11. /**
  12. * Markdown Extra Parser Class
  13. */
  14. class MarkdownExtra extends \Michelf\Markdown {
  15. /**
  16. * Configuration variables
  17. */
  18. /**
  19. * Prefix for footnote ids.
  20. * @var string
  21. */
  22. public $fn_id_prefix = "";
  23. /**
  24. * Optional title attribute for footnote links.
  25. * @var string
  26. */
  27. public $fn_link_title = "";
  28. /**
  29. * Optional class attribute for footnote links and backlinks.
  30. * @var string
  31. */
  32. public $fn_link_class = "footnote-ref";
  33. public $fn_backlink_class = "footnote-backref";
  34. /**
  35. * Content to be displayed within footnote backlinks. The default is '↩';
  36. * the U+FE0E on the end is a Unicode variant selector used to prevent iOS
  37. * from displaying the arrow character as an emoji.
  38. * Optionally use '^^' and '%%' to refer to the footnote number and
  39. * reference number respectively. {@see parseFootnotePlaceholders()}
  40. * @var string
  41. */
  42. public $fn_backlink_html = '&#8617;&#xFE0E;';
  43. /**
  44. * Optional title and aria-label attributes for footnote backlinks for
  45. * added accessibility (to ensure backlink uniqueness).
  46. * Use '^^' and '%%' to refer to the footnote number and reference number
  47. * respectively. {@see parseFootnotePlaceholders()}
  48. * @var string
  49. */
  50. public $fn_backlink_title = "";
  51. public $fn_backlink_label = "";
  52. /**
  53. * Class name for table cell alignment (%% replaced left/center/right)
  54. * For instance: 'go-%%' becomes 'go-left' or 'go-right' or 'go-center'
  55. * If empty, the align attribute is used instead of a class name.
  56. * @var string
  57. */
  58. public $table_align_class_tmpl = '';
  59. /**
  60. * Optional class prefix for fenced code block.
  61. * @var string
  62. */
  63. public $code_class_prefix = "";
  64. /**
  65. * Class attribute for code blocks goes on the `code` tag;
  66. * setting this to true will put attributes on the `pre` tag instead.
  67. * @var boolean
  68. */
  69. public $code_attr_on_pre = false;
  70. /**
  71. * Predefined abbreviations.
  72. * @var array
  73. */
  74. public $predef_abbr = array();
  75. /**
  76. * Only convert atx-style headers if there's a space between the header and #
  77. * @var boolean
  78. */
  79. public $hashtag_protection = false;
  80. /**
  81. * Determines whether footnotes should be appended to the end of the document.
  82. * If true, footnote html can be retrieved from $this->footnotes_assembled.
  83. * @var boolean
  84. */
  85. public $omit_footnotes = false;
  86. /**
  87. * After parsing, the HTML for the list of footnotes appears here.
  88. * This is available only if $omit_footnotes == true.
  89. *
  90. * Note: when placing the content of `footnotes_assembled` on the page,
  91. * consider adding the attribute `role="doc-endnotes"` to the `div` or
  92. * `section` that will enclose the list of footnotes so they are
  93. * reachable to accessibility tools the same way they would be with the
  94. * default HTML output.
  95. * @var null|string
  96. */
  97. public $footnotes_assembled = null;
  98. /**
  99. * Parser implementation
  100. */
  101. /**
  102. * Constructor function. Initialize the parser object.
  103. * @return void
  104. */
  105. public function __construct() {
  106. // Add extra escapable characters before parent constructor
  107. // initialize the table.
  108. $this->escape_chars .= ':|';
  109. // Insert extra document, block, and span transformations.
  110. // Parent constructor will do the sorting.
  111. $this->document_gamut += array(
  112. "doFencedCodeBlocks" => 5,
  113. "stripFootnotes" => 15,
  114. "stripAbbreviations" => 25,
  115. "appendFootnotes" => 50,
  116. );
  117. $this->block_gamut += array(
  118. "doFencedCodeBlocks" => 5,
  119. "doTables" => 15,
  120. "doDefLists" => 45,
  121. );
  122. $this->span_gamut += array(
  123. "doFootnotes" => 5,
  124. "doStrikethrough" => 55,
  125. "doAbbreviations" => 70,
  126. );
  127. $this->enhanced_ordered_list = true;
  128. parent::__construct();
  129. }
  130. /**
  131. * Extra variables used during extra transformations.
  132. * @var array
  133. */
  134. protected $footnotes = array();
  135. protected $footnotes_ordered = array();
  136. protected $footnotes_ref_count = array();
  137. protected $footnotes_numbers = array();
  138. protected $abbr_desciptions = array();
  139. /** @var string */
  140. protected $abbr_word_re = '';
  141. /**
  142. * Give the current footnote number.
  143. * @var integer
  144. */
  145. protected $footnote_counter = 1;
  146. /**
  147. * Ref attribute for links
  148. * @var array
  149. */
  150. protected $ref_attr = array();
  151. /**
  152. * Setting up Extra-specific variables.
  153. */
  154. protected function setup() {
  155. parent::setup();
  156. $this->footnotes = array();
  157. $this->footnotes_ordered = array();
  158. $this->footnotes_ref_count = array();
  159. $this->footnotes_numbers = array();
  160. $this->abbr_desciptions = array();
  161. $this->abbr_word_re = '';
  162. $this->footnote_counter = 1;
  163. $this->footnotes_assembled = null;
  164. foreach ($this->predef_abbr as $abbr_word => $abbr_desc) {
  165. if ($this->abbr_word_re)
  166. $this->abbr_word_re .= '|';
  167. $this->abbr_word_re .= preg_quote($abbr_word);
  168. $this->abbr_desciptions[$abbr_word] = trim($abbr_desc);
  169. }
  170. }
  171. /**
  172. * Clearing Extra-specific variables.
  173. */
  174. protected function teardown() {
  175. $this->footnotes = array();
  176. $this->footnotes_ordered = array();
  177. $this->footnotes_ref_count = array();
  178. $this->footnotes_numbers = array();
  179. $this->abbr_desciptions = array();
  180. $this->abbr_word_re = '';
  181. if ( ! $this->omit_footnotes )
  182. $this->footnotes_assembled = null;
  183. parent::teardown();
  184. }
  185. /**
  186. * Extra attribute parser
  187. */
  188. /**
  189. * Expression to use to catch attributes (includes the braces)
  190. * @var string
  191. */
  192. protected $id_class_attr_catch_re = '\{((?>[ ]*[#.a-z][-_:a-zA-Z0-9=]+){1,})[ ]*\}';
  193. /**
  194. * Expression to use when parsing in a context when no capture is desired
  195. * @var string
  196. */
  197. protected $id_class_attr_nocatch_re = '\{(?>[ ]*[#.a-z][-_:a-zA-Z0-9=]+){1,}[ ]*\}';
  198. /**
  199. * Parse attributes caught by the $this->id_class_attr_catch_re expression
  200. * and return the HTML-formatted list of attributes.
  201. *
  202. * Currently supported attributes are .class and #id.
  203. *
  204. * In addition, this method also supports supplying a default Id value,
  205. * which will be used to populate the id attribute in case it was not
  206. * overridden.
  207. * @param string $tag_name
  208. * @param string $attr
  209. * @param mixed $defaultIdValue
  210. * @param array $classes
  211. * @return string
  212. */
  213. protected function doExtraAttributes($tag_name, $attr, $defaultIdValue = null, $classes = array()) {
  214. if (empty($attr) && !$defaultIdValue && empty($classes)) {
  215. return "";
  216. }
  217. // Split on components
  218. preg_match_all('/[#.a-z][-_:a-zA-Z0-9=]+/', $attr, $matches);
  219. $elements = $matches[0];
  220. // Handle classes and IDs (only first ID taken into account)
  221. $attributes = array();
  222. $id = false;
  223. foreach ($elements as $element) {
  224. if ($element[0] === '.') {
  225. $classes[] = substr($element, 1);
  226. } else if ($element[0] === '#') {
  227. if ($id === false) $id = substr($element, 1);
  228. } else if (strpos($element, '=') > 0) {
  229. $parts = explode('=', $element, 2);
  230. $attributes[] = $parts[0] . '="' . $parts[1] . '"';
  231. }
  232. }
  233. if ($id === false || $id === '') {
  234. $id = $defaultIdValue;
  235. }
  236. // Compose attributes as string
  237. $attr_str = "";
  238. if (!empty($id)) {
  239. $attr_str .= ' id="'.$this->encodeAttribute($id) .'"';
  240. }
  241. if (!empty($classes)) {
  242. $attr_str .= ' class="'. implode(" ", $classes) . '"';
  243. }
  244. if (!$this->no_markup && !empty($attributes)) {
  245. $attr_str .= ' '.implode(" ", $attributes);
  246. }
  247. return $attr_str;
  248. }
  249. /**
  250. * Strips link definitions from text, stores the URLs and titles in
  251. * hash references.
  252. * @param string $text
  253. * @return string
  254. */
  255. protected function stripLinkDefinitions($text) {
  256. $less_than_tab = $this->tab_width - 1;
  257. // Link defs are in the form: ^[id]: url "optional title"
  258. $text = preg_replace_callback('{
  259. ^[ ]{0,'.$less_than_tab.'}\[(.+)\][ ]?: # id = $1
  260. [ ]*
  261. \n? # maybe *one* newline
  262. [ ]*
  263. (?:
  264. <(.+?)> # url = $2
  265. |
  266. (\S+?) # url = $3
  267. )
  268. [ ]*
  269. \n? # maybe one newline
  270. [ ]*
  271. (?:
  272. (?<=\s) # lookbehind for whitespace
  273. ["(]
  274. (.*?) # title = $4
  275. [")]
  276. [ ]*
  277. )? # title is optional
  278. (?:[ ]* '.$this->id_class_attr_catch_re.' )? # $5 = extra id & class attr
  279. (?:\n+|\Z)
  280. }xm',
  281. array($this, '_stripLinkDefinitions_callback'),
  282. $text);
  283. return $text;
  284. }
  285. /**
  286. * Strip link definition callback
  287. * @param array $matches
  288. * @return string
  289. */
  290. protected function _stripLinkDefinitions_callback($matches) {
  291. $link_id = strtolower($matches[1]);
  292. $url = $matches[2] == '' ? $matches[3] : $matches[2];
  293. $this->urls[$link_id] = $url;
  294. $this->titles[$link_id] =& $matches[4];
  295. $this->ref_attr[$link_id] = $this->doExtraAttributes("", $dummy =& $matches[5]);
  296. return ''; // String that will replace the block
  297. }
  298. /**
  299. * HTML block parser
  300. */
  301. /**
  302. * Tags that are always treated as block tags
  303. * @var string
  304. */
  305. protected $block_tags_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|form|fieldset|iframe|hr|legend|article|section|nav|aside|hgroup|header|footer|figcaption|figure|details|summary';
  306. /**
  307. * Tags treated as block tags only if the opening tag is alone on its line
  308. * @var string
  309. */
  310. protected $context_block_tags_re = 'script|noscript|style|ins|del|iframe|object|source|track|param|math|svg|canvas|audio|video';
  311. /**
  312. * Tags where markdown="1" default to span mode:
  313. * @var string
  314. */
  315. protected $contain_span_tags_re = 'p|h[1-6]|li|dd|dt|td|th|legend|address';
  316. /**
  317. * Tags which must not have their contents modified, no matter where
  318. * they appear
  319. * @var string
  320. */
  321. protected $clean_tags_re = 'script|style|math|svg';
  322. /**
  323. * Tags that do not need to be closed.
  324. * @var string
  325. */
  326. protected $auto_close_tags_re = 'hr|img|param|source|track';
  327. /**
  328. * Hashify HTML Blocks and "clean tags".
  329. *
  330. * We only want to do this for block-level HTML tags, such as headers,
  331. * lists, and tables. That's because we still want to wrap <p>s around
  332. * "paragraphs" that are wrapped in non-block-level tags, such as anchors,
  333. * phrase emphasis, and spans. The list of tags we're looking for is
  334. * hard-coded.
  335. *
  336. * This works by calling _HashHTMLBlocks_InMarkdown, which then calls
  337. * _HashHTMLBlocks_InHTML when it encounter block tags. When the markdown="1"
  338. * attribute is found within a tag, _HashHTMLBlocks_InHTML calls back
  339. * _HashHTMLBlocks_InMarkdown to handle the Markdown syntax within the tag.
  340. * These two functions are calling each other. It's recursive!
  341. * @param string $text
  342. * @return string
  343. */
  344. protected function hashHTMLBlocks($text) {
  345. if ($this->no_markup) {
  346. return $text;
  347. }
  348. // Call the HTML-in-Markdown hasher.
  349. list($text, ) = $this->_hashHTMLBlocks_inMarkdown($text);
  350. return $text;
  351. }
  352. /**
  353. * Parse markdown text, calling _HashHTMLBlocks_InHTML for block tags.
  354. *
  355. * * $indent is the number of space to be ignored when checking for code
  356. * blocks. This is important because if we don't take the indent into
  357. * account, something like this (which looks right) won't work as expected:
  358. *
  359. * <div>
  360. * <div markdown="1">
  361. * Hello World. <-- Is this a Markdown code block or text?
  362. * </div> <-- Is this a Markdown code block or a real tag?
  363. * <div>
  364. *
  365. * If you don't like this, just don't indent the tag on which
  366. * you apply the markdown="1" attribute.
  367. *
  368. * * If $enclosing_tag_re is not empty, stops at the first unmatched closing
  369. * tag with that name. Nested tags supported.
  370. *
  371. * * If $span is true, text inside must treated as span. So any double
  372. * newline will be replaced by a single newline so that it does not create
  373. * paragraphs.
  374. *
  375. * Returns an array of that form: ( processed text , remaining text )
  376. *
  377. * @param string $text
  378. * @param integer $indent
  379. * @param string $enclosing_tag_re
  380. * @param boolean $span
  381. * @return array
  382. */
  383. protected function _hashHTMLBlocks_inMarkdown($text, $indent = 0,
  384. $enclosing_tag_re = '', $span = false)
  385. {
  386. if ($text === '') return array('', '');
  387. // Regex to check for the presense of newlines around a block tag.
  388. $newline_before_re = '/(?:^\n?|\n\n)*$/';
  389. $newline_after_re =
  390. '{
  391. ^ # Start of text following the tag.
  392. (?>[ ]*<!--.*?-->)? # Optional comment.
  393. [ ]*\n # Must be followed by newline.
  394. }xs';
  395. // Regex to match any tag.
  396. $block_tag_re =
  397. '{
  398. ( # $2: Capture whole tag.
  399. </? # Any opening or closing tag.
  400. (?> # Tag name.
  401. ' . $this->block_tags_re . ' |
  402. ' . $this->context_block_tags_re . ' |
  403. ' . $this->clean_tags_re . ' |
  404. (?!\s)'.$enclosing_tag_re . '
  405. )
  406. (?:
  407. (?=[\s"\'/a-zA-Z0-9]) # Allowed characters after tag name.
  408. (?>
  409. ".*?" | # Double quotes (can contain `>`)
  410. \'.*?\' | # Single quotes (can contain `>`)
  411. .+? # Anything but quotes and `>`.
  412. )*?
  413. )?
  414. > # End of tag.
  415. |
  416. <!-- .*? --> # HTML Comment
  417. |
  418. <\?.*?\?> | <%.*?%> # Processing instruction
  419. |
  420. <!\[CDATA\[.*?\]\]> # CData Block
  421. ' . ( !$span ? ' # If not in span.
  422. |
  423. # Indented code block
  424. (?: ^[ ]*\n | ^ | \n[ ]*\n )
  425. [ ]{' . ($indent + 4) . '}[^\n]* \n
  426. (?>
  427. (?: [ ]{' . ($indent + 4) . '}[^\n]* | [ ]* ) \n
  428. )*
  429. |
  430. # Fenced code block marker
  431. (?<= ^ | \n )
  432. [ ]{0,' . ($indent + 3) . '}(?:~{3,}|`{3,})
  433. [ ]*
  434. (?: \.?[-_:a-zA-Z0-9]+ )? # standalone class name
  435. [ ]*
  436. (?: ' . $this->id_class_attr_nocatch_re . ' )? # extra attributes
  437. [ ]*
  438. (?= \n )
  439. ' : '' ) . ' # End (if not is span).
  440. |
  441. # Code span marker
  442. # Note, this regex needs to go after backtick fenced
  443. # code blocks but it should also be kept outside of the
  444. # "if not in span" condition adding backticks to the parser
  445. `+
  446. )
  447. }xs';
  448. $depth = 0; // Current depth inside the tag tree.
  449. $parsed = ""; // Parsed text that will be returned.
  450. // Loop through every tag until we find the closing tag of the parent
  451. // or loop until reaching the end of text if no parent tag specified.
  452. do {
  453. // Split the text using the first $tag_match pattern found.
  454. // Text before pattern will be first in the array, text after
  455. // pattern will be at the end, and between will be any catches made
  456. // by the pattern.
  457. $parts = preg_split($block_tag_re, $text, 2,
  458. PREG_SPLIT_DELIM_CAPTURE);
  459. // If in Markdown span mode, add a empty-string span-level hash
  460. // after each newline to prevent triggering any block element.
  461. if ($span) {
  462. $void = $this->hashPart("", ':');
  463. $newline = "\n$void";
  464. $parts[0] = $void . str_replace("\n", $newline, $parts[0]) . $void;
  465. }
  466. $parsed .= $parts[0]; // Text before current tag.
  467. // If end of $text has been reached. Stop loop.
  468. if (count($parts) < 3) {
  469. $text = "";
  470. break;
  471. }
  472. $tag = $parts[1]; // Tag to handle.
  473. $text = $parts[2]; // Remaining text after current tag.
  474. // Check for: Fenced code block marker.
  475. // Note: need to recheck the whole tag to disambiguate backtick
  476. // fences from code spans
  477. if (preg_match('{^\n?([ ]{0,' . ($indent + 3) . '})(~{3,}|`{3,})[ ]*(?:\.?[-_:a-zA-Z0-9]+)?[ ]*(?:' . $this->id_class_attr_nocatch_re . ')?[ ]*\n?$}', $tag, $capture)) {
  478. // Fenced code block marker: find matching end marker.
  479. $fence_indent = strlen($capture[1]); // use captured indent in re
  480. $fence_re = $capture[2]; // use captured fence in re
  481. if (preg_match('{^(?>.*\n)*?[ ]{' . ($fence_indent) . '}' . $fence_re . '[ ]*(?:\n|$)}', $text,
  482. $matches))
  483. {
  484. // End marker found: pass text unchanged until marker.
  485. $parsed .= $tag . $matches[0];
  486. $text = substr($text, strlen($matches[0]));
  487. }
  488. else {
  489. // No end marker: just skip it.
  490. $parsed .= $tag;
  491. }
  492. }
  493. // Check for: Indented code block.
  494. else if ($tag[0] === "\n" || $tag[0] === " ") {
  495. // Indented code block: pass it unchanged, will be handled
  496. // later.
  497. $parsed .= $tag;
  498. }
  499. // Check for: Code span marker
  500. // Note: need to check this after backtick fenced code blocks
  501. else if ($tag[0] === "`") {
  502. // Find corresponding end marker.
  503. $tag_re = preg_quote($tag);
  504. if (preg_match('{^(?>.+?|\n(?!\n))*?(?<!`)' . $tag_re . '(?!`)}',
  505. $text, $matches))
  506. {
  507. // End marker found: pass text unchanged until marker.
  508. $parsed .= $tag . $matches[0];
  509. $text = substr($text, strlen($matches[0]));
  510. }
  511. else {
  512. // Unmatched marker: just skip it.
  513. $parsed .= $tag;
  514. }
  515. }
  516. // Check for: Opening Block level tag or
  517. // Opening Context Block tag (like ins and del)
  518. // used as a block tag (tag is alone on it's line).
  519. else if (preg_match('{^<(?:' . $this->block_tags_re . ')\b}', $tag) ||
  520. ( preg_match('{^<(?:' . $this->context_block_tags_re . ')\b}', $tag) &&
  521. preg_match($newline_before_re, $parsed) &&
  522. preg_match($newline_after_re, $text) )
  523. )
  524. {
  525. // Need to parse tag and following text using the HTML parser.
  526. list($block_text, $text) =
  527. $this->_hashHTMLBlocks_inHTML($tag . $text, "hashBlock", true);
  528. // Make sure it stays outside of any paragraph by adding newlines.
  529. $parsed .= "\n\n$block_text\n\n";
  530. }
  531. // Check for: Clean tag (like script, math)
  532. // HTML Comments, processing instructions.
  533. else if (preg_match('{^<(?:' . $this->clean_tags_re . ')\b}', $tag) ||
  534. $tag[1] === '!' || $tag[1] === '?')
  535. {
  536. // Need to parse tag and following text using the HTML parser.
  537. // (don't check for markdown attribute)
  538. list($block_text, $text) =
  539. $this->_hashHTMLBlocks_inHTML($tag . $text, "hashClean", false);
  540. $parsed .= $block_text;
  541. }
  542. // Check for: Tag with same name as enclosing tag.
  543. else if ($enclosing_tag_re !== '' &&
  544. // Same name as enclosing tag.
  545. preg_match('{^</?(?:' . $enclosing_tag_re . ')\b}', $tag))
  546. {
  547. // Increase/decrease nested tag count.
  548. if ($tag[1] === '/') {
  549. $depth--;
  550. } else if ($tag[strlen($tag)-2] !== '/') {
  551. $depth++;
  552. }
  553. if ($depth < 0) {
  554. // Going out of parent element. Clean up and break so we
  555. // return to the calling function.
  556. $text = $tag . $text;
  557. break;
  558. }
  559. $parsed .= $tag;
  560. }
  561. else {
  562. $parsed .= $tag;
  563. }
  564. } while ($depth >= 0);
  565. return array($parsed, $text);
  566. }
  567. /**
  568. * Parse HTML, calling _HashHTMLBlocks_InMarkdown for block tags.
  569. *
  570. * * Calls $hash_method to convert any blocks.
  571. * * Stops when the first opening tag closes.
  572. * * $md_attr indicate if the use of the `markdown="1"` attribute is allowed.
  573. * (it is not inside clean tags)
  574. *
  575. * Returns an array of that form: ( processed text , remaining text )
  576. * @param string $text
  577. * @param string $hash_method
  578. * @param bool $md_attr Handle `markdown="1"` attribute
  579. * @return array
  580. */
  581. protected function _hashHTMLBlocks_inHTML($text, $hash_method, $md_attr) {
  582. if ($text === '') return array('', '');
  583. // Regex to match `markdown` attribute inside of a tag.
  584. $markdown_attr_re = '
  585. {
  586. \s* # Eat whitespace before the `markdown` attribute
  587. markdown
  588. \s*=\s*
  589. (?>
  590. (["\']) # $1: quote delimiter
  591. (.*?) # $2: attribute value
  592. \1 # matching delimiter
  593. |
  594. ([^\s>]*) # $3: unquoted attribute value
  595. )
  596. () # $4: make $3 always defined (avoid warnings)
  597. }xs';
  598. // Regex to match any tag.
  599. $tag_re = '{
  600. ( # $2: Capture whole tag.
  601. </? # Any opening or closing tag.
  602. [\w:$]+ # Tag name.
  603. (?:
  604. (?=[\s"\'/a-zA-Z0-9]) # Allowed characters after tag name.
  605. (?>
  606. ".*?" | # Double quotes (can contain `>`)
  607. \'.*?\' | # Single quotes (can contain `>`)
  608. .+? # Anything but quotes and `>`.
  609. )*?
  610. )?
  611. > # End of tag.
  612. |
  613. <!-- .*? --> # HTML Comment
  614. |
  615. <\?.*?\?> | <%.*?%> # Processing instruction
  616. |
  617. <!\[CDATA\[.*?\]\]> # CData Block
  618. )
  619. }xs';
  620. $original_text = $text; // Save original text in case of faliure.
  621. $depth = 0; // Current depth inside the tag tree.
  622. $block_text = ""; // Temporary text holder for current text.
  623. $parsed = ""; // Parsed text that will be returned.
  624. $base_tag_name_re = '';
  625. // Get the name of the starting tag.
  626. // (This pattern makes $base_tag_name_re safe without quoting.)
  627. if (preg_match('/^<([\w:$]*)\b/', $text, $matches))
  628. $base_tag_name_re = $matches[1];
  629. // Loop through every tag until we find the corresponding closing tag.
  630. do {
  631. // Split the text using the first $tag_match pattern found.
  632. // Text before pattern will be first in the array, text after
  633. // pattern will be at the end, and between will be any catches made
  634. // by the pattern.
  635. $parts = preg_split($tag_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE);
  636. if (count($parts) < 3) {
  637. // End of $text reached with unbalenced tag(s).
  638. // In that case, we return original text unchanged and pass the
  639. // first character as filtered to prevent an infinite loop in the
  640. // parent function.
  641. return array($original_text[0], substr($original_text, 1));
  642. }
  643. $block_text .= $parts[0]; // Text before current tag.
  644. $tag = $parts[1]; // Tag to handle.
  645. $text = $parts[2]; // Remaining text after current tag.
  646. // Check for: Auto-close tag (like <hr/>)
  647. // Comments and Processing Instructions.
  648. if (preg_match('{^</?(?:' . $this->auto_close_tags_re . ')\b}', $tag) ||
  649. $tag[1] === '!' || $tag[1] === '?')
  650. {
  651. // Just add the tag to the block as if it was text.
  652. $block_text .= $tag;
  653. }
  654. else {
  655. // Increase/decrease nested tag count. Only do so if
  656. // the tag's name match base tag's.
  657. if (preg_match('{^</?' . $base_tag_name_re . '\b}', $tag)) {
  658. if ($tag[1] === '/') {
  659. $depth--;
  660. } else if ($tag[strlen($tag)-2] !== '/') {
  661. $depth++;
  662. }
  663. }
  664. // Check for `markdown="1"` attribute and handle it.
  665. if ($md_attr &&
  666. preg_match($markdown_attr_re, $tag, $attr_m) &&
  667. preg_match('/^1|block|span$/', $attr_m[2] . $attr_m[3]))
  668. {
  669. // Remove `markdown` attribute from opening tag.
  670. $tag = preg_replace($markdown_attr_re, '', $tag);
  671. // Check if text inside this tag must be parsed in span mode.
  672. $mode = $attr_m[2] . $attr_m[3];
  673. $span_mode = $mode === 'span' || ($mode !== 'block' &&
  674. preg_match('{^<(?:' . $this->contain_span_tags_re . ')\b}', $tag));
  675. // Calculate indent before tag.
  676. if (preg_match('/(?:^|\n)( *?)(?! ).*?$/', $block_text, $matches)) {
  677. $strlen = $this->utf8_strlen;
  678. $indent = $strlen($matches[1], 'UTF-8');
  679. } else {
  680. $indent = 0;
  681. }
  682. // End preceding block with this tag.
  683. $block_text .= $tag;
  684. $parsed .= $this->$hash_method($block_text);
  685. // Get enclosing tag name for the ParseMarkdown function.
  686. // (This pattern makes $tag_name_re safe without quoting.)
  687. preg_match('/^<([\w:$]*)\b/', $tag, $matches);
  688. $tag_name_re = $matches[1];
  689. // Parse the content using the HTML-in-Markdown parser.
  690. list ($block_text, $text)
  691. = $this->_hashHTMLBlocks_inMarkdown($text, $indent,
  692. $tag_name_re, $span_mode);
  693. // Outdent markdown text.
  694. if ($indent > 0) {
  695. $block_text = preg_replace("/^[ ]{1,$indent}/m", "",
  696. $block_text);
  697. }
  698. // Append tag content to parsed text.
  699. if (!$span_mode) {
  700. $parsed .= "\n\n$block_text\n\n";
  701. } else {
  702. $parsed .= (string) $block_text;
  703. }
  704. // Start over with a new block.
  705. $block_text = "";
  706. }
  707. else $block_text .= $tag;
  708. }
  709. } while ($depth > 0);
  710. // Hash last block text that wasn't processed inside the loop.
  711. $parsed .= $this->$hash_method($block_text);
  712. return array($parsed, $text);
  713. }
  714. /**
  715. * Called whenever a tag must be hashed when a function inserts a "clean" tag
  716. * in $text, it passes through this function and is automaticaly escaped,
  717. * blocking invalid nested overlap.
  718. * @param string $text
  719. * @return string
  720. */
  721. protected function hashClean($text) {
  722. return $this->hashPart($text, 'C');
  723. }
  724. /**
  725. * Turn Markdown link shortcuts into XHTML <a> tags.
  726. * @param string $text
  727. * @return string
  728. */
  729. protected function doAnchors($text) {
  730. if ($this->in_anchor) {
  731. return $text;
  732. }
  733. $this->in_anchor = true;
  734. // First, handle reference-style links: [link text] [id]
  735. $text = preg_replace_callback('{
  736. ( # wrap whole match in $1
  737. \[
  738. (' . $this->nested_brackets_re . ') # link text = $2
  739. \]
  740. [ ]? # one optional space
  741. (?:\n[ ]*)? # one optional newline followed by spaces
  742. \[
  743. (.*?) # id = $3
  744. \]
  745. )
  746. }xs',
  747. array($this, '_doAnchors_reference_callback'), $text);
  748. // Next, inline-style links: [link text](url "optional title")
  749. $text = preg_replace_callback('{
  750. ( # wrap whole match in $1
  751. \[
  752. (' . $this->nested_brackets_re . ') # link text = $2
  753. \]
  754. \( # literal paren
  755. [ \n]*
  756. (?:
  757. <(.+?)> # href = $3
  758. |
  759. (' . $this->nested_url_parenthesis_re . ') # href = $4
  760. )
  761. [ \n]*
  762. ( # $5
  763. ([\'"]) # quote char = $6
  764. (.*?) # Title = $7
  765. \6 # matching quote
  766. [ \n]* # ignore any spaces/tabs between closing quote and )
  767. )? # title is optional
  768. \)
  769. (?:[ ]? ' . $this->id_class_attr_catch_re . ' )? # $8 = id/class attributes
  770. )
  771. }xs',
  772. array($this, '_doAnchors_inline_callback'), $text);
  773. // Last, handle reference-style shortcuts: [link text]
  774. // These must come last in case you've also got [link text][1]
  775. // or [link text](/foo)
  776. $text = preg_replace_callback('{
  777. ( # wrap whole match in $1
  778. \[
  779. ([^\[\]]+) # link text = $2; can\'t contain [ or ]
  780. \]
  781. )
  782. }xs',
  783. array($this, '_doAnchors_reference_callback'), $text);
  784. $this->in_anchor = false;
  785. return $text;
  786. }
  787. /**
  788. * Callback for reference anchors
  789. * @param array $matches
  790. * @return string
  791. */
  792. protected function _doAnchors_reference_callback($matches) {
  793. $whole_match = $matches[1];
  794. $link_text = $matches[2];
  795. $link_id =& $matches[3];
  796. if ($link_id == "") {
  797. // for shortcut links like [this][] or [this].
  798. $link_id = $link_text;
  799. }
  800. // lower-case and turn embedded newlines into spaces
  801. $link_id = strtolower($link_id);
  802. $link_id = preg_replace('{[ ]?\n}', ' ', $link_id);
  803. if (isset($this->urls[$link_id])) {
  804. $url = $this->urls[$link_id];
  805. $url = $this->encodeURLAttribute($url);
  806. $result = "<a href=\"$url\"";
  807. if ( isset( $this->titles[$link_id] ) ) {
  808. $title = $this->titles[$link_id];
  809. $title = $this->encodeAttribute($title);
  810. $result .= " title=\"$title\"";
  811. }
  812. if (isset($this->ref_attr[$link_id]))
  813. $result .= $this->ref_attr[$link_id];
  814. $link_text = $this->runSpanGamut($link_text);
  815. $result .= ">$link_text</a>";
  816. $result = $this->hashPart($result);
  817. }
  818. else {
  819. $result = $whole_match;
  820. }
  821. return $result;
  822. }
  823. /**
  824. * Callback for inline anchors
  825. * @param array $matches
  826. * @return string
  827. */
  828. protected function _doAnchors_inline_callback($matches) {
  829. $link_text = $this->runSpanGamut($matches[2]);
  830. $url = $matches[3] === '' ? $matches[4] : $matches[3];
  831. $title_quote =& $matches[6];
  832. $title =& $matches[7];
  833. $attr = $this->doExtraAttributes("a", $dummy =& $matches[8]);
  834. // if the URL was of the form <s p a c e s> it got caught by the HTML
  835. // tag parser and hashed. Need to reverse the process before using the URL.
  836. $unhashed = $this->unhash($url);
  837. if ($unhashed !== $url)
  838. $url = preg_replace('/^<(.*)>$/', '\1', $unhashed);
  839. $url = $this->encodeURLAttribute($url);
  840. $result = "<a href=\"$url\"";
  841. if (isset($title) && $title_quote) {
  842. $title = $this->encodeAttribute($title);
  843. $result .= " title=\"$title\"";
  844. }
  845. $result .= $attr;
  846. $link_text = $this->runSpanGamut($link_text);
  847. $result .= ">$link_text</a>";
  848. return $this->hashPart($result);
  849. }
  850. /**
  851. * Turn Markdown image shortcuts into <img> tags.
  852. * @param string $text
  853. * @return string
  854. */
  855. protected function doImages($text) {
  856. // First, handle reference-style labeled images: ![alt text][id]
  857. $text = preg_replace_callback('{
  858. ( # wrap whole match in $1
  859. !\[
  860. (' . $this->nested_brackets_re . ') # alt text = $2
  861. \]
  862. [ ]? # one optional space
  863. (?:\n[ ]*)? # one optional newline followed by spaces
  864. \[
  865. (.*?) # id = $3
  866. \]
  867. )
  868. }xs',
  869. array($this, '_doImages_reference_callback'), $text);
  870. // Next, handle inline images: ![alt text](url "optional title")
  871. // Don't forget: encode * and _
  872. $text = preg_replace_callback('{
  873. ( # wrap whole match in $1
  874. !\[
  875. (' . $this->nested_brackets_re . ') # alt text = $2
  876. \]
  877. \s? # One optional whitespace character
  878. \( # literal paren
  879. [ \n]*
  880. (?:
  881. <(\S*)> # src url = $3
  882. |
  883. (' . $this->nested_url_parenthesis_re . ') # src url = $4
  884. )
  885. [ \n]*
  886. ( # $5
  887. ([\'"]) # quote char = $6
  888. (.*?) # title = $7
  889. \6 # matching quote
  890. [ \n]*
  891. )? # title is optional
  892. \)
  893. (?:[ ]? ' . $this->id_class_attr_catch_re . ' )? # $8 = id/class attributes
  894. )
  895. }xs',
  896. array($this, '_doImages_inline_callback'), $text);
  897. return $text;
  898. }
  899. /**
  900. * Callback for referenced images
  901. * @param array $matches
  902. * @return string
  903. */
  904. protected function _doImages_reference_callback($matches) {
  905. $whole_match = $matches[1];
  906. $alt_text = $matches[2];
  907. $link_id = strtolower($matches[3]);
  908. if ($link_id === "") {
  909. $link_id = strtolower($alt_text); // for shortcut links like ![this][].
  910. }
  911. $alt_text = $this->encodeAttribute($alt_text);
  912. if (isset($this->urls[$link_id])) {
  913. $url = $this->encodeURLAttribute($this->urls[$link_id]);
  914. $result = "<img src=\"$url\" alt=\"$alt_text\"";
  915. if (isset($this->titles[$link_id])) {
  916. $title = $this->titles[$link_id];
  917. $title = $this->encodeAttribute($title);
  918. $result .= " title=\"$title\"";
  919. }
  920. if (isset($this->ref_attr[$link_id])) {
  921. $result .= $this->ref_attr[$link_id];
  922. }
  923. $result .= $this->empty_element_suffix;
  924. $result = $this->hashPart($result);
  925. }
  926. else {
  927. // If there's no such link ID, leave intact:
  928. $result = $whole_match;
  929. }
  930. return $result;
  931. }
  932. /**
  933. * Callback for inline images
  934. * @param array $matches
  935. * @return string
  936. */
  937. protected function _doImages_inline_callback($matches) {
  938. $alt_text = $matches[2];
  939. $url = $matches[3] === '' ? $matches[4] : $matches[3];
  940. $title_quote =& $matches[6];
  941. $title =& $matches[7];
  942. $attr = $this->doExtraAttributes("img", $dummy =& $matches[8]);
  943. $alt_text = $this->encodeAttribute($alt_text);
  944. $url = $this->encodeURLAttribute($url);
  945. $result = "<img src=\"$url\" alt=\"$alt_text\"";
  946. if (isset($title) && $title_quote) {
  947. $title = $this->encodeAttribute($title);
  948. $result .= " title=\"$title\""; // $title already quoted
  949. }
  950. $result .= $attr;
  951. $result .= $this->empty_element_suffix;
  952. return $this->hashPart($result);
  953. }
  954. /**
  955. * Process markdown headers. Redefined to add ID and class attribute support.
  956. * @param string $text
  957. * @return string
  958. */
  959. protected function doHeaders($text) {
  960. // Setext-style headers:
  961. // Header 1 {#header1}
  962. // ========
  963. //
  964. // Header 2 {#header2 .class1 .class2}
  965. // --------
  966. //
  967. $text = preg_replace_callback(
  968. '{
  969. (^.+?) # $1: Header text
  970. (?:[ ]+ ' . $this->id_class_attr_catch_re . ' )? # $3 = id/class attributes
  971. [ ]*\n(=+|-+)[ ]*\n+ # $3: Header footer
  972. }mx',
  973. array($this, '_doHeaders_callback_setext'), $text);
  974. // atx-style headers:
  975. // # Header 1 {#header1}
  976. // ## Header 2 {#header2}
  977. // ## Header 2 with closing hashes ## {#header3.class1.class2}
  978. // ...
  979. // ###### Header 6 {.class2}
  980. //
  981. $text = preg_replace_callback('{
  982. ^(\#{1,6}) # $1 = string of #\'s
  983. [ ]'.($this->hashtag_protection ? '+' : '*').'
  984. (.+?) # $2 = Header text
  985. [ ]*
  986. \#* # optional closing #\'s (not counted)
  987. (?:[ ]+ ' . $this->id_class_attr_catch_re . ' )? # $3 = id/class attributes
  988. [ ]*
  989. \n+
  990. }xm',
  991. array($this, '_doHeaders_callback_atx'), $text);
  992. return $text;
  993. }
  994. /**
  995. * Callback for setext headers
  996. * @param array $matches
  997. * @return string
  998. */
  999. protected function _doHeaders_callback_setext($matches) {
  1000. if ($matches[3] === '-' && preg_match('{^- }', $matches[1])) {
  1001. return $matches[0];
  1002. }
  1003. $level = $matches[3][0] === '=' ? 1 : 2;
  1004. $defaultId = is_callable($this->header_id_func) ? call_user_func($this->header_id_func, $matches[1]) : null;
  1005. $attr = $this->doExtraAttributes("h$level", $dummy =& $matches[2], $defaultId);
  1006. $block = "<h$level$attr>" . $this->runSpanGamut($matches[1]) . "</h$level>";
  1007. return "\n" . $this->hashBlock($block) . "\n\n";
  1008. }
  1009. /**
  1010. * Callback for atx headers
  1011. * @param array $matches
  1012. * @return string
  1013. */
  1014. protected function _doHeaders_callback_atx($matches) {
  1015. $level = strlen($matches[1]);
  1016. $defaultId = is_callable($this->header_id_func) ? call_user_func($this->header_id_func, $matches[2]) : null;
  1017. $attr = $this->doExtraAttributes("h$level", $dummy =& $matches[3], $defaultId);
  1018. $block = "<h$level$attr>" . $this->runSpanGamut($matches[2]) . "</h$level>";
  1019. return "\n" . $this->hashBlock($block) . "\n\n";
  1020. }
  1021. /**
  1022. * Form HTML tables.
  1023. * @param string $text
  1024. * @return string
  1025. */
  1026. protected function doTables($text) {
  1027. $less_than_tab = $this->tab_width - 1;
  1028. // Find tables with leading pipe.
  1029. //
  1030. // | Header 1 | Header 2
  1031. // | -------- | --------
  1032. // | Cell 1 | Cell 2
  1033. // | Cell 3 | Cell 4
  1034. $text = preg_replace_callback('
  1035. {
  1036. ^ # Start of a line
  1037. [ ]{0,' . $less_than_tab . '} # Allowed whitespace.
  1038. [|] # Optional leading pipe (present)
  1039. (.+) \n # $1: Header row (at least one pipe)
  1040. [ ]{0,' . $less_than_tab . '} # Allowed whitespace.
  1041. [|] ([ ]*[-:]+[-| :]*) \n # $2: Header underline
  1042. ( # $3: Cells
  1043. (?>
  1044. [ ]* # Allowed whitespace.
  1045. [|] .* \n # Row content.
  1046. )*
  1047. )
  1048. (?=\n|\Z) # Stop at final double newline.
  1049. }xm',
  1050. array($this, '_doTable_leadingPipe_callback'), $text);
  1051. // Find tables without leading pipe.
  1052. //
  1053. // Header 1 | Header 2
  1054. // -------- | --------
  1055. // Cell 1 | Cell 2
  1056. // Cell 3 | Cell 4
  1057. $text = preg_replace_callback('
  1058. {
  1059. ^ # Start of a line
  1060. [ ]{0,' . $less_than_tab . '} # Allowed whitespace.
  1061. (\S.*[|].*) \n # $1: Header row (at least one pipe)
  1062. [ ]{0,' . $less_than_tab . '} # Allowed whitespace.
  1063. ([-:]+[ ]*[|][-| :]*) \n # $2: Header underline
  1064. ( # $3: Cells
  1065. (?>
  1066. .* [|] .* \n # Row content
  1067. )*
  1068. )
  1069. (?=\n|\Z) # Stop at final double newline.
  1070. }xm',
  1071. array($this, '_DoTable_callback'), $text);
  1072. return $text;
  1073. }
  1074. /**
  1075. * Callback for removing the leading pipe for each row
  1076. * @param array $matches
  1077. * @return string
  1078. */
  1079. protected function _doTable_leadingPipe_callback($matches) {
  1080. $head = $matches[1];
  1081. $underline = $matches[2];
  1082. $content = $matches[3];
  1083. $content = preg_replace('/^ *[|]/m', '', $content);
  1084. return $this->_doTable_callback(array($matches[0], $head, $underline, $content));
  1085. }
  1086. /**
  1087. * Make the align attribute in a table
  1088. * @param string $alignname
  1089. * @return string
  1090. */
  1091. protected function _doTable_makeAlignAttr($alignname) {
  1092. if (empty($this->table_align_class_tmpl)) {
  1093. return " align=\"$alignname\"";
  1094. }
  1095. $classname = str_replace('%%', $alignname, $this->table_align_class_tmpl);
  1096. return " class=\"$classname\"";
  1097. }
  1098. /**
  1099. * Calback for processing tables
  1100. * @param array $matches
  1101. * @return string
  1102. */
  1103. protected function _doTable_callback($matches) {
  1104. $head = $matches[1];
  1105. $underline = $matches[2];
  1106. $content = $matches[3];
  1107. // Remove any tailing pipes for each line.
  1108. $head = preg_replace('/[|] *$/m', '', $head);
  1109. $underline = preg_replace('/[|] *$/m', '', $underline);
  1110. $content = preg_replace('/[|] *$/m', '', $content);
  1111. // Reading alignement from header underline.
  1112. $separators = preg_split('/ *[|] */', $underline);
  1113. foreach ($separators as $n => $s) {
  1114. if (preg_match('/^ *-+: *$/', $s))
  1115. $attr[$n] = $this->_doTable_makeAlignAttr('right');
  1116. else if (preg_match('/^ *:-+: *$/', $s))
  1117. $attr[$n] = $this->_doTable_makeAlignAttr('center');
  1118. else if (preg_match('/^ *:-+ *$/', $s))
  1119. $attr[$n] = $this->_doTable_makeAlignAttr('left');
  1120. else
  1121. $attr[$n] = '';
  1122. }
  1123. // Parsing span elements, including code spans, character escapes,
  1124. // and inline HTML tags, so that pipes inside those gets ignored.
  1125. $head = $this->parseSpan($head);
  1126. $headers = preg_split('/ *[|] */', $head);
  1127. $col_count = count($headers);
  1128. $attr = array_pad($attr, $col_count, '');
  1129. // Write column headers.
  1130. $text = "<table>\n";
  1131. $text .= "<thead>\n";
  1132. $text .= "<tr>\n";
  1133. foreach ($headers as $n => $header) {
  1134. $text .= " <th$attr[$n]>" . $this->runSpanGamut(trim($header)) . "</th>\n";
  1135. }
  1136. $text .= "</tr>\n";
  1137. $text .= "</thead>\n";
  1138. // Split content by row.
  1139. $rows = explode("\n", trim($content, "\n"));
  1140. $text .= "<tbody>\n";
  1141. foreach ($rows as $row) {
  1142. // Parsing span elements, including code spans, character escapes,
  1143. // and inline HTML tags, so that pipes inside those gets ignored.
  1144. $row = $this->parseSpan($row);
  1145. // Split row by cell.
  1146. $row_cells = preg_split('/ *[|] */', $row, $col_count);
  1147. $row_cells = array_pad($row_cells, $col_count, '');
  1148. $text .= "<tr>\n";
  1149. foreach ($row_cells as $n => $cell) {
  1150. $text .= " <td$attr[$n]>" . $this->runSpanGamut(trim($cell)) . "</td>\n";
  1151. }
  1152. $text .= "</tr>\n";
  1153. }
  1154. $text .= "</tbody>\n";
  1155. $text .= "</table>";
  1156. return $this->hashBlock($text) . "\n";
  1157. }
  1158. /**
  1159. * Form HTML definition lists.
  1160. * @param string $text
  1161. * @return string
  1162. */
  1163. protected function doDefLists($text) {
  1164. $less_than_tab = $this->tab_width - 1;
  1165. // Re-usable pattern to match any entire dl list:
  1166. $whole_list_re = '(?>
  1167. ( # $1 = whole list
  1168. ( # $2
  1169. [ ]{0,' . $less_than_tab . '}
  1170. ((?>.*\S.*\n)+) # $3 = defined term
  1171. \n?
  1172. [ ]{0,' . $less_than_tab . '}:[ ]+ # colon starting definition
  1173. )
  1174. (?s:.+?)
  1175. ( # $4
  1176. \z
  1177. |
  1178. \n{2,}
  1179. (?=\S)
  1180. (?! # Negative lookahead for another term
  1181. [ ]{0,' . $less_than_tab . '}
  1182. (?: \S.*\n )+? # defined term
  1183. \n?
  1184. [ ]{0,' . $less_than_tab . '}:[ ]+ # colon starting definition
  1185. )
  1186. (?! # Negative lookahead for another definition
  1187. [ ]{0,' . $less_than_tab . '}:[ ]+ # colon starting definition
  1188. )
  1189. )
  1190. )
  1191. )'; // mx
  1192. $text = preg_replace_callback('{
  1193. (?>\A\n?|(?<=\n\n))
  1194. ' . $whole_list_re . '
  1195. }mx',
  1196. array($this, '_doDefLists_callback'), $text);
  1197. return $text;
  1198. }
  1199. /**
  1200. * Callback for processing definition lists
  1201. * @param array $matches
  1202. * @return string
  1203. */
  1204. protected function _doDefLists_callback($matches) {
  1205. // Re-usable patterns to match list item bullets and number markers:
  1206. $list = $matches[1];
  1207. // Turn double returns into triple returns, so that we can make a
  1208. // paragraph for the last item in a list, if necessary:
  1209. $result = trim($this->processDefListItems($list));
  1210. $result = "<dl>\n" . $result . "\n</dl>";
  1211. return $this->hashBlock($result) . "\n\n";
  1212. }
  1213. /**
  1214. * Process the contents of a single definition list, splitting it
  1215. * into individual term and definition list items.
  1216. * @param string $list_str
  1217. * @return string
  1218. */
  1219. protected function processDefListItems($list_str) {
  1220. $less_than_tab = $this->tab_width - 1;
  1221. // Trim trailing blank lines:
  1222. $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str);
  1223. // Process definition terms.
  1224. $list_str = preg_replace_callback('{
  1225. (?>\A\n?|\n\n+) # leading line
  1226. ( # definition terms = $1
  1227. [ ]{0,' . $less_than_tab . '} # leading whitespace
  1228. (?!\:[ ]|[ ]) # negative lookahead for a definition
  1229. # mark (colon) or more whitespace.
  1230. (?> \S.* \n)+? # actual term (not whitespace).
  1231. )
  1232. (?=\n?[ ]{0,3}:[ ]) # lookahead for following line feed
  1233. # with a definition mark.
  1234. }xm',
  1235. array($this, '_processDefListItems_callback_dt'), $list_str);
  1236. // Process actual definitions.
  1237. $list_str = preg_replace_callback('{
  1238. \n(\n+)? # leading line = $1
  1239. ( # marker space = $2
  1240. [ ]{0,' . $less_than_tab . '} # whitespace before colon
  1241. \:[ ]+ # definition mark (colon)
  1242. )
  1243. ((?s:.+?)) # definition text = $3
  1244. (?= \n+ # stop at next definition mark,
  1245. (?: # next term or end of text
  1246. [ ]{0,' . $less_than_tab . '} \:[ ] |
  1247. <dt> | \z
  1248. )
  1249. )
  1250. }xm',
  1251. array($this, '_processDefListItems_callback_dd'), $list_str);
  1252. return $list_str;
  1253. }
  1254. /**
  1255. * Callback for <dt> elements in definition lists
  1256. * @param array $matches
  1257. * @return string
  1258. */
  1259. protected function _processDefListItems_callback_dt($matches) {
  1260. $terms = explode("\n", trim($matches[1]));
  1261. $text = '';
  1262. foreach ($terms as $term) {
  1263. $term = $this->runSpanGamut(trim($term));
  1264. $text .= "\n<dt>" . $term . "</dt>";
  1265. }
  1266. return $text . "\n";
  1267. }
  1268. /**
  1269. * Callback for <dd> elements in definition lists
  1270. * @param array $matches
  1271. * @return string
  1272. */
  1273. protected function _processDefListItems_callback_dd($matches) {
  1274. $leading_line = $matches[1];
  1275. $marker_space = $matches[2];
  1276. $def = $matches[3];
  1277. if ($leading_line || preg_match('/\n{2,}/', $def)) {
  1278. // Replace marker with the appropriate whitespace indentation
  1279. $def = str_repeat(' ', strlen($marker_space)) . $def;
  1280. $def = $this->runBlockGamut($this->outdent($def . "\n\n"));
  1281. $def = "\n". $def ."\n";
  1282. }
  1283. else {
  1284. $def = rtrim($def);
  1285. $def = $this->runSpanGamut($this->outdent($def));
  1286. }
  1287. return "\n<dd>" . $def . "</dd>\n";
  1288. }
  1289. /**
  1290. * Adding the fenced code block syntax to regular Markdown:
  1291. *
  1292. * ~~~
  1293. * Code block
  1294. * ~~~
  1295. *
  1296. * @param string $text
  1297. * @return string
  1298. */
  1299. protected function doFencedCodeBlocks($text) {
  1300. $text = preg_replace_callback('{
  1301. (?:\n|\A)
  1302. # 1: Opening marker
  1303. (
  1304. (?:~{3,}|`{3,}) # 3 or more tildes/backticks.
  1305. )
  1306. [ ]*
  1307. (?:
  1308. \.?([-_:a-zA-Z0-9]+) # 2: standalone class name
  1309. )?
  1310. [ ]*
  1311. (?:
  1312. ' . $this->id_class_attr_catch_re . ' # 3: Extra attributes
  1313. )?
  1314. [ ]* \n # Whitespace and newline following marker.
  1315. # 4: Content
  1316. (
  1317. (?>
  1318. (?!\1 [ ]* \n) # Not a closing marker.
  1319. .*\n+
  1320. )+
  1321. )
  1322. # Closing marker.
  1323. \1 [ ]* (?= \n )
  1324. }xm',
  1325. array($this, '_doFencedCodeBlocks_callback'), $text);
  1326. return $text;
  1327. }
  1328. /**
  1329. * Callback to process fenced code blocks
  1330. * @param array $matches
  1331. * @return string
  1332. */
  1333. protected function _doFencedCodeBlocks_callback($matches) {
  1334. $classname =& $matches[2];
  1335. $attrs =& $matches[3];
  1336. $codeblock = $matches[4];
  1337. if ($this->code_block_content_func) {
  1338. $codeblock = call_user_func($this->code_block_content_func, $codeblock, $classname);
  1339. } else {
  1340. $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES);
  1341. }
  1342. $codeblock = preg_replace_callback('/^\n+/',
  1343. array($this, '_doFencedCodeBlocks_newlines'), $codeblock);
  1344. $classes = array();
  1345. if ($classname !== "") {
  1346. if ($classname[0] === '.') {
  1347. $classname = substr($classname, 1);
  1348. }
  1349. $classes[] = $this->code_class_prefix . $classname;
  1350. }
  1351. $attr_str = $this->doExtraAttributes($this->code_attr_on_pre ? "pre" : "code", $attrs, null, $classes);
  1352. $pre_attr_str = $this->code_attr_on_pre ? $attr_str : '';
  1353. $code_attr_str = $this->code_attr_on_pre ? '' : $attr_str;
  1354. $codeblock = "<pre$pre_attr_str><code$code_attr_str>$codeblock</code></pre>";
  1355. return "\n\n".$this->hashBlock($codeblock)."\n\n";
  1356. }
  1357. /**
  1358. * Replace new lines in fenced code blocks
  1359. * @param array $matches
  1360. * @return string
  1361. */
  1362. protected function _doFencedCodeBlocks_newlines($matches) {
  1363. return str_repeat("<br$this->empty_element_suffix",
  1364. strlen($matches[0]));
  1365. }
  1366. /**
  1367. * Redefining emphasis markers so that emphasis by underscore does not
  1368. * work in the middle of a word.
  1369. * @var array
  1370. */
  1371. protected $em_relist = array(
  1372. '' => '(?:(?<!\*)\*(?!\*)|(?<![a-zA-Z0-9_])_(?!_))(?![\.,:;]?\s)',
  1373. '*' => '(?<![\s*])\*(?!\*)',
  1374. '_' => '(?<![\s_])_(?![a-zA-Z0-9_])',
  1375. );
  1376. protected $strong_relist = array(
  1377. '' => '(?:(?<!\*)\*\*(?!\*)|(?<![a-zA-Z0-9_])__(?!_))(?![\.,:;]?\s)',
  1378. '**' => '(?<![\s*])\*\*(?!\*)',
  1379. '__' => '(?<![\s_])__(?![a-zA-Z0-9_])',
  1380. );
  1381. protected $em_strong_relist = array(
  1382. '' => '(?:(?<!\*)\*\*\*(?!\*)|(?<![a-zA-Z0-9_])___(?!_))(?![\.,:;]?\s)',
  1383. '***' => '(?<![\s*])\*\*\*(?!\*)',
  1384. '___' => '(?<![\s_])___(?![a-zA-Z0-9_])',
  1385. );
  1386. /**
  1387. * Parse text into paragraphs
  1388. * @param string $text String to process in paragraphs
  1389. * @param boolean $wrap_in_p Whether paragraphs should be wrapped in <p> tags
  1390. * @return string HTML output
  1391. */
  1392. protected function formParagraphs($text, $wrap_in_p = true) {
  1393. // Strip leading and trailing lines:
  1394. $text = preg_replace('/\A\n+|\n+\z/', '', $text);
  1395. $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY);
  1396. // Wrap <p> tags and unhashify HTML blocks
  1397. foreach ($grafs as $key => $value) {
  1398. $value = trim($this->runSpanGamut($value));
  1399. // Check if this should be enclosed in a paragraph.
  1400. // Clean tag hashes & block tag hashes are left alone.
  1401. $is_p = $wrap_in_p && !preg_match('/^B\x1A[0-9]+B|^C\x1A[0-9]+C$/', $value);
  1402. if ($is_p) {
  1403. $value = "<p>$value</p>";
  1404. }
  1405. $grafs[$key] = $value;
  1406. }
  1407. // Join grafs in one text, then unhash HTML tags.
  1408. $text = implode("\n\n", $grafs);
  1409. // Finish by removing any tag hashes still present in $text.
  1410. $text = $this->unhash($text);
  1411. return $text;
  1412. }
  1413. /**
  1414. * Footnotes - Strips link definitions from text, stores the URLs and
  1415. * titles in hash references.
  1416. * @param string $text
  1417. * @return string
  1418. */
  1419. protected function stripFootnotes($text) {
  1420. $less_than_tab = $this->tab_width - 1;
  1421. // Link defs are in the form: [^id]: url "optional title"
  1422. $text = preg_replace_callback('{
  1423. ^[ ]{0,' . $less_than_tab . '}\[\^(.+?)\][ ]?: # note_id = $1
  1424. [ ]*
  1425. \n? # maybe *one* newline
  1426. ( # text = $2 (no blank lines allowed)
  1427. (?:
  1428. .+ # actual text
  1429. |
  1430. \n # newlines but
  1431. (?!\[.+?\][ ]?:\s)# negative lookahead for footnote or link definition marker.
  1432. (?!\n+[ ]{0,3}\S)# ensure line is not blank and followed
  1433. # by non-indented content
  1434. )*
  1435. )
  1436. }xm',
  1437. array($this, '_stripFootnotes_callback'),
  1438. $text);
  1439. return $text;
  1440. }
  1441. /**
  1442. * Callback for stripping footnotes
  1443. * @param array $matches
  1444. * @return string
  1445. */
  1446. protected function _stripFootnotes_callback($matches) {
  1447. $note_id = $this->fn_id_prefix . $matches[1];
  1448. $this->footnotes[$note_id] = $this->outdent($matches[2]);
  1449. return ''; // String that will replace the block
  1450. }
  1451. /**
  1452. * Replace footnote references in $text [^id] with a special text-token
  1453. * which will be replaced by the actual footnote marker in appendFootnotes.
  1454. * @param string $text
  1455. * @return string
  1456. */
  1457. protected function doFootnotes($text) {
  1458. if (!$this->in_anchor) {
  1459. $text = preg_replace('{\[\^(.+?)\]}', "F\x1Afn:\\1\x1A:", $text);
  1460. }
  1461. return $text;
  1462. }
  1463. /**
  1464. * Append footnote list to text
  1465. * @param string $text
  1466. * @return string
  1467. */
  1468. protected function appendFootnotes($text) {
  1469. $text = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}',
  1470. array($this, '_appendFootnotes_callback'), $text);
  1471. if ( ! empty( $this->footnotes_ordered ) ) {
  1472. $this->_doFootnotes();
  1473. if ( ! $this->omit_footnotes ) {
  1474. $text .= "\n\n";
  1475. $text .= "<div class=\"footnotes\" role=\"doc-endnotes\">\n";
  1476. $text .= "<hr" . $this->empty_element_suffix . "\n";
  1477. $text .= $this->footnotes_assembled;
  1478. $text .= "</div>";
  1479. }
  1480. }
  1481. return $text;
  1482. }
  1483. /**
  1484. * Generates the HTML for footnotes. Called by appendFootnotes, even if
  1485. * footnotes are not being appended.
  1486. * @return void
  1487. */
  1488. protected function _doFootnotes() {
  1489. $attr = array();
  1490. if ($this->fn_backlink_class !== "") {
  1491. $class = $this->fn_backlink_class;
  1492. $class = $this->encodeAttribute($class);
  1493. $attr['class'] = " class=\"$class\"";
  1494. }
  1495. $attr['role'] = " role=\"doc-backlink\"";
  1496. $num = 0;
  1497. $text = "<ol>\n\n";
  1498. while (!empty($this->footnotes_ordered)) {
  1499. $footnote = reset($this->footnotes_ordered);
  1500. $note_id = key($this->footnotes_ordered);
  1501. unset($this->footnotes_ordered[$note_id]);
  1502. $ref_count = $this->footnotes_ref_count[$note_id];
  1503. unset($this->footnotes_ref_count[$note_id]);
  1504. unset($this->footnotes[$note_id]);
  1505. $footnote .= "\n"; // Need to append newline before parsing.
  1506. $footnote = $this->runBlockGamut("$footnote\n");
  1507. $footnote = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}',
  1508. array($this, '_appendFootnotes_callback'), $footnote);
  1509. $num++;
  1510. $note_id = $this->encodeAttribute($note_id);
  1511. // Prepare backlink, multiple backlinks if multiple references
  1512. // Do not create empty backlinks if the html is blank
  1513. $backlink = "";
  1514. if (!empty($this->fn_backlink_html)) {
  1515. for ($ref_num = 1; $ref_num <= $ref_count; ++$ref_num) {
  1516. if (!empty($this->fn_backlink_title)) {
  1517. $attr['title'] = ' title="' . $this->encodeAttribute($this->fn_backlink_title) . '"';
  1518. }
  1519. if (!empty($this->fn_backlink_label)) {
  1520. $attr['label'] = ' aria-label="' . $this->encodeAttribute($this->fn_backlink_label) . '"';
  1521. }
  1522. $parsed_attr = $this->parseFootnotePlaceholders(
  1523. implode('', $attr),
  1524. $num,
  1525. $ref_num
  1526. );
  1527. $backlink_text = $this->parseFootnotePlaceholders(
  1528. $this->fn_backlink_html,
  1529. $num,
  1530. $ref_num
  1531. );
  1532. $ref_count_mark = $ref_num > 1 ? $ref_num : '';
  1533. $backlink .= " <a href=\"#fnref$ref_count_mark:$note_id\"$parsed_attr>$backlink_text</a>";
  1534. }
  1535. $backlink = trim($backlink);
  1536. }
  1537. // Add backlink to last paragraph; create new paragraph if needed.
  1538. if (!empty($backlink)) {
  1539. if (preg_match('{</p>$}', $footnote)) {
  1540. $footnote = substr($footnote, 0, -4) . "&#160;$backlink</p>";
  1541. } else {
  1542. $footnote .= "\n\n<p>$backlink</p>";
  1543. }
  1544. }
  1545. $text .= "<li id=\"fn:$note_id\" role=\"doc-endnote\">\n";
  1546. $text .= $footnote . "\n";
  1547. $text .= "</li>\n\n";
  1548. }
  1549. $text .= "</ol>\n";
  1550. $this->footnotes_assembled = $text;
  1551. }
  1552. /**
  1553. * Callback for appending footnotes
  1554. * @param array $matches
  1555. * @return string
  1556. */
  1557. protected function _appendFootnotes_callback($matches) {
  1558. $node_id = $this->fn_id_prefix . $matches[1];
  1559. // Create footnote marker only if it has a corresponding footnote *and*
  1560. // the footnote hasn't been used by another marker.
  1561. if (isset($this->footnotes[$node_id])) {
  1562. $num =& $this->footnotes_numbers[$node_id];
  1563. if (!isset($num)) {
  1564. // Transfer footnote content to the ordered list and give it its
  1565. // number
  1566. $this->footnotes_ordered[$node_id] = $this->footnotes[$node_id];
  1567. $this->footnotes_ref_count[$node_id] = 1;
  1568. $num = $this->footnote_counter++;
  1569. $ref_count_mark = '';
  1570. } else {
  1571. $ref_count_mark = $this->footnotes_ref_count[$node_id] += 1;
  1572. }
  1573. $attr = "";
  1574. if ($this->fn_link_class !== "") {
  1575. $class = $this->fn_link_class;
  1576. $class = $this->encodeAttribute($class);
  1577. $attr .= " class=\"$class\"";
  1578. }
  1579. if ($this->fn_link_title !== "") {
  1580. $title = $this->fn_link_title;
  1581. $title = $this->encodeAttribute($title);
  1582. $attr .= " title=\"$title\"";
  1583. }
  1584. $attr .= " role=\"doc-noteref\"";
  1585. $attr = str_replace("%%", $num, $attr);
  1586. $node_id = $this->encodeAttribute($node_id);
  1587. return
  1588. "<sup id=\"fnref$ref_count_mark:$node_id\">".
  1589. "<a href=\"#fn:$node_id\"$attr>$num</a>".
  1590. "</sup>";
  1591. }
  1592. return "[^" . $matches[1] . "]";
  1593. }
  1594. /**
  1595. * Build footnote label by evaluating any placeholders.
  1596. * - ^^ footnote number
  1597. * - %% footnote reference number (Nth reference to footnote number)
  1598. * @param string $label
  1599. * @param int $footnote_number
  1600. * @param int $reference_number
  1601. * @return string
  1602. */
  1603. protected function parseFootnotePlaceholders($label, $footnote_number, $reference_number) {
  1604. return str_replace(
  1605. array('^^', '%%'),
  1606. array($footnote_number, $reference_number),
  1607. $label
  1608. );
  1609. }
  1610. /**
  1611. * Abbreviations - strips abbreviations from text, stores titles in hash
  1612. * references.
  1613. * @param string $text
  1614. * @return string
  1615. */
  1616. protected function stripAbbreviations($text) {
  1617. $less_than_tab = $this->tab_width - 1;
  1618. // Link defs are in the form: [id]*: url "optional title"
  1619. $text = preg_replace_callback('{
  1620. ^[ ]{0,' . $less_than_tab . '}\*\[(.+?)\][ ]?: # abbr_id = $1
  1621. (.*) # text = $2 (no blank lines allowed)
  1622. }xm',
  1623. array($this, '_stripAbbreviations_callback'),
  1624. $text);
  1625. return $text;
  1626. }
  1627. /**
  1628. * Callback for stripping abbreviations
  1629. * @param array $matches
  1630. * @return string
  1631. */
  1632. protected function _stripAbbreviations_callback($matches) {
  1633. $abbr_word = $matches[1];
  1634. $abbr_desc = $matches[2];
  1635. if ($this->abbr_word_re) {
  1636. $this->abbr_word_re .= '|';
  1637. }
  1638. $this->abbr_word_re .= preg_quote($abbr_word);
  1639. $this->abbr_desciptions[$abbr_word] = trim($abbr_desc);
  1640. return ''; // String that will replace the block
  1641. }
  1642. /**
  1643. * Find defined abbreviations in text and wrap them in <abbr> elements.
  1644. * @param string $text
  1645. * @return string
  1646. */
  1647. protected function doAbbreviations($text) {
  1648. if ($this->abbr_word_re) {
  1649. // cannot use the /x modifier because abbr_word_re may
  1650. // contain significant spaces:
  1651. $text = preg_replace_callback('{' .
  1652. '(?<![\w\x1A])' .
  1653. '(?:' . $this->abbr_word_re . ')' .
  1654. '(?![\w\x1A])' .
  1655. '}',
  1656. array($this, '_doAbbreviations_callback'), $text);
  1657. }
  1658. return $text;
  1659. }
  1660. /**
  1661. * Callback for processing abbreviations
  1662. * @param array $matches
  1663. * @return string
  1664. */
  1665. protected function _doAbbreviations_callback($matches) {
  1666. $abbr = $matches[0];
  1667. if (isset($this->abbr_desciptions[$abbr])) {
  1668. $desc = $this->abbr_desciptions[$abbr];
  1669. if (empty($desc)) {
  1670. return $this->hashPart("<abbr>$abbr</abbr>");
  1671. }
  1672. $desc = $this->encodeAttribute($desc);
  1673. return $this->hashPart("<abbr title=\"$desc\">$abbr</abbr>");
  1674. }
  1675. return $matches[0];
  1676. }
  1677. protected function doStrikethrough($text) {
  1678. #
  1679. # Strikethrough:
  1680. # in: text ~~deleted~~ from doc
  1681. # out: text <del>deleted</del> from doc
  1682. #
  1683. $parts = preg_split('/(?<![~])(~~)(?![~])/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
  1684. //don't bother if nothing to do...
  1685. if(count($parts) <= 1)
  1686. return $text;
  1687. $inTag = false;
  1688. foreach($parts as &$part) {
  1689. if($part == '~~') {
  1690. $part = ($inTag ? '</del>' : '<del>');
  1691. $inTag = !$inTag;
  1692. }
  1693. }
  1694. //no hanging delimiter
  1695. if($inTag)
  1696. $parts[] = '</del>';
  1697. return implode('', $parts);
  1698. }
  1699. }