2
0

showdown.js 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454
  1. //
  2. // showdown.js -- A javascript port of Markdown.
  3. //
  4. // Copyright (c) 2007 John Fraser.
  5. //
  6. // Original Markdown Copyright (c) 2004-2005 John Gruber
  7. // <http://daringfireball.net/projects/markdown/>
  8. //
  9. // Redistributable under a BSD-style open source license.
  10. // See license.txt for more information.
  11. //
  12. // The full source distribution is at:
  13. //
  14. // A A L
  15. // T C A
  16. // T K B
  17. //
  18. // <http://www.attacklab.net/>
  19. //
  20. //
  21. // Wherever possible, Showdown is a straight, line-by-line port
  22. // of the Perl version of Markdown.
  23. //
  24. // This is not a normal parser design; it's basically just a
  25. // series of string substitutions. It's hard to read and
  26. // maintain this way, but keeping Showdown close to the original
  27. // design makes it easier to port new features.
  28. //
  29. // More importantly, Showdown behaves like markdown.pl in most
  30. // edge cases. So web applications can do client-side preview
  31. // in Javascript, and then build identical HTML on the server.
  32. //
  33. // This port needs the new RegExp functionality of ECMA 262,
  34. // 3rd Edition (i.e. Javascript 1.5). Most modern web browsers
  35. // should do fine. Even with the new regular expression features,
  36. // We do a lot of work to emulate Perl's regex functionality.
  37. // The tricky changes in this file mostly have the "attacklab:"
  38. // label. Major or self-explanatory changes don't.
  39. //
  40. // Smart diff tools like Araxis Merge will be able to match up
  41. // this file with markdown.pl in a useful way. A little tweaking
  42. // helps: in a copy of markdown.pl, replace "#" with "//" and
  43. // replace "$text" with "text". Be sure to ignore whitespace
  44. // and line endings.
  45. //
  46. //
  47. // Showdown usage:
  48. //
  49. // var text = "Markdown *rocks*.";
  50. //
  51. // var converter = new Showdown.converter();
  52. // var html = converter.makeHtml(text);
  53. //
  54. // alert(html);
  55. //
  56. // Note: move the sample code to the bottom of this
  57. // file before uncommenting it.
  58. //
  59. //
  60. // Showdown namespace
  61. //
  62. var Showdown = { extensions: {} };
  63. //
  64. // forEach
  65. //
  66. var forEach = Showdown.forEach = function(obj, callback) {
  67. if (typeof obj.forEach === 'function') {
  68. obj.forEach(callback);
  69. } else {
  70. var i, len = obj.length;
  71. for (i = 0; i < len; i++) {
  72. callback(obj[i], i, obj);
  73. }
  74. }
  75. };
  76. //
  77. // Standard extension naming
  78. //
  79. var stdExtName = function(s) {
  80. return s.replace(/[_-]||\s/g, '').toLowerCase();
  81. };
  82. //
  83. // converter
  84. //
  85. // Wraps all "globals" so that the only thing
  86. // exposed is makeHtml().
  87. //
  88. Showdown.converter = function(converter_options) {
  89. //
  90. // Globals:
  91. //
  92. // Global hashes, used by various utility routines
  93. var g_urls;
  94. var g_titles;
  95. var g_html_blocks;
  96. // Used to track when we're inside an ordered or unordered list
  97. // (see _ProcessListItems() for details):
  98. var g_list_level = 0;
  99. // Global extensions
  100. var g_lang_extensions = [];
  101. var g_output_modifiers = [];
  102. //
  103. // Automatic Extension Loading (node only):
  104. //
  105. if (typeof module !== 'undefind' && typeof exports !== 'undefined' && typeof require !== 'undefind') {
  106. var fs = require('fs');
  107. if (fs) {
  108. // Search extensions folder
  109. var extensions = fs.readdirSync((__dirname || '.')+'/extensions').filter(function(file){
  110. return ~file.indexOf('.js');
  111. }).map(function(file){
  112. return file.replace(/\.js$/, '');
  113. });
  114. // Load extensions into Showdown namespace
  115. 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){return hashBlock('<h1 id="' + headerId(m1) + '">' + _RunSpanGamut(m1) + "</h1>");});
  658. text = text.replace(/^(.+)[ \t]*\n-+[ \t]*\n+/gm,
  659. function(matchFound,m1){return hashBlock('<h2 id="' + headerId(m1) + '">' + _RunSpanGamut(m1) + "</h2>");});
  660. // atx-style headers:
  661. // # Header 1
  662. // ## Header 2
  663. // ## Header 2 with closing hashes ##
  664. // ...
  665. // ###### Header 6
  666. //
  667. /*
  668. text = text.replace(/
  669. ^(\#{1,6}) // $1 = string of #'s
  670. [ \t]*
  671. (.+?) // $2 = Header text
  672. [ \t]*
  673. \#* // optional closing #'s (not counted)
  674. \n+
  675. /gm, function() {...});
  676. */
  677. text = text.replace(/^(\#{1,6})[ \t]*(.+?)[ \t]*\#*\n+/gm,
  678. function(wholeMatch,m1,m2) {
  679. var h_level = m1.length;
  680. return hashBlock("<h" + h_level + ' id="' + headerId(m2) + '">' + _RunSpanGamut(m2) + "</h" + h_level + ">");
  681. });
  682. function headerId(m) {
  683. return m.replace(/[^\w]/g, '').toLowerCase();
  684. }
  685. return text;
  686. }
  687. // This declaration keeps Dojo compressor from outputting garbage:
  688. var _ProcessListItems;
  689. var _DoLists = function(text) {
  690. //
  691. // Form HTML ordered (numbered) and unordered (bulleted) lists.
  692. //
  693. // attacklab: add sentinel to hack around khtml/safari bug:
  694. // http://bugs.webkit.org/show_bug.cgi?id=11231
  695. text += "~0";
  696. // Re-usable pattern to match any entirel ul or ol list:
  697. /*
  698. var whole_list = /
  699. ( // $1 = whole list
  700. ( // $2
  701. [ ]{0,3} // attacklab: g_tab_width - 1
  702. ([*+-]|\d+[.]) // $3 = first list item marker
  703. [ \t]+
  704. )
  705. [^\r]+?
  706. ( // $4
  707. ~0 // sentinel for workaround; should be $
  708. |
  709. \n{2,}
  710. (?=\S)
  711. (?! // Negative lookahead for another list item marker
  712. [ \t]*
  713. (?:[*+-]|\d+[.])[ \t]+
  714. )
  715. )
  716. )/g
  717. */
  718. var whole_list = /^(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm;
  719. if (g_list_level) {
  720. text = text.replace(whole_list,function(wholeMatch,m1,m2) {
  721. var list = m1;
  722. var list_type = (m2.search(/[*+-]/g)>-1) ? "ul" : "ol";
  723. // Turn double returns into triple returns, so that we can make a
  724. // paragraph for the last item in a list, if necessary:
  725. list = list.replace(/\n{2,}/g,"\n\n\n");;
  726. var result = _ProcessListItems(list);
  727. // Trim any trailing whitespace, to put the closing `</$list_type>`
  728. // up on the preceding line, to get it past the current stupid
  729. // HTML block parser. This is a hack to work around the terrible
  730. // hack that is the HTML block parser.
  731. result = result.replace(/\s+$/,"");
  732. result = "<"+list_type+">" + result + "</"+list_type+">\n";
  733. return result;
  734. });
  735. } else {
  736. whole_list = /(\n\n|^\n?)(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/g;
  737. text = text.replace(whole_list,function(wholeMatch,m1,m2,m3) {
  738. var runup = m1;
  739. var list = m2;
  740. var list_type = (m3.search(/[*+-]/g)>-1) ? "ul" : "ol";
  741. // Turn double returns into triple returns, so that we can make a
  742. // paragraph for the last item in a list, if necessary:
  743. var list = list.replace(/\n{2,}/g,"\n\n\n");;
  744. var result = _ProcessListItems(list);
  745. result = runup + "<"+list_type+">\n" + result + "</"+list_type+">\n";
  746. return result;
  747. });
  748. }
  749. // attacklab: strip sentinel
  750. text = text.replace(/~0/,"");
  751. return text;
  752. }
  753. _ProcessListItems = function(list_str) {
  754. //
  755. // Process the contents of a single ordered or unordered list, splitting it
  756. // into individual list items.
  757. //
  758. // The $g_list_level global keeps track of when we're inside a list.
  759. // Each time we enter a list, we increment it; when we leave a list,
  760. // we decrement. If it's zero, we're not in a list anymore.
  761. //
  762. // We do this because when we're not inside a list, we want to treat
  763. // something like this:
  764. //
  765. // I recommend upgrading to version
  766. // 8. Oops, now this line is treated
  767. // as a sub-list.
  768. //
  769. // As a single paragraph, despite the fact that the second line starts
  770. // with a digit-period-space sequence.
  771. //
  772. // Whereas when we're inside a list (or sub-list), that line will be
  773. // treated as the start of a sub-list. What a kludge, huh? This is
  774. // an aspect of Markdown's syntax that's hard to parse perfectly
  775. // without resorting to mind-reading. Perhaps the solution is to
  776. // change the syntax rules such that sub-lists must start with a
  777. // starting cardinal number; e.g. "1." or "a.".
  778. g_list_level++;
  779. // trim trailing blank lines:
  780. list_str = list_str.replace(/\n{2,}$/,"\n");
  781. // attacklab: add sentinel to emulate \z
  782. list_str += "~0";
  783. /*
  784. list_str = list_str.replace(/
  785. (\n)? // leading line = $1
  786. (^[ \t]*) // leading whitespace = $2
  787. ([*+-]|\d+[.]) [ \t]+ // list marker = $3
  788. ([^\r]+? // list item text = $4
  789. (\n{1,2}))
  790. (?= \n* (~0 | \2 ([*+-]|\d+[.]) [ \t]+))
  791. /gm, function(){...});
  792. */
  793. list_str = list_str.replace(/(\n)?(^[ \t]*)([*+-]|\d+[.])[ \t]+([^\r]+?(\n{1,2}))(?=\n*(~0|\2([*+-]|\d+[.])[ \t]+))/gm,
  794. function(wholeMatch,m1,m2,m3,m4){
  795. var item = m4;
  796. var leading_line = m1;
  797. var leading_space = m2;
  798. if (leading_line || (item.search(/\n{2,}/)>-1)) {
  799. item = _RunBlockGamut(_Outdent(item));
  800. }
  801. else {
  802. // Recursion for sub-lists:
  803. item = _DoLists(_Outdent(item));
  804. item = item.replace(/\n$/,""); // chomp(item)
  805. item = _RunSpanGamut(item);
  806. }
  807. return "<li>" + item + "</li>\n";
  808. }
  809. );
  810. // attacklab: strip sentinel
  811. list_str = list_str.replace(/~0/g,"");
  812. g_list_level--;
  813. return list_str;
  814. }
  815. var _DoCodeBlocks = function(text) {
  816. //
  817. // Process Markdown `<pre><code>` blocks.
  818. //
  819. /*
  820. text = text.replace(text,
  821. /(?:\n\n|^)
  822. ( // $1 = the code block -- one or more lines, starting with a space/tab
  823. (?:
  824. (?:[ ]{4}|\t) // Lines must start with a tab or a tab-width of spaces - attacklab: g_tab_width
  825. .*\n+
  826. )+
  827. )
  828. (\n*[ ]{0,3}[^ \t\n]|(?=~0)) // attacklab: g_tab_width
  829. /g,function(){...});
  830. */
  831. // attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
  832. text += "~0";
  833. text = text.replace(/(?:\n\n|^)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=~0))/g,
  834. function(wholeMatch,m1,m2) {
  835. var codeblock = m1;
  836. var nextChar = m2;
  837. codeblock = _EncodeCode( _Outdent(codeblock));
  838. codeblock = _Detab(codeblock);
  839. codeblock = codeblock.replace(/^\n+/g,""); // trim leading newlines
  840. codeblock = codeblock.replace(/\n+$/g,""); // trim trailing whitespace
  841. codeblock = "<pre><code>" + codeblock + "\n</code></pre>";
  842. return hashBlock(codeblock) + nextChar;
  843. }
  844. );
  845. // attacklab: strip sentinel
  846. text = text.replace(/~0/,"");
  847. return text;
  848. };
  849. var _DoGithubCodeBlocks = function(text) {
  850. //
  851. // Process Github-style code blocks
  852. // Example:
  853. // ```ruby
  854. // def hello_world(x)
  855. // puts "Hello, #{x}"
  856. // end
  857. // ```
  858. //
  859. // attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
  860. text += "~0";
  861. text = text.replace(/(?:^|\n)```(.*)\n([\s\S]*?)\n```/g,
  862. function(wholeMatch,m1,m2) {
  863. var language = m1;
  864. var codeblock = m2;
  865. codeblock = _EncodeCode(codeblock);
  866. codeblock = _Detab(codeblock);
  867. codeblock = codeblock.replace(/^\n+/g,""); // trim leading newlines
  868. codeblock = codeblock.replace(/\n+$/g,""); // trim trailing whitespace
  869. codeblock = "<pre><code" + (language ? " class=\"" + language + '"' : "") + ">" + codeblock + "\n</code></pre>";
  870. return hashBlock(codeblock);
  871. }
  872. );
  873. // attacklab: strip sentinel
  874. text = text.replace(/~0/,"");
  875. return text;
  876. }
  877. var hashBlock = function(text) {
  878. text = text.replace(/(^\n+|\n+$)/g,"");
  879. return "\n\n~K" + (g_html_blocks.push(text)-1) + "K\n\n";
  880. }
  881. var _DoCodeSpans = function(text) {
  882. //
  883. // * Backtick quotes are used for <code></code> spans.
  884. //
  885. // * You can use multiple backticks as the delimiters if you want to
  886. // include literal backticks in the code span. So, this input:
  887. //
  888. // Just type ``foo `bar` baz`` at the prompt.
  889. //
  890. // Will translate to:
  891. //
  892. // <p>Just type <code>foo `bar` baz</code> at the prompt.</p>
  893. //
  894. // There's no arbitrary limit to the number of backticks you
  895. // can use as delimters. If you need three consecutive backticks
  896. // in your code, use four for delimiters, etc.
  897. //
  898. // * You can use spaces to get literal backticks at the edges:
  899. //
  900. // ... type `` `bar` `` ...
  901. //
  902. // Turns to:
  903. //
  904. // ... type <code>`bar`</code> ...
  905. //
  906. /*
  907. text = text.replace(/
  908. (^|[^\\]) // Character before opening ` can't be a backslash
  909. (`+) // $2 = Opening run of `
  910. ( // $3 = The code block
  911. [^\r]*?
  912. [^`] // attacklab: work around lack of lookbehind
  913. )
  914. \2 // Matching closer
  915. (?!`)
  916. /gm, function(){...});
  917. */
  918. text = text.replace(/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/gm,
  919. function(wholeMatch,m1,m2,m3,m4) {
  920. var c = m3;
  921. c = c.replace(/^([ \t]*)/g,""); // leading whitespace
  922. c = c.replace(/[ \t]*$/g,""); // trailing whitespace
  923. c = _EncodeCode(c);
  924. return m1+"<code>"+c+"</code>";
  925. });
  926. return text;
  927. }
  928. var _EncodeCode = function(text) {
  929. //
  930. // Encode/escape certain characters inside Markdown code runs.
  931. // The point is that in code, these characters are literals,
  932. // and lose their special Markdown meanings.
  933. //
  934. // Encode all ampersands; HTML entities are not
  935. // entities within a Markdown code span.
  936. text = text.replace(/&/g,"&amp;");
  937. // Do the angle bracket song and dance:
  938. text = text.replace(/</g,"&lt;");
  939. text = text.replace(/>/g,"&gt;");
  940. // Now, escape characters that are magic in Markdown:
  941. text = escapeCharacters(text,"\*_{}[]\\",false);
  942. // jj the line above breaks this:
  943. //---
  944. //* Item
  945. // 1. Subitem
  946. // special char: *
  947. //---
  948. return text;
  949. }
  950. var _DoItalicsAndBold = function(text) {
  951. // <strong> must go first:
  952. text = text.replace(/(\*\*|__)(?=\S)([^\r]*?\S[*_]*)\1/g,
  953. "<strong>$2</strong>");
  954. text = text.replace(/(\*|_)(?=\S)([^\r]*?\S)\1/g,
  955. "<em>$2</em>");
  956. return text;
  957. }
  958. var _DoBlockQuotes = function(text) {
  959. /*
  960. text = text.replace(/
  961. ( // Wrap whole match in $1
  962. (
  963. ^[ \t]*>[ \t]? // '>' at the start of a line
  964. .+\n // rest of the first line
  965. (.+\n)* // subsequent consecutive lines
  966. \n* // blanks
  967. )+
  968. )
  969. /gm, function(){...});
  970. */
  971. text = text.replace(/((^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+)/gm,
  972. function(wholeMatch,m1) {
  973. var bq = m1;
  974. // attacklab: hack around Konqueror 3.5.4 bug:
  975. // "----------bug".replace(/^-/g,"") == "bug"
  976. bq = bq.replace(/^[ \t]*>[ \t]?/gm,"~0"); // trim one level of quoting
  977. // attacklab: clean up hack
  978. bq = bq.replace(/~0/g,"");
  979. bq = bq.replace(/^[ \t]+$/gm,""); // trim whitespace-only lines
  980. bq = _RunBlockGamut(bq); // recurse
  981. bq = bq.replace(/(^|\n)/g,"$1 ");
  982. // These leading spaces screw with <pre> content, so we need to fix that:
  983. bq = bq.replace(
  984. /(\s*<pre>[^\r]+?<\/pre>)/gm,
  985. function(wholeMatch,m1) {
  986. var pre = m1;
  987. // attacklab: hack around Konqueror 3.5.4 bug:
  988. pre = pre.replace(/^ /mg,"~0");
  989. pre = pre.replace(/~0/g,"");
  990. return pre;
  991. });
  992. return hashBlock("<blockquote>\n" + bq + "\n</blockquote>");
  993. });
  994. return text;
  995. }
  996. var _FormParagraphs = function(text) {
  997. //
  998. // Params:
  999. // $text - string to process with html <p> tags
  1000. //
  1001. // Strip leading and trailing lines:
  1002. text = text.replace(/^\n+/g,"");
  1003. text = text.replace(/\n+$/g,"");
  1004. var grafs = text.split(/\n{2,}/g);
  1005. var grafsOut = [];
  1006. //
  1007. // Wrap <p> tags.
  1008. //
  1009. var end = grafs.length;
  1010. for (var i=0; i<end; i++) {
  1011. var str = grafs[i];
  1012. // if this is an HTML marker, copy it
  1013. if (str.search(/~K(\d+)K/g) >= 0) {
  1014. grafsOut.push(str);
  1015. }
  1016. else if (str.search(/\S/) >= 0) {
  1017. str = _RunSpanGamut(str);
  1018. str = str.replace(/^([ \t]*)/g,"<p>");
  1019. str += "</p>"
  1020. grafsOut.push(str);
  1021. }
  1022. }
  1023. //
  1024. // Unhashify HTML blocks
  1025. //
  1026. end = grafsOut.length;
  1027. for (var i=0; i<end; i++) {
  1028. // if this is a marker for an html block...
  1029. while (grafsOut[i].search(/~K(\d+)K/) >= 0) {
  1030. var blockText = g_html_blocks[RegExp.$1];
  1031. blockText = blockText.replace(/\$/g,"$$$$"); // Escape any dollar signs
  1032. grafsOut[i] = grafsOut[i].replace(/~K\d+K/,blockText);
  1033. }
  1034. }
  1035. return grafsOut.join("\n\n");
  1036. }
  1037. var _EncodeAmpsAndAngles = function(text) {
  1038. // Smart processing for ampersands and angle brackets that need to be encoded.
  1039. // Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
  1040. // http://bumppo.net/projects/amputator/
  1041. text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g,"&amp;");
  1042. // Encode naked <'s
  1043. text = text.replace(/<(?![a-z\/?\$!])/gi,"&lt;");
  1044. return text;
  1045. }
  1046. var _EncodeBackslashEscapes = function(text) {
  1047. //
  1048. // Parameter: String.
  1049. // Returns: The string, with after processing the following backslash
  1050. // escape sequences.
  1051. //
  1052. // attacklab: The polite way to do this is with the new
  1053. // escapeCharacters() function:
  1054. //
  1055. // text = escapeCharacters(text,"\\",true);
  1056. // text = escapeCharacters(text,"`*_{}[]()>#+-.!",true);
  1057. //
  1058. // ...but we're sidestepping its use of the (slow) RegExp constructor
  1059. // as an optimization for Firefox. This function gets called a LOT.
  1060. text = text.replace(/\\(\\)/g,escapeCharacters_callback);
  1061. text = text.replace(/\\([`*_{}\[\]()>#+-.!])/g,escapeCharacters_callback);
  1062. return text;
  1063. }
  1064. var _DoAutoLinks = function(text) {
  1065. text = text.replace(/<((https?|ftp|dict):[^'">\s]+)>/gi,"<a href=\"$1\">$1</a>");
  1066. // Email addresses: <address@domain.foo>
  1067. /*
  1068. text = text.replace(/
  1069. <
  1070. (?:mailto:)?
  1071. (
  1072. [-.\w]+
  1073. \@
  1074. [-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+
  1075. )
  1076. >
  1077. /gi, _DoAutoLinks_callback());
  1078. */
  1079. text = text.replace(/<(?:mailto:)?([-.\w]+\@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi,
  1080. function(wholeMatch,m1) {
  1081. return _EncodeEmailAddress( _UnescapeSpecialChars(m1) );
  1082. }
  1083. );
  1084. return text;
  1085. }
  1086. var _EncodeEmailAddress = function(addr) {
  1087. //
  1088. // Input: an email address, e.g. "foo@example.com"
  1089. //
  1090. // Output: the email address as a mailto link, with each character
  1091. // of the address encoded as either a decimal or hex entity, in
  1092. // the hopes of foiling most address harvesting spam bots. E.g.:
  1093. //
  1094. // <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101;
  1095. // x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111;
  1096. // &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a>
  1097. //
  1098. // Based on a filter by Matthew Wickline, posted to the BBEdit-Talk
  1099. // mailing list: <http://tinyurl.com/yu7ue>
  1100. //
  1101. var encode = [
  1102. function(ch){return "&#"+ch.charCodeAt(0)+";";},
  1103. function(ch){return "&#x"+ch.charCodeAt(0).toString(16)+";";},
  1104. function(ch){return ch;}
  1105. ];
  1106. addr = "mailto:" + addr;
  1107. addr = addr.replace(/./g, function(ch) {
  1108. if (ch == "@") {
  1109. // this *must* be encoded. I insist.
  1110. ch = encode[Math.floor(Math.random()*2)](ch);
  1111. } else if (ch !=":") {
  1112. // leave ':' alone (to spot mailto: later)
  1113. var r = Math.random();
  1114. // roughly 10% raw, 45% hex, 45% dec
  1115. ch = (
  1116. r > .9 ? encode[2](ch) :
  1117. r > .45 ? encode[1](ch) :
  1118. encode[0](ch)
  1119. );
  1120. }
  1121. return ch;
  1122. });
  1123. addr = "<a href=\"" + addr + "\">" + addr + "</a>";
  1124. addr = addr.replace(/">.+:/g,"\">"); // strip the mailto: from the visible part
  1125. return addr;
  1126. }
  1127. var _UnescapeSpecialChars = function(text) {
  1128. //
  1129. // Swap back in all the special characters we've hidden.
  1130. //
  1131. text = text.replace(/~E(\d+)E/g,
  1132. function(wholeMatch,m1) {
  1133. var charCodeToReplace = parseInt(m1);
  1134. return String.fromCharCode(charCodeToReplace);
  1135. }
  1136. );
  1137. return text;
  1138. }
  1139. var _Outdent = function(text) {
  1140. //
  1141. // Remove one level of line-leading tabs or spaces
  1142. //
  1143. // attacklab: hack around Konqueror 3.5.4 bug:
  1144. // "----------bug".replace(/^-/g,"") == "bug"
  1145. text = text.replace(/^(\t|[ ]{1,4})/gm,"~0"); // attacklab: g_tab_width
  1146. // attacklab: clean up hack
  1147. text = text.replace(/~0/g,"")
  1148. return text;
  1149. }
  1150. var _Detab = function(text) {
  1151. // attacklab: Detab's completely rewritten for speed.
  1152. // In perl we could fix it by anchoring the regexp with \G.
  1153. // In javascript we're less fortunate.
  1154. // expand first n-1 tabs
  1155. text = text.replace(/\t(?=\t)/g," "); // attacklab: g_tab_width
  1156. // replace the nth with two sentinels
  1157. text = text.replace(/\t/g,"~A~B");
  1158. // use the sentinel to anchor our regex so it doesn't explode
  1159. text = text.replace(/~B(.+?)~A/g,
  1160. function(wholeMatch,m1,m2) {
  1161. var leadingText = m1;
  1162. var numSpaces = 4 - leadingText.length % 4; // attacklab: g_tab_width
  1163. // there *must* be a better way to do this:
  1164. for (var i=0; i<numSpaces; i++) leadingText+=" ";
  1165. return leadingText;
  1166. }
  1167. );
  1168. // clean up sentinels
  1169. text = text.replace(/~A/g," "); // attacklab: g_tab_width
  1170. text = text.replace(/~B/g,"");
  1171. return text;
  1172. }
  1173. //
  1174. // attacklab: Utility functions
  1175. //
  1176. var escapeCharacters = function(text, charsToEscape, afterBackslash) {
  1177. // First we have to escape the escape characters so that
  1178. // we can build a character class out of them
  1179. var regexString = "([" + charsToEscape.replace(/([\[\]\\])/g,"\\$1") + "])";
  1180. if (afterBackslash) {
  1181. regexString = "\\\\" + regexString;
  1182. }
  1183. var regex = new RegExp(regexString,"g");
  1184. text = text.replace(regex,escapeCharacters_callback);
  1185. return text;
  1186. }
  1187. var escapeCharacters_callback = function(wholeMatch,m1) {
  1188. var charCodeToEscape = m1.charCodeAt(0);
  1189. return "~E"+charCodeToEscape+"E";
  1190. }
  1191. } // end of Showdown.converter
  1192. // export
  1193. if (typeof module !== 'undefined') module.exports = Showdown;
  1194. // stolen from AMD branch of underscore
  1195. // AMD define happens at the end for compatibility with AMD loaders
  1196. // that don't enforce next-turn semantics on modules.
  1197. if (typeof define === 'function' && define.amd) {
  1198. define('showdown', function() {
  1199. return Showdown;
  1200. });
  1201. }