showdown.js 37 KB

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