showdown.js 46 KB

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