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