You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

1297 lines
33 KiB

  1. //
  2. // showdown.js -- A javascript port of Markdown.
  3. //
  4. // Copyright (c) 2007 John Fraser.
  5. //
  6. // Original Markdown Copyright (c) 2004-2005 John Gruber
  7. // <http://daringfireball.net/projects/markdown/>
  8. //
  9. // Redistributable under a BSD-style open source license.
  10. // See license.txt for more information.
  11. //
  12. // The full source distribution is at:
  13. //
  14. // A A L
  15. // T C A
  16. // T K B
  17. //
  18. // <http://www.attacklab.net/>
  19. //
  20. //
  21. // Wherever possible, Showdown is a straight, line-by-line port
  22. // of the Perl version of Markdown.
  23. //
  24. // This is not a normal parser design; it's basically just a
  25. // series of string substitutions. It's hard to read and
  26. // maintain this way, but keeping Showdown close to the original
  27. // design makes it easier to port new features.
  28. //
  29. // More importantly, Showdown behaves like markdown.pl in most
  30. // edge cases. So web applications can do client-side preview
  31. // in Javascript, and then build identical HTML on the server.
  32. //
  33. // This port needs the new RegExp functionality of ECMA 262,
  34. // 3rd Edition (i.e. Javascript 1.5). Most modern web browsers
  35. // should do fine. Even with the new regular expression features,
  36. // We do a lot of work to emulate Perl's regex functionality.
  37. // The tricky changes in this file mostly have the "attacklab:"
  38. // label. Major or self-explanatory changes don't.
  39. //
  40. // Smart diff tools like Araxis Merge will be able to match up
  41. // this file with markdown.pl in a useful way. A little tweaking
  42. // helps: in a copy of markdown.pl, replace "#" with "//" and
  43. // replace "$text" with "text". Be sure to ignore whitespace
  44. // and line endings.
  45. //
  46. //
  47. // Showdown usage:
  48. //
  49. // var text = "Markdown *rocks*.";
  50. //
  51. // var converter = new Showdown.converter();
  52. // var html = converter.makeHtml(text);
  53. //
  54. // alert(html);
  55. //
  56. // Note: move the sample code to the bottom of this
  57. // file before uncommenting it.
  58. //
  59. //
  60. // Showdown namespace
  61. //
  62. var Showdown = {};
  63. //
  64. // converter
  65. //
  66. // Wraps all "globals" so that the only thing
  67. // exposed is makeHtml().
  68. //
  69. Showdown.converter = function() {
  70. //
  71. // Globals:
  72. //
  73. // Global hashes, used by various utility routines
  74. var g_urls;
  75. var g_titles;
  76. var g_html_blocks;
  77. // Used to track when we're inside an ordered or unordered list
  78. // (see _ProcessListItems() for details):
  79. var g_list_level = 0;
  80. this.makeHtml = function(text) {
  81. //
  82. // Main function. The order in which other subs are called here is
  83. // essential. Link and image substitutions need to happen before
  84. // _EscapeSpecialCharsWithinTagAttributes(), so that any *'s or _'s in the <a>
  85. // and <img> tags get encoded.
  86. //
  87. // Clear the global hashes. If we don't clear these, you get conflicts
  88. // from other articles when generating a page which contains more than
  89. // one article (e.g. an index page that shows the N most recent
  90. // articles):
  91. g_urls = new Array();
  92. g_titles = new Array();
  93. g_html_blocks = new Array();
  94. // attacklab: Replace ~ with ~T
  95. // This lets us use tilde as an escape char to avoid md5 hashes
  96. // The choice of character is arbitray; anything that isn't
  97. // magic in Markdown will work.
  98. text = text.replace(/~/g,"~T");
  99. // attacklab: Replace $ with ~D
  100. // RegExp interprets $ as a special character
  101. // when it's in a replacement string
  102. text = text.replace(/\$/g,"~D");
  103. // Standardize line endings
  104. text = text.replace(/\r\n/g,"\n"); // DOS to Unix
  105. text = text.replace(/\r/g,"\n"); // Mac to Unix
  106. // Make sure text begins and ends with a couple of newlines:
  107. text = "\n\n" + text + "\n\n";
  108. // Convert all tabs to spaces.
  109. text = _Detab(text);
  110. // Strip any lines consisting only of spaces and tabs.
  111. // This makes subsequent regexen easier to write, because we can
  112. // match consecutive blank lines with /\n+/ instead of something
  113. // contorted like /[ \t]*\n+/ .
  114. text = text.replace(/^[ \t]+$/mg,"");
  115. // Turn block-level HTML blocks into hash entries
  116. text = _HashHTMLBlocks(text);
  117. // Strip link definitions, store in hashes.
  118. text = _StripLinkDefinitions(text);
  119. text = _RunBlockGamut(text);
  120. text = _UnescapeSpecialChars(text);
  121. // attacklab: Restore dollar signs
  122. text = text.replace(/~D/g,"$$");
  123. // attacklab: Restore tildes
  124. text = text.replace(/~T/g,"~");
  125. return text;
  126. }
  127. var _StripLinkDefinitions = function(text) {
  128. //
  129. // Strips link definitions from text, stores the URLs and titles in
  130. // hash references.
  131. //
  132. // Link defs are in the form: ^[id]: url "optional title"
  133. /*
  134. var text = text.replace(/
  135. ^[ ]{0,3}\[(.+)\]: // id = $1 attacklab: g_tab_width - 1
  136. [ \t]*
  137. \n? // maybe *one* newline
  138. [ \t]*
  139. <?(\S+?)>? // url = $2
  140. [ \t]*
  141. \n? // maybe one newline
  142. [ \t]*
  143. (?:
  144. (\n*) // any lines skipped = $3 attacklab: lookbehind removed
  145. ["(]
  146. (.+?) // title = $4
  147. [")]
  148. [ \t]*
  149. )? // title is optional
  150. (?:\n+|$)
  151. /gm,
  152. function(){...});
  153. */
  154. var text = text.replace(/^[ ]{0,3}\[(.+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?[ \t]*\n?[ \t]*(?:(\n*)["(](.+?)[")][ \t]*)?(?:\n+|\Z)/gm,
  155. function (wholeMatch,m1,m2,m3,m4) {
  156. m1 = m1.toLowerCase();
  157. g_urls[m1] = _EncodeAmpsAndAngles(m2); // Link IDs are case-insensitive
  158. if (m3) {
  159. // Oops, found blank lines, so it's not a title.
  160. // Put back the parenthetical statement we stole.
  161. return m3+m4;
  162. } else if (m4) {
  163. g_titles[m1] = m4.replace(/"/g,"&quot;");
  164. }
  165. // Completely remove the definition from the text
  166. return "";
  167. }
  168. );
  169. return text;
  170. }
  171. var _HashHTMLBlocks = function(text) {
  172. // attacklab: Double up blank lines to reduce lookaround
  173. text = text.replace(/\n/g,"\n\n");
  174. // Hashify HTML blocks:
  175. // We only want to do this for block-level HTML tags, such as headers,
  176. // lists, and tables. That's because we still want to wrap <p>s around
  177. // "paragraphs" that are wrapped in non-block-level tags, such as anchors,
  178. // phrase emphasis, and spans. The list of tags we're looking for is
  179. // hard-coded:
  180. var block_tags_a = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del"
  181. var block_tags_b = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math"
  182. // First, look for nested blocks, e.g.:
  183. // <div>
  184. // <div>
  185. // tags for inner block must be indented.
  186. // </div>
  187. // </div>
  188. //
  189. // The outermost tags must start at the left margin for this to match, and
  190. // the inner nested divs must be indented.
  191. // We need to do this before the next, more liberal match, because the next
  192. // match will start at the first `<div>` and stop at the first `</div>`.
  193. // attacklab: This regex can be expensive when it fails.
  194. /*
  195. var text = text.replace(/
  196. ( // save in $1
  197. ^ // start of line (with /m)
  198. <($block_tags_a) // start tag = $2
  199. \b // word break
  200. // attacklab: hack around khtml/pcre bug...
  201. [^\r]*?\n // any number of lines, minimally matching
  202. </\2> // the matching end tag
  203. [ \t]* // trailing spaces/tabs
  204. (?=\n+) // followed by a newline
  205. ) // attacklab: there are sentinel newlines at end of document
  206. /gm,function(){...}};
  207. */
  208. text = text.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del)\b[^\r]*?\n<\/\2>[ \t]*(?=\n+))/gm,hashElement);
  209. //
  210. // Now match more liberally, simply from `\n<tag>` to `</tag>\n`
  211. //
  212. /*
  213. var text = text.replace(/
  214. ( // save in $1
  215. ^ // start of line (with /m)
  216. <($block_tags_b) // start tag = $2
  217. \b // word break
  218. // attacklab: hack around khtml/pcre bug...
  219. [^\r]*? // any number of lines, minimally matching
  220. .*</\2> // the matching end tag
  221. [ \t]* // trailing spaces/tabs
  222. (?=\n+) // followed by a newline
  223. ) // attacklab: there are sentinel newlines at end of document
  224. /gm,function(){...}};
  225. */
  226. text = text.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math)\b[^\r]*?.*<\/\2>[ \t]*(?=\n+)\n)/gm,hashElement);
  227. // Special case just for <hr />. It was easier to make a special case than
  228. // to make the other regex more complicated.
  229. /*
  230. text = text.replace(/
  231. ( // save in $1
  232. \n\n // Starting after a blank line
  233. [ ]{0,3}
  234. (<(hr) // start tag = $2
  235. \b // word break
  236. ([^<>])*? //
  237. \/?>) // the matching end tag
  238. [ \t]*
  239. (?=\n{2,}) // followed by a blank line
  240. )
  241. /g,hashElement);
  242. */
  243. text = text.replace(/(\n[ ]{0,3}(<(hr)\b([^<>])*?\/?>)[ \t]*(?=\n{2,}))/g,hashElement);
  244. // Special case for standalone HTML comments:
  245. /*
  246. text = text.replace(/
  247. ( // save in $1
  248. \n\n // Starting after a blank line
  249. [ ]{0,3} // attacklab: g_tab_width - 1
  250. <!
  251. (--[^\r]*?--\s*)+
  252. >
  253. [ \t]*
  254. (?=\n{2,}) // followed by a blank line
  255. )
  256. /g,hashElement);
  257. */
  258. text = text.replace(/(\n\n[ ]{0,3}<!(--[^\r]*?--\s*)+>[ \t]*(?=\n{2,}))/g,hashElement);
  259. // PHP and ASP-style processor instructions (<?...?> and <%...%>)
  260. /*
  261. text = text.replace(/
  262. (?:
  263. \n\n // Starting after a blank line
  264. )
  265. ( // save in $1
  266. [ ]{0,3} // attacklab: g_tab_width - 1
  267. (?:
  268. <([?%]) // $2
  269. [^\r]*?
  270. \2>
  271. )
  272. [ \t]*
  273. (?=\n{2,}) // followed by a blank line
  274. )
  275. /g,hashElement);
  276. */
  277. text = text.replace(/(?:\n\n)([ ]{0,3}(?:<([?%])[^\r]*?\2>)[ \t]*(?=\n{2,}))/g,hashElement);
  278. // attacklab: Undo double lines (see comment at top of this function)
  279. text = text.replace(/\n\n/g,"\n");
  280. return text;
  281. }
  282. var hashElement = function(wholeMatch,m1) {
  283. var blockText = m1;
  284. // Undo double lines
  285. blockText = blockText.replace(/\n\n/g,"\n");
  286. blockText = blockText.replace(/^\n/,"");
  287. // strip trailing blank lines
  288. blockText = blockText.replace(/\n+$/g,"");
  289. // Replace the element text with a marker ("~KxK" where x is its key)
  290. blockText = "\n\n~K" + (g_html_blocks.push(blockText)-1) + "K\n\n";
  291. return blockText;
  292. };
  293. var _RunBlockGamut = function(text) {
  294. //
  295. // These are all the transformations that form block-level
  296. // tags like paragraphs, headers, and list items.
  297. //
  298. text = _DoHeaders(text);
  299. // Do Horizontal Rules:
  300. var key = hashBlock("<hr />");
  301. text = text.replace(/^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$/gm,key);
  302. text = text.replace(/^[ ]{0,2}([ ]?\-[ ]?){3,}[ \t]*$/gm,key);
  303. text = text.replace(/^[ ]{0,2}([ ]?\_[ ]?){3,}[ \t]*$/gm,key);
  304. text = _DoLists(text);
  305. text = _DoCodeBlocks(text);
  306. text = _DoBlockQuotes(text);
  307. // We already ran _HashHTMLBlocks() before, in Markdown(), but that
  308. // was to escape raw HTML in the original Markdown source. This time,
  309. // we're escaping the markup we've just created, so that we don't wrap
  310. // <p> tags around block-level tags.
  311. text = _HashHTMLBlocks(text);
  312. text = _FormParagraphs(text);
  313. return text;
  314. }
  315. var _RunSpanGamut = function(text) {
  316. //
  317. // These are all the transformations that occur *within* block-level
  318. // tags like paragraphs, headers, and list items.
  319. //
  320. text = _DoCodeSpans(text);
  321. text = _EscapeSpecialCharsWithinTagAttributes(text);
  322. text = _EncodeBackslashEscapes(text);
  323. // Process anchor and image tags. Images must come first,
  324. // because ![foo][f] looks like an anchor.
  325. text = _DoImages(text);
  326. text = _DoAnchors(text);
  327. // Make links out of things like `<http://example.com/>`
  328. // Must come after _DoAnchors(), because you can use < and >
  329. // delimiters in inline links like [this](<url>).
  330. text = _DoAutoLinks(text);
  331. text = _EncodeAmpsAndAngles(text);
  332. text = _DoItalicsAndBold(text);
  333. // Do hard breaks:
  334. text = text.replace(/ +\n/g," <br />\n");
  335. return text;
  336. }
  337. var _EscapeSpecialCharsWithinTagAttributes = function(text) {
  338. //
  339. // Within tags -- meaning between < and > -- encode [\ ` * _] so they
  340. // don't conflict with their use in Markdown for code, italics and strong.
  341. //
  342. // Build a regex to find HTML tags and comments. See Friedl's
  343. // "Mastering Regular Expressions", 2nd Ed., pp. 200-201.
  344. var regex = /(<[a-z\/!$]("[^"]*"|'[^']*'|[^'">])*>|<!(--.*?--\s*)+>)/gi;
  345. text = text.replace(regex, function(wholeMatch) {
  346. var tag = wholeMatch.replace(/(.)<\/?code>(?=.)/g,"$1`");
  347. tag = escapeCharacters(tag,"\\`*_");
  348. return tag;
  349. });
  350. return text;
  351. }
  352. var _DoAnchors = function(text) {
  353. //
  354. // Turn Markdown link shortcuts into XHTML <a> tags.
  355. //
  356. //
  357. // First, handle reference-style links: [link text] [id]
  358. //
  359. /*
  360. text = text.replace(/
  361. ( // wrap whole match in $1
  362. \[
  363. (
  364. (?:
  365. \[[^\]]*\] // allow brackets nested one level
  366. |
  367. [^\[] // or anything else
  368. )*
  369. )
  370. \]
  371. [ ]? // one optional space
  372. (?:\n[ ]*)? // one optional newline followed by spaces
  373. \[
  374. (.*?) // id = $3
  375. \]
  376. )()()()() // pad remaining backreferences
  377. /g,_DoAnchors_callback);
  378. */
  379. text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,writeAnchorTag);
  380. //
  381. // Next, inline-style links: [link text](url "optional title")
  382. //
  383. /*
  384. text = text.replace(/
  385. ( // wrap whole match in $1
  386. \[
  387. (
  388. (?:
  389. \[[^\]]*\] // allow brackets nested one level
  390. |
  391. [^\[\]] // or anything else
  392. )
  393. )
  394. \]
  395. \( // literal paren
  396. [ \t]*
  397. () // no id, so leave $3 empty
  398. <?(.*?)>? // href = $4
  399. [ \t]*
  400. ( // $5
  401. (['"]) // quote char = $6
  402. (.*?) // Title = $7
  403. \6 // matching quote
  404. [ \t]* // ignore any spaces/tabs between closing quote and )
  405. )? // title is optional
  406. \)
  407. )
  408. /g,writeAnchorTag);
  409. */
  410. text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\]\([ \t]*()<?(.*?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,writeAnchorTag);
  411. //
  412. // Last, handle reference-style shortcuts: [link text]
  413. // These must come last in case you've also got [link test][1]
  414. // or [link test](/foo)
  415. //
  416. /*
  417. text = text.replace(/
  418. ( // wrap whole match in $1
  419. \[
  420. ([^\[\]]+) // link text = $2; can't contain '[' or ']'
  421. \]
  422. )()()()()() // pad rest of backreferences
  423. /g, writeAnchorTag);
  424. */
  425. text = text.replace(/(\[([^\[\]]+)\])()()()()()/g, writeAnchorTag);
  426. return text;
  427. }
  428. var writeAnchorTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) {
  429. if (m7 == undefined) m7 = "";
  430. var whole_match = m1;
  431. var link_text = m2;
  432. var link_id = m3.toLowerCase();
  433. var url = m4;
  434. var title = m7;
  435. if (url == "") {
  436. if (link_id == "") {
  437. // lower-case and turn embedded newlines into spaces
  438. link_id = link_text.toLowerCase().replace(/ ?\n/g," ");
  439. }
  440. url = "#"+link_id;
  441. if (g_urls[link_id] != undefined) {
  442. url = g_urls[link_id];
  443. if (g_titles[link_id] != undefined) {
  444. title = g_titles[link_id];
  445. }
  446. }
  447. else {
  448. if (whole_match.search(/\(\s*\)$/m)>-1) {
  449. // Special case for explicit empty url
  450. url = "";
  451. } else {
  452. return whole_match;
  453. }
  454. }
  455. }
  456. url = escapeCharacters(url,"*_");
  457. var result = "<a href=\"" + url + "\"";
  458. if (title != "") {
  459. title = title.replace(/"/g,"&quot;");
  460. title = escapeCharacters(title,"*_");
  461. result += " title=\"" + title + "\"";
  462. }
  463. result += ">" + link_text + "</a>";
  464. return result;
  465. }
  466. var _DoImages = function(text) {
  467. //
  468. // Turn Markdown image shortcuts into <img> tags.
  469. //
  470. //
  471. // First, handle reference-style labeled images: ![alt text][id]
  472. //
  473. /*
  474. text = text.replace(/
  475. ( // wrap whole match in $1
  476. !\[
  477. (.*?) // alt text = $2
  478. \]
  479. [ ]? // one optional space
  480. (?:\n[ ]*)? // one optional newline followed by spaces
  481. \[
  482. (.*?) // id = $3
  483. \]
  484. )()()()() // pad rest of backreferences
  485. /g,writeImageTag);
  486. */
  487. text = text.replace(/(!\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,writeImageTag);
  488. //
  489. // Next, handle inline images: ![alt text](url "optional title")
  490. // Don't forget: encode * and _
  491. /*
  492. text = text.replace(/
  493. ( // wrap whole match in $1
  494. !\[
  495. (.*?) // alt text = $2
  496. \]
  497. \s? // One optional whitespace character
  498. \( // literal paren
  499. [ \t]*
  500. () // no id, so leave $3 empty
  501. <?(\S+?)>? // src url = $4
  502. [ \t]*
  503. ( // $5
  504. (['"]) // quote char = $6
  505. (.*?) // title = $7
  506. \6 // matching quote
  507. [ \t]*
  508. )? // title is optional
  509. \)
  510. )
  511. /g,writeImageTag);
  512. */
  513. text = text.replace(/(!\[(.*?)\]\s?\([ \t]*()<?(\S+?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,writeImageTag);
  514. return text;
  515. }
  516. var writeImageTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) {
  517. var whole_match = m1;
  518. var alt_text = m2;
  519. var link_id = m3.toLowerCase();
  520. var url = m4;
  521. var title = m7;
  522. if (!title) title = "";
  523. if (url == "") {
  524. if (link_id == "") {
  525. // lower-case and turn embedded newlines into spaces
  526. link_id = alt_text.toLowerCase().replace(/ ?\n/g," ");
  527. }
  528. url = "#"+link_id;
  529. if (g_urls[link_id] != undefined) {
  530. url = g_urls[link_id];
  531. if (g_titles[link_id] != undefined) {
  532. title = g_titles[link_id];
  533. }
  534. }
  535. else {
  536. return whole_match;
  537. }
  538. }
  539. alt_text = alt_text.replace(/"/g,"&quot;");
  540. url = escapeCharacters(url,"*_");
  541. var result = "<img src=\"" + url + "\" alt=\"" + alt_text + "\"";
  542. // attacklab: Markdown.pl adds empty title attributes to images.
  543. // Replicate this bug.
  544. //if (title != "") {
  545. title = title.replace(/"/g,"&quot;");
  546. title = escapeCharacters(title,"*_");
  547. result += " title=\"" + title + "\"";
  548. //}
  549. result += " />";
  550. return result;
  551. }
  552. var _DoHeaders = function(text) {
  553. // Setext-style headers:
  554. // Header 1
  555. // ========
  556. //
  557. // Header 2
  558. // --------
  559. //
  560. text = text.replace(/^(.+)[ \t]*\n=+[ \t]*\n+/gm,
  561. function(wholeMatch,m1){return hashBlock("<h1>" + _RunSpanGamut(m1) + "</h1>");});
  562. text = text.replace(/^(.+)[ \t]*\n-+[ \t]*\n+/gm,
  563. function(matchFound,m1){return hashBlock("<h2>" + _RunSpanGamut(m1) + "</h2>");});
  564. // atx-style headers:
  565. // # Header 1
  566. // ## Header 2
  567. // ## Header 2 with closing hashes ##
  568. // ...
  569. // ###### Header 6
  570. //
  571. /*
  572. text = text.replace(/
  573. ^(\#{1,6}) // $1 = string of #'s
  574. [ \t]*
  575. (.+?) // $2 = Header text
  576. [ \t]*
  577. \#* // optional closing #'s (not counted)
  578. \n+
  579. /gm, function() {...});
  580. */
  581. text = text.replace(/^(\#{1,6})[ \t]*(.+?)[ \t]*\#*\n+/gm,
  582. function(wholeMatch,m1,m2) {
  583. var h_level = m1.length;
  584. return hashBlock("<h" + h_level + ">" + _RunSpanGamut(m2) + "</h" + h_level + ">");
  585. });
  586. return text;
  587. }
  588. // This declaration keeps Dojo compressor from outputting garbage:
  589. var _ProcessListItems;
  590. var _DoLists = function(text) {
  591. //
  592. // Form HTML ordered (numbered) and unordered (bulleted) lists.
  593. //
  594. // attacklab: add sentinel to hack around khtml/safari bug:
  595. // http://bugs.webkit.org/show_bug.cgi?id=11231
  596. text += "~0";
  597. // Re-usable pattern to match any entirel ul or ol list:
  598. /*
  599. var whole_list = /
  600. ( // $1 = whole list
  601. ( // $2
  602. [ ]{0,3} // attacklab: g_tab_width - 1
  603. ([*+-]|\d+[.]) // $3 = first list item marker
  604. [ \t]+
  605. )
  606. [^\r]+?
  607. ( // $4
  608. ~0 // sentinel for workaround; should be $
  609. |
  610. \n{2,}
  611. (?=\S)
  612. (?! // Negative lookahead for another list item marker
  613. [ \t]*
  614. (?:[*+-]|\d+[.])[ \t]+
  615. )
  616. )
  617. )/g
  618. */
  619. var whole_list = /^(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm;
  620. if (g_list_level) {
  621. text = text.replace(whole_list,function(wholeMatch,m1,m2) {
  622. var list = m1;
  623. var list_type = (m2.search(/[*+-]/g)>-1) ? "ul" : "ol";
  624. // Turn double returns into triple returns, so that we can make a
  625. // paragraph for the last item in a list, if necessary:
  626. list = list.replace(/\n{2,}/g,"\n\n\n");;
  627. var result = _ProcessListItems(list);
  628. // Trim any trailing whitespace, to put the closing `</$list_type>`
  629. // up on the preceding line, to get it past the current stupid
  630. // HTML block parser. This is a hack to work around the terrible
  631. // hack that is the HTML block parser.
  632. result = result.replace(/\s+$/,"");
  633. result = "<"+list_type+">" + result + "</"+list_type+">\n";
  634. return result;
  635. });
  636. } else {
  637. whole_list = /(\n\n|^\n?)(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/g;
  638. text = text.replace(whole_list,function(wholeMatch,m1,m2,m3) {
  639. var runup = m1;
  640. var list = m2;
  641. var list_type = (m3.search(/[*+-]/g)>-1) ? "ul" : "ol";
  642. // Turn double returns into triple returns, so that we can make a
  643. // paragraph for the last item in a list, if necessary:
  644. var list = list.replace(/\n{2,}/g,"\n\n\n");;
  645. var result = _ProcessListItems(list);
  646. result = runup + "<"+list_type+">\n" + result + "</"+list_type+">\n";
  647. return result;
  648. });
  649. }
  650. // attacklab: strip sentinel
  651. text = text.replace(/~0/,"");
  652. return text;
  653. }
  654. _ProcessListItems = function(list_str) {
  655. //
  656. // Process the contents of a single ordered or unordered list, splitting it
  657. // into individual list items.
  658. //
  659. // The $g_list_level global keeps track of when we're inside a list.
  660. // Each time we enter a list, we increment it; when we leave a list,
  661. // we decrement. If it's zero, we're not in a list anymore.
  662. //
  663. // We do this because when we're not inside a list, we want to treat
  664. // something like this:
  665. //
  666. // I recommend upgrading to version
  667. // 8. Oops, now this line is treated
  668. // as a sub-list.
  669. //
  670. // As a single paragraph, despite the fact that the second line starts
  671. // with a digit-period-space sequence.
  672. //
  673. // Whereas when we're inside a list (or sub-list), that line will be
  674. // treated as the start of a sub-list. What a kludge, huh? This is
  675. // an aspect of Markdown's syntax that's hard to parse perfectly
  676. // without resorting to mind-reading. Perhaps the solution is to
  677. // change the syntax rules such that sub-lists must start with a
  678. // starting cardinal number; e.g. "1." or "a.".
  679. g_list_level++;
  680. // trim trailing blank lines:
  681. list_str = list_str.replace(/\n{2,}$/,"\n");
  682. // attacklab: add sentinel to emulate \z
  683. list_str += "~0";
  684. /*
  685. list_str = list_str.replace(/
  686. (\n)? // leading line = $1
  687. (^[ \t]*) // leading whitespace = $2
  688. ([*+-]|\d+[.]) [ \t]+ // list marker = $3
  689. ([^\r]+? // list item text = $4
  690. (\n{1,2}))
  691. (?= \n* (~0 | \2 ([*+-]|\d+[.]) [ \t]+))
  692. /gm, function(){...});
  693. */
  694. list_str = list_str.replace(/(\n)?(^[ \t]*)([*+-]|\d+[.])[ \t]+([^\r]+?(\n{1,2}))(?=\n*(~0|\2([*+-]|\d+[.])[ \t]+))/gm,
  695. function(wholeMatch,m1,m2,m3,m4){
  696. var item = m4;
  697. var leading_line = m1;
  698. var leading_space = m2;
  699. if (leading_line || (item.search(/\n{2,}/)>-1)) {
  700. item = _RunBlockGamut(_Outdent(item));
  701. }
  702. else {
  703. // Recursion for sub-lists:
  704. item = _DoLists(_Outdent(item));
  705. item = item.replace(/\n$/,""); // chomp(item)
  706. item = _RunSpanGamut(item);
  707. }
  708. return "<li>" + item + "</li>\n";
  709. }
  710. );
  711. // attacklab: strip sentinel
  712. list_str = list_str.replace(/~0/g,"");
  713. g_list_level--;
  714. return list_str;
  715. }
  716. var _DoCodeBlocks = function(text) {
  717. //
  718. // Process Markdown `<pre><code>` blocks.
  719. //
  720. /*
  721. text = text.replace(text,
  722. /(?:\n\n|^)
  723. ( // $1 = the code block -- one or more lines, starting with a space/tab
  724. (?:
  725. (?:[ ]{4}|\t) // Lines must start with a tab or a tab-width of spaces - attacklab: g_tab_width
  726. .*\n+
  727. )+
  728. )
  729. (\n*[ ]{0,3}[^ \t\n]|(?=~0)) // attacklab: g_tab_width
  730. /g,function(){...});
  731. */
  732. // attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
  733. text += "~0";
  734. text = text.replace(/(?:\n\n|^)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=~0))/g,
  735. function(wholeMatch,m1,m2) {
  736. var codeblock = m1;
  737. var nextChar = m2;
  738. codeblock = _EncodeCode( _Outdent(codeblock));
  739. codeblock = _Detab(codeblock);
  740. codeblock = codeblock.replace(/^\n+/g,""); // trim leading newlines
  741. codeblock = codeblock.replace(/\n+$/g,""); // trim trailing whitespace
  742. codeblock = "<pre><code>" + codeblock + "\n</code></pre>";
  743. return hashBlock(codeblock) + nextChar;
  744. }
  745. );
  746. // attacklab: strip sentinel
  747. text = text.replace(/~0/,"");
  748. return text;
  749. }
  750. var hashBlock = function(text) {
  751. text = text.replace(/(^\n+|\n+$)/g,"");
  752. return "\n\n~K" + (g_html_blocks.push(text)-1) + "K\n\n";
  753. }
  754. var _DoCodeSpans = function(text) {
  755. //
  756. // * Backtick quotes are used for <code></code> spans.
  757. //
  758. // * You can use multiple backticks as the delimiters if you want to
  759. // include literal backticks in the code span. So, this input:
  760. //
  761. // Just type ``foo `bar` baz`` at the prompt.
  762. //
  763. // Will translate to:
  764. //
  765. // <p>Just type <code>foo `bar` baz</code> at the prompt.</p>
  766. //
  767. // There's no arbitrary limit to the number of backticks you
  768. // can use as delimters. If you need three consecutive backticks
  769. // in your code, use four for delimiters, etc.
  770. //
  771. // * You can use spaces to get literal backticks at the edges:
  772. //
  773. // ... type `` `bar` `` ...
  774. //
  775. // Turns to:
  776. //
  777. // ... type <code>`bar`</code> ...
  778. //
  779. /*
  780. text = text.replace(/
  781. (^|[^\\]) // Character before opening ` can't be a backslash
  782. (`+) // $2 = Opening run of `
  783. ( // $3 = The code block
  784. [^\r]*?
  785. [^`] // attacklab: work around lack of lookbehind
  786. )
  787. \2 // Matching closer
  788. (?!`)
  789. /gm, function(){...});
  790. */
  791. text = text.replace(/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/gm,
  792. function(wholeMatch,m1,m2,m3,m4) {
  793. var c = m3;
  794. c = c.replace(/^([ \t]*)/g,""); // leading whitespace
  795. c = c.replace(/[ \t]*$/g,""); // trailing whitespace
  796. c = _EncodeCode(c);
  797. return m1+"<code>"+c+"</code>";
  798. });
  799. return text;
  800. }
  801. var _EncodeCode = function(text) {
  802. //
  803. // Encode/escape certain characters inside Markdown code runs.
  804. // The point is that in code, these characters are literals,
  805. // and lose their special Markdown meanings.
  806. //
  807. // Encode all ampersands; HTML entities are not
  808. // entities within a Markdown code span.
  809. text = text.replace(/&/g,"&amp;");
  810. // Do the angle bracket song and dance:
  811. text = text.replace(/</g,"&lt;");
  812. text = text.replace(/>/g,"&gt;");
  813. // Now, escape characters that are magic in Markdown:
  814. text = escapeCharacters(text,"\*_{}[]\\",false);
  815. // jj the line above breaks this:
  816. //---
  817. //* Item
  818. // 1. Subitem
  819. // special char: *
  820. //---
  821. return text;
  822. }
  823. var _DoItalicsAndBold = function(text) {
  824. // <strong> must go first:
  825. text = text.replace(/(\*\*|__)(?=\S)([^\r]*?\S[*_]*)\1/g,
  826. "<strong>$2</strong>");
  827. text = text.replace(/(\*|_)(?=\S)([^\r]*?\S)\1/g,
  828. "<em>$2</em>");
  829. return text;
  830. }
  831. var _DoBlockQuotes = function(text) {
  832. /*
  833. text = text.replace(/
  834. ( // Wrap whole match in $1
  835. (
  836. ^[ \t]*>[ \t]? // '>' at the start of a line
  837. .+\n // rest of the first line
  838. (.+\n)* // subsequent consecutive lines
  839. \n* // blanks
  840. )+
  841. )
  842. /gm, function(){...});
  843. */
  844. text = text.replace(/((^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+)/gm,
  845. function(wholeMatch,m1) {
  846. var bq = m1;
  847. // attacklab: hack around Konqueror 3.5.4 bug:
  848. // "----------bug".replace(/^-/g,"") == "bug"
  849. bq = bq.replace(/^[ \t]*>[ \t]?/gm,"~0"); // trim one level of quoting
  850. // attacklab: clean up hack
  851. bq = bq.replace(/~0/g,"");
  852. bq = bq.replace(/^[ \t]+$/gm,""); // trim whitespace-only lines
  853. bq = _RunBlockGamut(bq); // recurse
  854. bq = bq.replace(/(^|\n)/g,"$1 ");
  855. // These leading spaces screw with <pre> content, so we need to fix that:
  856. bq = bq.replace(
  857. /(\s*<pre>[^\r]+?<\/pre>)/gm,
  858. function(wholeMatch,m1) {
  859. var pre = m1;
  860. // attacklab: hack around Konqueror 3.5.4 bug:
  861. pre = pre.replace(/^ /mg,"~0");
  862. pre = pre.replace(/~0/g,"");
  863. return pre;
  864. });
  865. return hashBlock("<blockquote>\n" + bq + "\n</blockquote>");
  866. });
  867. return text;
  868. }
  869. var _FormParagraphs = function(text) {
  870. //
  871. // Params:
  872. // $text - string to process with html <p> tags
  873. //
  874. // Strip leading and trailing lines:
  875. text = text.replace(/^\n+/g,"");
  876. text = text.replace(/\n+$/g,"");
  877. var grafs = text.split(/\n{2,}/g);
  878. var grafsOut = new Array();
  879. //
  880. // Wrap <p> tags.
  881. //
  882. var end = grafs.length;
  883. for (var i=0; i<end; i++) {
  884. var str = grafs[i];
  885. // if this is an HTML marker, copy it
  886. if (str.search(/~K(\d+)K/g) >= 0) {
  887. grafsOut.push(str);
  888. }
  889. else if (str.search(/\S/) >= 0) {
  890. str = _RunSpanGamut(str);
  891. str = str.replace(/^([ \t]*)/g,"<p>");
  892. str += "</p>"
  893. grafsOut.push(str);
  894. }
  895. }
  896. //
  897. // Unhashify HTML blocks
  898. //
  899. end = grafsOut.length;
  900. for (var i=0; i<end; i++) {
  901. // if this is a marker for an html block...
  902. while (grafsOut[i].search(/~K(\d+)K/) >= 0) {
  903. var blockText = g_html_blocks[RegExp.$1];
  904. blockText = blockText.replace(/\$/g,"$$$$"); // Escape any dollar signs
  905. grafsOut[i] = grafsOut[i].replace(/~K\d+K/,blockText);
  906. }
  907. }
  908. return grafsOut.join("\n\n");
  909. }
  910. var _EncodeAmpsAndAngles = function(text) {
  911. // Smart processing for ampersands and angle brackets that need to be encoded.
  912. // Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
  913. // http://bumppo.net/projects/amputator/
  914. text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g,"&amp;");
  915. // Encode naked <'s
  916. text = text.replace(/<(?![a-z\/?\$!])/gi,"&lt;");
  917. return text;
  918. }
  919. var _EncodeBackslashEscapes = function(text) {
  920. //
  921. // Parameter: String.
  922. // Returns: The string, with after processing the following backslash
  923. // escape sequences.
  924. //
  925. // attacklab: The polite way to do this is with the new
  926. // escapeCharacters() function:
  927. //
  928. // text = escapeCharacters(text,"\\",true);
  929. // text = escapeCharacters(text,"`*_{}[]()>#+-.!",true);
  930. //
  931. // ...but we're sidestepping its use of the (slow) RegExp constructor
  932. // as an optimization for Firefox. This function gets called a LOT.
  933. text = text.replace(/\\(\\)/g,escapeCharacters_callback);
  934. text = text.replace(/\\([`*_{}\[\]()>#+-.!])/g,escapeCharacters_callback);
  935. return text;
  936. }
  937. var _DoAutoLinks = function(text) {
  938. text = text.replace(/<((https?|ftp|dict):[^'">\s]+)>/gi,"<a href=\"$1\">$1</a>");
  939. // Email addresses: <address@domain.foo>
  940. /*
  941. text = text.replace(/
  942. <
  943. (?:mailto:)?
  944. (
  945. [-.\w]+
  946. \@
  947. [-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+
  948. )
  949. >
  950. /gi, _DoAutoLinks_callback());
  951. */
  952. text = text.replace(/<(?:mailto:)?([-.\w]+\@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi,
  953. function(wholeMatch,m1) {
  954. return _EncodeEmailAddress( _UnescapeSpecialChars(m1) );
  955. }
  956. );
  957. return text;
  958. }
  959. var _EncodeEmailAddress = function(addr) {
  960. //
  961. // Input: an email address, e.g. "foo@example.com"
  962. //
  963. // Output: the email address as a mailto link, with each character
  964. // of the address encoded as either a decimal or hex entity, in
  965. // the hopes of foiling most address harvesting spam bots. E.g.:
  966. //
  967. // <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101;
  968. // x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111;
  969. // &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a>
  970. //
  971. // Based on a filter by Matthew Wickline, posted to the BBEdit-Talk
  972. // mailing list: <http://tinyurl.com/yu7ue>
  973. //
  974. // attacklab: why can't javascript speak hex?
  975. function char2hex(ch) {
  976. var hexDigits = '0123456789ABCDEF';
  977. var dec = ch.charCodeAt(0);
  978. return(hexDigits.charAt(dec>>4) + hexDigits.charAt(dec&15));
  979. }
  980. var encode = [
  981. function(ch){return "&#"+ch.charCodeAt(0)+";";},
  982. function(ch){return "&#x"+char2hex(ch)+";";},
  983. function(ch){return ch;}
  984. ];
  985. addr = "mailto:" + addr;
  986. addr = addr.replace(/./g, function(ch) {
  987. if (ch == "@") {
  988. // this *must* be encoded. I insist.
  989. ch = encode[Math.floor(Math.random()*2)](ch);
  990. } else if (ch !=":") {
  991. // leave ':' alone (to spot mailto: later)
  992. var r = Math.random();
  993. // roughly 10% raw, 45% hex, 45% dec
  994. ch = (
  995. r > .9 ? encode[2](ch) :
  996. r > .45 ? encode[1](ch) :
  997. encode[0](ch)
  998. );
  999. }
  1000. return ch;
  1001. });
  1002. addr = "<a href=\"" + addr + "\">" + addr + "</a>";
  1003. addr = addr.replace(/">.+:/g,"\">"); // strip the mailto: from the visible part
  1004. return addr;
  1005. }
  1006. var _UnescapeSpecialChars = function(text) {
  1007. //
  1008. // Swap back in all the special characters we've hidden.
  1009. //
  1010. text = text.replace(/~E(\d+)E/g,
  1011. function(wholeMatch,m1) {
  1012. var charCodeToReplace = parseInt(m1);
  1013. return String.fromCharCode(charCodeToReplace);
  1014. }
  1015. );
  1016. return text;
  1017. }
  1018. var _Outdent = function(text) {
  1019. //
  1020. // Remove one level of line-leading tabs or spaces
  1021. //
  1022. // attacklab: hack around Konqueror 3.5.4 bug:
  1023. // "----------bug".replace(/^-/g,"") == "bug"
  1024. text = text.replace(/^(\t|[ ]{1,4})/gm,"~0"); // attacklab: g_tab_width
  1025. // attacklab: clean up hack
  1026. text = text.replace(/~0/g,"")
  1027. return text;
  1028. }
  1029. var _Detab = function(text) {
  1030. // attacklab: Detab's completely rewritten for speed.
  1031. // In perl we could fix it by anchoring the regexp with \G.
  1032. // In javascript we're less fortunate.
  1033. // expand first n-1 tabs
  1034. text = text.replace(/\t(?=\t)/g," "); // attacklab: g_tab_width
  1035. // replace the nth with two sentinels
  1036. text = text.replace(/\t/g,"~A~B");
  1037. // use the sentinel to anchor our regex so it doesn't explode
  1038. text = text.replace(/~B(.+?)~A/g,
  1039. function(wholeMatch,m1,m2) {
  1040. var leadingText = m1;
  1041. var numSpaces = 4 - leadingText.length % 4; // attacklab: g_tab_width
  1042. // there *must* be a better way to do this:
  1043. for (var i=0; i<numSpaces; i++) leadingText+=" ";
  1044. return leadingText;
  1045. }
  1046. );
  1047. // clean up sentinels
  1048. text = text.replace(/~A/g," "); // attacklab: g_tab_width
  1049. text = text.replace(/~B/g,"");
  1050. return text;
  1051. }
  1052. //
  1053. // attacklab: Utility functions
  1054. //
  1055. var escapeCharacters = function(text, charsToEscape, afterBackslash) {
  1056. // First we have to escape the escape characters so that
  1057. // we can build a character class out of them
  1058. var regexString = "([" + charsToEscape.replace(/([\[\]\\])/g,"\\$1") + "])";
  1059. if (afterBackslash) {
  1060. regexString = "\\\\" + regexString;
  1061. }
  1062. var regex = new RegExp(regexString,"g");
  1063. text = text.replace(regex,escapeCharacters_callback);
  1064. return text;
  1065. }
  1066. var escapeCharacters_callback = function(wholeMatch,m1) {
  1067. var charCodeToEscape = m1.charCodeAt(0);
  1068. return "~E"+charCodeToEscape+"E";
  1069. }
  1070. } // end of Showdown.converter