showdown.js 50 KB

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