showdown.js 46 KB

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