showdown.js 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315
  1. ;/*! showdown 14-07-2015 */
  2. (function(){
  3. /**
  4. * Created by Tivie on 13-07-2015.
  5. */
  6. function getDefaultOpts(simple) {
  7. 'use strict';
  8. var defaultOptions = {
  9. omitExtraWLInCodeBlocks: {
  10. default: false,
  11. describe: 'Omit the default extra whiteline added to code blocks',
  12. type: 'boolean'
  13. },
  14. noHeaderId: {
  15. default: false,
  16. describe: 'Turn on/off generated header id',
  17. type: 'boolean'
  18. },
  19. prefixHeaderId: {
  20. default: false,
  21. describe: 'Specify a prefix to generated header ids',
  22. type: 'string'
  23. },
  24. headerLevelStart: {
  25. default: false,
  26. describe: 'The header blocks level start',
  27. type: 'integer'
  28. },
  29. parseImgDimensions: {
  30. default: false,
  31. describe: 'Turn on/off image dimension parsing',
  32. type: 'boolean'
  33. },
  34. simplifiedAutoLink: {
  35. default: false,
  36. describe: 'Turn on/off GFM autolink style',
  37. type: 'boolean'
  38. },
  39. literalMidWordUnderscores: {
  40. default: false,
  41. describe: 'Parse midword underscores as literal underscores',
  42. type: 'boolean'
  43. },
  44. strikethrough: {
  45. default: false,
  46. describe: 'Turn on/off strikethrough support',
  47. type: 'boolean'
  48. },
  49. tables: {
  50. default: false,
  51. describe: 'Turn on/off tables support',
  52. type: 'boolean'
  53. },
  54. tablesHeaderId: {
  55. default: false,
  56. describe: 'Add an id to table headers',
  57. type: 'boolean'
  58. },
  59. ghCodeBlocks: {
  60. default: true,
  61. describe: 'Turn on/off GFM fenced code blocks support',
  62. type: 'boolean'
  63. },
  64. tasklists: {
  65. default: false,
  66. describe: 'Turn on/off GFM tasklist support',
  67. type: 'boolean'
  68. },
  69. smoothLivePreview: {
  70. default: false,
  71. describe: 'Prevents weird effects in live previews due to incomplete input',
  72. type: 'boolean'
  73. }
  74. };
  75. if (simple === false) {
  76. return JSON.parse(JSON.stringify(defaultOptions));
  77. }
  78. var ret = {};
  79. for (var opt in defaultOptions) {
  80. if (defaultOptions.hasOwnProperty(opt)) {
  81. ret[opt] = defaultOptions[opt].default;
  82. }
  83. }
  84. return ret;
  85. }
  86. /**
  87. * Created by Tivie on 06-01-2015.
  88. */
  89. // Private properties
  90. var showdown = {},
  91. parsers = {},
  92. extensions = {},
  93. globalOptions = getDefaultOpts(true),
  94. flavor = {
  95. github: {
  96. omitExtraWLInCodeBlocks: true,
  97. prefixHeaderId: 'user-content-',
  98. simplifiedAutoLink: true,
  99. literalMidWordUnderscores: true,
  100. strikethrough: true,
  101. tables: true,
  102. tablesHeaderId: true,
  103. ghCodeBlocks: true,
  104. tasklists: true
  105. },
  106. vanilla: getDefaultOpts(true)
  107. };
  108. /**
  109. * helper namespace
  110. * @type {{}}
  111. */
  112. showdown.helper = {};
  113. /**
  114. * TODO LEGACY SUPPORT CODE
  115. * @type {{}}
  116. */
  117. showdown.extensions = {};
  118. /**
  119. * Set a global option
  120. * @static
  121. * @param {string} key
  122. * @param {*} value
  123. * @returns {showdown}
  124. */
  125. showdown.setOption = function (key, value) {
  126. 'use strict';
  127. globalOptions[key] = value;
  128. return this;
  129. };
  130. /**
  131. * Get a global option
  132. * @static
  133. * @param {string} key
  134. * @returns {*}
  135. */
  136. showdown.getOption = function (key) {
  137. 'use strict';
  138. return globalOptions[key];
  139. };
  140. /**
  141. * Get the global options
  142. * @static
  143. * @returns {{}}
  144. */
  145. showdown.getOptions = function () {
  146. 'use strict';
  147. return globalOptions;
  148. };
  149. /**
  150. * Reset global options to the default values
  151. * @static
  152. */
  153. showdown.resetOptions = function () {
  154. 'use strict';
  155. globalOptions = getDefaultOpts(true);
  156. };
  157. /**
  158. * Set the flavor showdown should use as default
  159. * @param {string} name
  160. */
  161. showdown.setFlavor = function (name) {
  162. 'use strict';
  163. if (flavor.hasOwnProperty(name)) {
  164. var preset = flavor[name];
  165. for (var option in preset) {
  166. if (preset.hasOwnProperty(option)) {
  167. globalOptions[option] = preset[option];
  168. }
  169. }
  170. }
  171. };
  172. /**
  173. * Get the default options
  174. * @static
  175. * @param {boolean} [simple=true]
  176. * @returns {{}}
  177. */
  178. showdown.getDefaultOptions = function (simple) {
  179. 'use strict';
  180. return getDefaultOpts(simple);
  181. };
  182. /**
  183. * Get or set a subParser
  184. *
  185. * subParser(name) - Get a registered subParser
  186. * subParser(name, func) - Register a subParser
  187. * @static
  188. * @param {string} name
  189. * @param {function} [func]
  190. * @returns {*}
  191. */
  192. showdown.subParser = function (name, func) {
  193. 'use strict';
  194. if (showdown.helper.isString(name)) {
  195. if (typeof func !== 'undefined') {
  196. parsers[name] = func;
  197. } else {
  198. if (parsers.hasOwnProperty(name)) {
  199. return parsers[name];
  200. } else {
  201. throw Error('SubParser named ' + name + ' not registered!');
  202. }
  203. }
  204. }
  205. };
  206. /**
  207. * Gets or registers an extension
  208. * @static
  209. * @param {string} name
  210. * @param {object|function=} ext
  211. * @returns {*}
  212. */
  213. showdown.extension = function (name, ext) {
  214. 'use strict';
  215. if (!showdown.helper.isString(name)) {
  216. throw Error('Extension \'name\' must be a string');
  217. }
  218. name = showdown.helper.stdExtName(name);
  219. // Getter
  220. if (showdown.helper.isUndefined(ext)) {
  221. if (!extensions.hasOwnProperty(name)) {
  222. throw Error('Extension named ' + name + ' is not registered!');
  223. }
  224. return extensions[name];
  225. // Setter
  226. } else {
  227. // Expand extension if it's wrapped in a function
  228. if (typeof ext === 'function') {
  229. ext = ext();
  230. }
  231. // Ensure extension is an array
  232. if (!showdown.helper.isArray(ext)) {
  233. ext = [ext];
  234. }
  235. var validExtension = validate(ext, name);
  236. if (validExtension.valid) {
  237. extensions[name] = ext;
  238. } else {
  239. throw Error(validExtension.error);
  240. }
  241. }
  242. };
  243. /**
  244. * Gets all extensions registered
  245. * @returns {{}}
  246. */
  247. showdown.getAllExtensions = function () {
  248. 'use strict';
  249. return extensions;
  250. };
  251. /**
  252. * Remove an extension
  253. * @param {string} name
  254. */
  255. showdown.removeExtension = function (name) {
  256. 'use strict';
  257. delete extensions[name];
  258. };
  259. /**
  260. * Removes all extensions
  261. */
  262. showdown.resetExtensions = function () {
  263. 'use strict';
  264. extensions = {};
  265. };
  266. /**
  267. * Validate extension
  268. * @param {array} extension
  269. * @param {string} name
  270. * @returns {{valid: boolean, error: string}}
  271. */
  272. function validate(extension, name) {
  273. 'use strict';
  274. var errMsg = (name) ? 'Error in ' + name + ' extension->' : 'Error in unnamed extension',
  275. ret = {
  276. valid: true,
  277. error: ''
  278. };
  279. if (!showdown.helper.isArray(extension)) {
  280. extension = [extension];
  281. }
  282. for (var i = 0; i < extension.length; ++i) {
  283. var baseMsg = errMsg + ' sub-extension ' + i + ': ',
  284. ext = extension[i];
  285. if (typeof ext !== 'object') {
  286. ret.valid = false;
  287. ret.error = baseMsg + 'must be an object, but ' + typeof ext + ' given';
  288. return ret;
  289. }
  290. if (!showdown.helper.isString(ext.type)) {
  291. ret.valid = false;
  292. ret.error = baseMsg + 'property "type" must be a string, but ' + typeof ext.type + ' given';
  293. return ret;
  294. }
  295. var type = ext.type = ext.type.toLowerCase();
  296. // normalize extension type
  297. if (type === 'language') {
  298. type = ext.type = 'lang';
  299. }
  300. if (type === 'html') {
  301. type = ext.type = 'output';
  302. }
  303. if (type !== 'lang' && type !== 'output') {
  304. ret.valid = false;
  305. ret.error = baseMsg + 'type ' + type + ' is not recognized. Valid values: "lang" or "output"';
  306. return ret;
  307. }
  308. if (ext.filter) {
  309. if (typeof ext.filter !== 'function') {
  310. ret.valid = false;
  311. ret.error = baseMsg + '"filter" must be a function, but ' + typeof ext.filter + ' given';
  312. return ret;
  313. }
  314. } else if (ext.regex) {
  315. if (showdown.helper.isString(ext.regex)) {
  316. ext.regex = new RegExp(ext.regex, 'g');
  317. }
  318. if (!ext.regex instanceof RegExp) {
  319. ret.valid = false;
  320. ret.error = baseMsg + '"regex" property must either be a string or a RegExp object, but ' +
  321. typeof ext.regex + ' given';
  322. return ret;
  323. }
  324. if (showdown.helper.isUndefined(ext.replace)) {
  325. ret.valid = false;
  326. ret.error = baseMsg + '"regex" extensions must implement a replace string or function';
  327. return ret;
  328. }
  329. } else {
  330. ret.valid = false;
  331. ret.error = baseMsg + 'extensions must define either a "regex" property or a "filter" method';
  332. return ret;
  333. }
  334. if (showdown.helper.isUndefined(ext.filter) && showdown.helper.isUndefined(ext.regex)) {
  335. ret.valid = false;
  336. ret.error = baseMsg + 'output extensions must define a filter property';
  337. return ret;
  338. }
  339. }
  340. return ret;
  341. }
  342. /**
  343. * Validate extension
  344. * @param {object} ext
  345. * @returns {boolean}
  346. */
  347. showdown.validateExtension = function (ext) {
  348. 'use strict';
  349. var validateExtension = validate(ext, null);
  350. if (!validateExtension.valid) {
  351. console.warn(validateExtension.error);
  352. return false;
  353. }
  354. return true;
  355. };
  356. /**
  357. * showdownjs helper functions
  358. */
  359. if (!showdown.hasOwnProperty('helper')) {
  360. showdown.helper = {};
  361. }
  362. /**
  363. * Check if var is string
  364. * @static
  365. * @param {string} a
  366. * @returns {boolean}
  367. */
  368. showdown.helper.isString = function isString(a) {
  369. 'use strict';
  370. return (typeof a === 'string' || a instanceof String);
  371. };
  372. /**
  373. * ForEach helper function
  374. * @static
  375. * @param {*} obj
  376. * @param {function} callback
  377. */
  378. showdown.helper.forEach = function forEach(obj, callback) {
  379. 'use strict';
  380. if (typeof obj.forEach === 'function') {
  381. obj.forEach(callback);
  382. } else {
  383. for (var i = 0; i < obj.length; i++) {
  384. callback(obj[i], i, obj);
  385. }
  386. }
  387. };
  388. /**
  389. * isArray helper function
  390. * @static
  391. * @param {*} a
  392. * @returns {boolean}
  393. */
  394. showdown.helper.isArray = function isArray(a) {
  395. 'use strict';
  396. return a.constructor === Array;
  397. };
  398. /**
  399. * Check if value is undefined
  400. * @static
  401. * @param {*} value The value to check.
  402. * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
  403. */
  404. showdown.helper.isUndefined = function isUndefined(value) {
  405. 'use strict';
  406. return typeof value === 'undefined';
  407. };
  408. /**
  409. * Standardidize extension name
  410. * @static
  411. * @param {string} s extension name
  412. * @returns {string}
  413. */
  414. showdown.helper.stdExtName = function (s) {
  415. 'use strict';
  416. return s.replace(/[_-]||\s/g, '').toLowerCase();
  417. };
  418. function escapeCharactersCallback(wholeMatch, m1) {
  419. 'use strict';
  420. var charCodeToEscape = m1.charCodeAt(0);
  421. return '~E' + charCodeToEscape + 'E';
  422. }
  423. /**
  424. * Callback used to escape characters when passing through String.replace
  425. * @static
  426. * @param {string} wholeMatch
  427. * @param {string} m1
  428. * @returns {string}
  429. */
  430. showdown.helper.escapeCharactersCallback = escapeCharactersCallback;
  431. /**
  432. * Escape characters in a string
  433. * @static
  434. * @param {string} text
  435. * @param {string} charsToEscape
  436. * @param {boolean} afterBackslash
  437. * @returns {XML|string|void|*}
  438. */
  439. showdown.helper.escapeCharacters = function escapeCharacters(text, charsToEscape, afterBackslash) {
  440. 'use strict';
  441. // First we have to escape the escape characters so that
  442. // we can build a character class out of them
  443. var regexString = '([' + charsToEscape.replace(/([\[\]\\])/g, '\\$1') + '])';
  444. if (afterBackslash) {
  445. regexString = '\\\\' + regexString;
  446. }
  447. var regex = new RegExp(regexString, 'g');
  448. text = text.replace(regex, escapeCharactersCallback);
  449. return text;
  450. };
  451. /**
  452. * POLYFILLS
  453. */
  454. if (showdown.helper.isUndefined(console)) {
  455. console = {
  456. warn: function (msg) {
  457. 'use strict';
  458. alert(msg);
  459. },
  460. log: function (msg) {
  461. 'use strict';
  462. alert(msg);
  463. }
  464. };
  465. }
  466. /**
  467. * Created by Estevao on 31-05-2015.
  468. */
  469. /**
  470. * Showdown Converter class
  471. * @class
  472. * @param {object} [converterOptions]
  473. * @returns {
  474. * {makeHtml: Function},
  475. * {setOption: Function},
  476. * {getOption: Function},
  477. * {getOptions: Function}
  478. * }
  479. */
  480. showdown.Converter = function (converterOptions) {
  481. 'use strict';
  482. var
  483. /**
  484. * Options used by this converter
  485. * @private
  486. * @type {{}}
  487. */
  488. options = {},
  489. /**
  490. * Language extensions used by this converter
  491. * @private
  492. * @type {Array}
  493. */
  494. langExtensions = [],
  495. /**
  496. * Output modifiers extensions used by this converter
  497. * @private
  498. * @type {Array}
  499. */
  500. outputModifiers = [],
  501. /**
  502. * The parser Order
  503. * @private
  504. * @type {string[]}
  505. */
  506. parserOrder = [
  507. 'githubCodeBlocks',
  508. 'hashHTMLBlocks',
  509. 'stripLinkDefinitions',
  510. 'blockGamut',
  511. 'unescapeSpecialChars'
  512. ];
  513. _constructor();
  514. /**
  515. * Converter constructor
  516. * @private
  517. */
  518. function _constructor() {
  519. converterOptions = converterOptions || {};
  520. for (var gOpt in globalOptions) {
  521. if (globalOptions.hasOwnProperty(gOpt)) {
  522. options[gOpt] = globalOptions[gOpt];
  523. }
  524. }
  525. // Merge options
  526. if (typeof converterOptions === 'object') {
  527. for (var opt in converterOptions) {
  528. if (converterOptions.hasOwnProperty(opt)) {
  529. options[opt] = converterOptions[opt];
  530. }
  531. }
  532. } else {
  533. throw Error('Converter expects the passed parameter to be an object, but ' + typeof converterOptions +
  534. ' was passed instead.');
  535. }
  536. if (options.extensions) {
  537. showdown.helper.forEach(options.extensions, _parseExtension);
  538. }
  539. }
  540. /**
  541. * Parse extension
  542. * @param {*} ext
  543. * @param {string} [name='']
  544. * @private
  545. */
  546. function _parseExtension(ext, name) {
  547. name = name || null;
  548. // If it's a string, the extension was previously loaded
  549. if (showdown.helper.isString(ext)) {
  550. ext = showdown.helper.stdExtName(ext);
  551. name = ext;
  552. // LEGACY_SUPPORT CODE
  553. if (showdown.extensions[ext]) {
  554. console.warn('DEPRECATION WARNING: ' + ext + ' is an old extension that uses a deprecated loading method.' +
  555. 'Please inform the developer that the extension should be updated!');
  556. legacyExtensionLoading(showdown.extensions[ext], ext);
  557. return;
  558. // END LEGACY SUPPORT CODE
  559. } else if (!showdown.helper.isUndefined(extensions[ext])) {
  560. ext = extensions[ext];
  561. } else {
  562. throw Error('Extension "' + ext + '" could not be loaded. It was either not found or is not a valid extension.');
  563. }
  564. }
  565. if (typeof ext === 'function') {
  566. ext = ext();
  567. }
  568. if (!showdown.helper.isArray(ext)) {
  569. ext = [ext];
  570. }
  571. var validExt = validate(ext, name);
  572. if (!validExt.valid) {
  573. throw Error(validExt.error);
  574. }
  575. for (var i = 0; i < ext.length; ++i) {
  576. switch (ext[i].type) {
  577. case 'lang':
  578. langExtensions.push(ext[i]);
  579. break;
  580. case 'output':
  581. outputModifiers.push(ext[i]);
  582. break;
  583. default:
  584. // should never reach here
  585. throw Error('Extension loader error: Type unrecognized!!!');
  586. }
  587. }
  588. }
  589. /**
  590. * LEGACY_SUPPORT
  591. * @param {*} ext
  592. * @param {string} name
  593. */
  594. function legacyExtensionLoading(ext, name) {
  595. if (typeof ext === 'function') {
  596. ext = ext(new showdown.Converter());
  597. }
  598. if (!showdown.helper.isArray(ext)) {
  599. ext = [ext];
  600. }
  601. var valid = validate(ext, name);
  602. if (!valid.valid) {
  603. throw Error(valid.error);
  604. }
  605. for (var i = 0; i < ext.length; ++i) {
  606. switch (ext[i].type) {
  607. case 'lang':
  608. langExtensions.push(ext[i]);
  609. break;
  610. case 'output':
  611. outputModifiers.push(ext[i]);
  612. break;
  613. default:// should never reach here
  614. throw Error('Extension loader error: Type unrecognized!!!');
  615. }
  616. }
  617. }
  618. /**
  619. * Converts a markdown string into HTML
  620. * @param {string} text
  621. * @returns {*}
  622. */
  623. this.makeHtml = function (text) {
  624. //check if text is not falsy
  625. if (!text) {
  626. return text;
  627. }
  628. var globals = {
  629. gHtmlBlocks: [],
  630. gUrls: {},
  631. gTitles: {},
  632. gDimensions: {},
  633. gListLevel: 0,
  634. hashLinkCounts: {},
  635. langExtensions: langExtensions,
  636. outputModifiers: outputModifiers,
  637. converter: this
  638. };
  639. // attacklab: Replace ~ with ~T
  640. // This lets us use tilde as an escape char to avoid md5 hashes
  641. // The choice of character is arbitrary; anything that isn't
  642. // magic in Markdown will work.
  643. text = text.replace(/~/g, '~T');
  644. // attacklab: Replace $ with ~D
  645. // RegExp interprets $ as a special character
  646. // when it's in a replacement string
  647. text = text.replace(/\$/g, '~D');
  648. // Standardize line endings
  649. text = text.replace(/\r\n/g, '\n'); // DOS to Unix
  650. text = text.replace(/\r/g, '\n'); // Mac to Unix
  651. // Make sure text begins and ends with a couple of newlines:
  652. text = '\n\n' + text + '\n\n';
  653. // detab
  654. text = showdown.subParser('detab')(text, options, globals);
  655. // stripBlankLines
  656. text = showdown.subParser('stripBlankLines')(text, options, globals);
  657. //run languageExtensions
  658. showdown.helper.forEach(langExtensions, function (ext) {
  659. text = showdown.subParser('runExtension')(ext, text, options, globals);
  660. });
  661. // Run all registered parsers
  662. for (var i = 0; i < parserOrder.length; ++i) {
  663. var name = parserOrder[i];
  664. text = parsers[name](text, options, globals);
  665. }
  666. // attacklab: Restore dollar signs
  667. text = text.replace(/~D/g, '$$');
  668. // attacklab: Restore tildes
  669. text = text.replace(/~T/g, '~');
  670. // Run output modifiers
  671. showdown.helper.forEach(outputModifiers, function (ext) {
  672. text = showdown.subParser('runExtension')(ext, text, options, globals);
  673. });
  674. return text;
  675. };
  676. /**
  677. * Set an option of this Converter instance
  678. * @param {string} key
  679. * @param {*} value
  680. */
  681. this.setOption = function (key, value) {
  682. options[key] = value;
  683. };
  684. /**
  685. * Get the option of this Converter instance
  686. * @param {string} key
  687. * @returns {*}
  688. */
  689. this.getOption = function (key) {
  690. return options[key];
  691. };
  692. /**
  693. * Get the options of this Converter instance
  694. * @returns {{}}
  695. */
  696. this.getOptions = function () {
  697. return options;
  698. };
  699. /**
  700. * Add extension to THIS converter
  701. * @param {{}} extension
  702. * @param {string} [name=null]
  703. */
  704. this.addExtension = function (extension, name) {
  705. name = name || null;
  706. _parseExtension(extension, name);
  707. };
  708. /**
  709. * Use a global registered extension with THIS converter
  710. * @param {string} extensionName Name of the previously registered extension
  711. */
  712. this.useExtension = function (extensionName) {
  713. _parseExtension(extensionName);
  714. };
  715. /**
  716. * Set the flavor THIS converter should use
  717. * @param {string} name
  718. */
  719. this.setFlavor = function (name) {
  720. if (flavor.hasOwnProperty(name)) {
  721. var preset = flavor[name];
  722. for (var option in preset) {
  723. if (preset.hasOwnProperty(option)) {
  724. options[option] = preset[option];
  725. }
  726. }
  727. }
  728. };
  729. /**
  730. * Remove an extension from THIS converter.
  731. * Note: This is a costly operation. It's better to initialize a new converter
  732. * and specify the extensions you wish to use
  733. * @param {Array} extension
  734. */
  735. this.removeExtension = function (extension) {
  736. if (!showdown.helper.isArray(extension)) {
  737. extension = [extension];
  738. }
  739. for (var a = 0; a < extension.length; ++a) {
  740. var ext = extension[a];
  741. for (var i = 0; i < langExtensions.length; ++i) {
  742. if (langExtensions[i] === ext) {
  743. langExtensions[i].splice(i, 1);
  744. }
  745. }
  746. for (var ii = 0; ii < outputModifiers.length; ++i) {
  747. if (outputModifiers[ii] === ext) {
  748. outputModifiers[ii].splice(i, 1);
  749. }
  750. }
  751. }
  752. };
  753. /**
  754. * Get all extension of THIS converter
  755. * @returns {{language: Array, output: Array}}
  756. */
  757. this.getAllExtensions = function () {
  758. return {
  759. language: langExtensions,
  760. output: outputModifiers
  761. };
  762. };
  763. };
  764. /**
  765. * Turn Markdown link shortcuts into XHTML <a> tags.
  766. */
  767. showdown.subParser('anchors', function (text, config, globals) {
  768. 'use strict';
  769. var writeAnchorTag = function (wholeMatch, m1, m2, m3, m4, m5, m6, m7) {
  770. if (showdown.helper.isUndefined(m7)) {
  771. m7 = '';
  772. }
  773. wholeMatch = m1;
  774. var linkText = m2,
  775. linkId = m3.toLowerCase(),
  776. url = m4,
  777. title = m7;
  778. if (!url) {
  779. if (!linkId) {
  780. // lower-case and turn embedded newlines into spaces
  781. linkId = linkText.toLowerCase().replace(/ ?\n/g, ' ');
  782. }
  783. url = '#' + linkId;
  784. if (!showdown.helper.isUndefined(globals.gUrls[linkId])) {
  785. url = globals.gUrls[linkId];
  786. if (!showdown.helper.isUndefined(globals.gTitles[linkId])) {
  787. title = globals.gTitles[linkId];
  788. }
  789. } else {
  790. if (wholeMatch.search(/\(\s*\)$/m) > -1) {
  791. // Special case for explicit empty url
  792. url = '';
  793. } else {
  794. return wholeMatch;
  795. }
  796. }
  797. }
  798. url = showdown.helper.escapeCharacters(url, '*_', false);
  799. var result = '<a href="' + url + '"';
  800. if (title !== '' && title !== null) {
  801. title = title.replace(/"/g, '&quot;');
  802. title = showdown.helper.escapeCharacters(title, '*_', false);
  803. result += ' title="' + title + '"';
  804. }
  805. result += '>' + linkText + '</a>';
  806. return result;
  807. };
  808. // First, handle reference-style links: [link text] [id]
  809. /*
  810. text = text.replace(/
  811. ( // wrap whole match in $1
  812. \[
  813. (
  814. (?:
  815. \[[^\]]*\] // allow brackets nested one level
  816. |
  817. [^\[] // or anything else
  818. )*
  819. )
  820. \]
  821. [ ]? // one optional space
  822. (?:\n[ ]*)? // one optional newline followed by spaces
  823. \[
  824. (.*?) // id = $3
  825. \]
  826. )()()()() // pad remaining backreferences
  827. /g,_DoAnchors_callback);
  828. */
  829. text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g, writeAnchorTag);
  830. //
  831. // Next, inline-style links: [link text](url "optional title")
  832. //
  833. /*
  834. text = text.replace(/
  835. ( // wrap whole match in $1
  836. \[
  837. (
  838. (?:
  839. \[[^\]]*\] // allow brackets nested one level
  840. |
  841. [^\[\]] // or anything else
  842. )
  843. )
  844. \]
  845. \( // literal paren
  846. [ \t]*
  847. () // no id, so leave $3 empty
  848. <?(.*?)>? // href = $4
  849. [ \t]*
  850. ( // $5
  851. (['"]) // quote char = $6
  852. (.*?) // Title = $7
  853. \6 // matching quote
  854. [ \t]* // ignore any spaces/tabs between closing quote and )
  855. )? // title is optional
  856. \)
  857. )
  858. /g,writeAnchorTag);
  859. */
  860. text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\]\([ \t]*()<?(.*?(?:\(.*?\).*?)?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,
  861. writeAnchorTag);
  862. //
  863. // Last, handle reference-style shortcuts: [link text]
  864. // These must come last in case you've also got [link test][1]
  865. // or [link test](/foo)
  866. //
  867. /*
  868. text = text.replace(/
  869. ( // wrap whole match in $1
  870. \[
  871. ([^\[\]]+) // link text = $2; can't contain '[' or ']'
  872. \]
  873. )()()()()() // pad rest of backreferences
  874. /g, writeAnchorTag);
  875. */
  876. text = text.replace(/(\[([^\[\]]+)\])()()()()()/g, writeAnchorTag);
  877. return text;
  878. });
  879. showdown.subParser('autoLinks', function (text, options) {
  880. 'use strict';
  881. //simpleURLRegex = /\b(((https?|ftp|dict):\/\/|www\.)[-.+~:?#@!$&'()*,;=[\]\w]+)\b/gi,
  882. var simpleURLRegex = /\b(((https?|ftp|dict):\/\/|www\.)[^'">\s]+\.[^'">\s]+)(?=\s|$)(?!["<>])/gi,
  883. delimUrlRegex = /<(((https?|ftp|dict):\/\/|www\.)[^'">\s]+)>/gi,
  884. simpleMailRegex = /\b(?:mailto:)?([-.\w]+@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)\b/gi,
  885. delimMailRegex = /<(?:mailto:)?([-.\w]+@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi;
  886. text = text.replace(delimUrlRegex, '<a href=\"$1\">$1</a>');
  887. text = text.replace(delimMailRegex, replaceMail);
  888. //simpleURLRegex = /\b(((https?|ftp|dict):\/\/|www\.)[-.+~:?#@!$&'()*,;=[\]\w]+)\b/gi,
  889. // Email addresses: <address@domain.foo>
  890. if (options.simplifiedAutoLink) {
  891. text = text.replace(simpleURLRegex, '<a href=\"$1\">$1</a>');
  892. text = text.replace(simpleMailRegex, '<a href=\"$1\">$1</a>');
  893. }
  894. function replaceMail(wholeMatch, m1) {
  895. var unescapedStr = showdown.subParser('unescapeSpecialChars')(m1);
  896. return showdown.subParser('encodeEmailAddress')(unescapedStr);
  897. }
  898. return text;
  899. });
  900. /**
  901. * These are all the transformations that form block-level
  902. * tags like paragraphs, headers, and list items.
  903. */
  904. showdown.subParser('blockGamut', function (text, options, globals) {
  905. 'use strict';
  906. text = showdown.subParser('headers')(text, options, globals);
  907. // Do Horizontal Rules:
  908. var key = showdown.subParser('hashBlock')('<hr />', options, globals);
  909. text = text.replace(/^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$/gm, key);
  910. text = text.replace(/^[ ]{0,2}([ ]?\-[ ]?){3,}[ \t]*$/gm, key);
  911. text = text.replace(/^[ ]{0,2}([ ]?_[ ]?){3,}[ \t]*$/gm, key);
  912. text = showdown.subParser('tables')(text, options, globals);
  913. text = showdown.subParser('lists')(text, options, globals);
  914. text = showdown.subParser('codeBlocks')(text, options, globals);
  915. text = showdown.subParser('blockQuotes')(text, options, globals);
  916. // We already ran _HashHTMLBlocks() before, in Markdown(), but that
  917. // was to escape raw HTML in the original Markdown source. This time,
  918. // we're escaping the markup we've just created, so that we don't wrap
  919. // <p> tags around block-level tags.
  920. text = showdown.subParser('hashHTMLBlocks')(text, options, globals);
  921. text = showdown.subParser('paragraphs')(text, options, globals);
  922. return text;
  923. });
  924. showdown.subParser('blockQuotes', function (text, options, globals) {
  925. 'use strict';
  926. /*
  927. text = text.replace(/
  928. ( // Wrap whole match in $1
  929. (
  930. ^[ \t]*>[ \t]? // '>' at the start of a line
  931. .+\n // rest of the first line
  932. (.+\n)* // subsequent consecutive lines
  933. \n* // blanks
  934. )+
  935. )
  936. /gm, function(){...});
  937. */
  938. text = text.replace(/((^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+)/gm, function (wholeMatch, m1) {
  939. var bq = m1;
  940. // attacklab: hack around Konqueror 3.5.4 bug:
  941. // "----------bug".replace(/^-/g,"") == "bug"
  942. bq = bq.replace(/^[ \t]*>[ \t]?/gm, '~0'); // trim one level of quoting
  943. // attacklab: clean up hack
  944. bq = bq.replace(/~0/g, '');
  945. bq = bq.replace(/^[ \t]+$/gm, ''); // trim whitespace-only lines
  946. bq = showdown.subParser('blockGamut')(bq, options, globals); // recurse
  947. bq = bq.replace(/(^|\n)/g, '$1 ');
  948. // These leading spaces screw with <pre> content, so we need to fix that:
  949. bq = bq.replace(/(\s*<pre>[^\r]+?<\/pre>)/gm, function (wholeMatch, m1) {
  950. var pre = m1;
  951. // attacklab: hack around Konqueror 3.5.4 bug:
  952. pre = pre.replace(/^ /mg, '~0');
  953. pre = pre.replace(/~0/g, '');
  954. return pre;
  955. });
  956. return showdown.subParser('hashBlock')('<blockquote>\n' + bq + '\n</blockquote>', options, globals);
  957. });
  958. return text;
  959. });
  960. /**
  961. * Process Markdown `<pre><code>` blocks.
  962. */
  963. showdown.subParser('codeBlocks', function (text, options, globals) {
  964. 'use strict';
  965. /*
  966. text = text.replace(text,
  967. /(?:\n\n|^)
  968. ( // $1 = the code block -- one or more lines, starting with a space/tab
  969. (?:
  970. (?:[ ]{4}|\t) // Lines must start with a tab or a tab-width of spaces - attacklab: g_tab_width
  971. .*\n+
  972. )+
  973. )
  974. (\n*[ ]{0,3}[^ \t\n]|(?=~0)) // attacklab: g_tab_width
  975. /g,function(){...});
  976. */
  977. // attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
  978. text += '~0';
  979. var pattern = /(?:\n\n|^)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=~0))/g;
  980. text = text.replace(pattern, function (wholeMatch, m1, m2) {
  981. var codeblock = m1,
  982. nextChar = m2,
  983. end = '\n';
  984. codeblock = showdown.subParser('outdent')(codeblock);
  985. codeblock = showdown.subParser('encodeCode')(codeblock);
  986. codeblock = showdown.subParser('detab')(codeblock);
  987. codeblock = codeblock.replace(/^\n+/g, ''); // trim leading newlines
  988. codeblock = codeblock.replace(/\n+$/g, ''); // trim trailing newlines
  989. if (options.omitExtraWLInCodeBlocks) {
  990. end = '';
  991. }
  992. codeblock = '<pre><code>' + codeblock + end + '</code></pre>';
  993. return showdown.subParser('hashBlock')(codeblock, options, globals) + nextChar;
  994. });
  995. // attacklab: strip sentinel
  996. text = text.replace(/~0/, '');
  997. return text;
  998. });
  999. /**
  1000. *
  1001. * * Backtick quotes are used for <code></code> spans.
  1002. *
  1003. * * You can use multiple backticks as the delimiters if you want to
  1004. * include literal backticks in the code span. So, this input:
  1005. *
  1006. * Just type ``foo `bar` baz`` at the prompt.
  1007. *
  1008. * Will translate to:
  1009. *
  1010. * <p>Just type <code>foo `bar` baz</code> at the prompt.</p>
  1011. *
  1012. * There's no arbitrary limit to the number of backticks you
  1013. * can use as delimters. If you need three consecutive backticks
  1014. * in your code, use four for delimiters, etc.
  1015. *
  1016. * * You can use spaces to get literal backticks at the edges:
  1017. *
  1018. * ... type `` `bar` `` ...
  1019. *
  1020. * Turns to:
  1021. *
  1022. * ... type <code>`bar`</code> ...
  1023. */
  1024. showdown.subParser('codeSpans', function (text) {
  1025. 'use strict';
  1026. /*
  1027. text = text.replace(/
  1028. (^|[^\\]) // Character before opening ` can't be a backslash
  1029. (`+) // $2 = Opening run of `
  1030. ( // $3 = The code block
  1031. [^\r]*?
  1032. [^`] // attacklab: work around lack of lookbehind
  1033. )
  1034. \2 // Matching closer
  1035. (?!`)
  1036. /gm, function(){...});
  1037. */
  1038. text = text.replace(/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/gm, function (wholeMatch, m1, m2, m3) {
  1039. var c = m3;
  1040. c = c.replace(/^([ \t]*)/g, ''); // leading whitespace
  1041. c = c.replace(/[ \t]*$/g, ''); // trailing whitespace
  1042. c = showdown.subParser('encodeCode')(c);
  1043. return m1 + '<code>' + c + '</code>';
  1044. });
  1045. return text;
  1046. });
  1047. /**
  1048. * Convert all tabs to spaces
  1049. */
  1050. showdown.subParser('detab', function (text) {
  1051. 'use strict';
  1052. // expand first n-1 tabs
  1053. text = text.replace(/\t(?=\t)/g, ' '); // g_tab_width
  1054. // replace the nth with two sentinels
  1055. text = text.replace(/\t/g, '~A~B');
  1056. // use the sentinel to anchor our regex so it doesn't explode
  1057. text = text.replace(/~B(.+?)~A/g, function (wholeMatch, m1) {
  1058. var leadingText = m1,
  1059. numSpaces = 4 - leadingText.length % 4; // g_tab_width
  1060. // there *must* be a better way to do this:
  1061. for (var i = 0; i < numSpaces; i++) {
  1062. leadingText += ' ';
  1063. }
  1064. return leadingText;
  1065. });
  1066. // clean up sentinels
  1067. text = text.replace(/~A/g, ' '); // g_tab_width
  1068. text = text.replace(/~B/g, '');
  1069. return text;
  1070. });
  1071. /**
  1072. * Smart processing for ampersands and angle brackets that need to be encoded.
  1073. */
  1074. showdown.subParser('encodeAmpsAndAngles', function (text) {
  1075. 'use strict';
  1076. // Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
  1077. // http://bumppo.net/projects/amputator/
  1078. text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g, '&amp;');
  1079. // Encode naked <'s
  1080. text = text.replace(/<(?![a-z\/?\$!])/gi, '&lt;');
  1081. return text;
  1082. });
  1083. /**
  1084. * Returns the string, with after processing the following backslash escape sequences.
  1085. *
  1086. * attacklab: The polite way to do this is with the new escapeCharacters() function:
  1087. *
  1088. * text = escapeCharacters(text,"\\",true);
  1089. * text = escapeCharacters(text,"`*_{}[]()>#+-.!",true);
  1090. *
  1091. * ...but we're sidestepping its use of the (slow) RegExp constructor
  1092. * as an optimization for Firefox. This function gets called a LOT.
  1093. */
  1094. showdown.subParser('encodeBackslashEscapes', function (text) {
  1095. 'use strict';
  1096. text = text.replace(/\\(\\)/g, showdown.helper.escapeCharactersCallback);
  1097. text = text.replace(/\\([`*_{}\[\]()>#+-.!])/g, showdown.helper.escapeCharactersCallback);
  1098. return text;
  1099. });
  1100. /**
  1101. * Encode/escape certain characters inside Markdown code runs.
  1102. * The point is that in code, these characters are literals,
  1103. * and lose their special Markdown meanings.
  1104. */
  1105. showdown.subParser('encodeCode', function (text) {
  1106. 'use strict';
  1107. // Encode all ampersands; HTML entities are not
  1108. // entities within a Markdown code span.
  1109. text = text.replace(/&/g, '&amp;');
  1110. // Do the angle bracket song and dance:
  1111. text = text.replace(/</g, '&lt;');
  1112. text = text.replace(/>/g, '&gt;');
  1113. // Now, escape characters that are magic in Markdown:
  1114. text = showdown.helper.escapeCharacters(text, '*_{}[]\\', false);
  1115. // jj the line above breaks this:
  1116. //---
  1117. //* Item
  1118. // 1. Subitem
  1119. // special char: *
  1120. // ---
  1121. return text;
  1122. });
  1123. /**
  1124. * Input: an email address, e.g. "foo@example.com"
  1125. *
  1126. * Output: the email address as a mailto link, with each character
  1127. * of the address encoded as either a decimal or hex entity, in
  1128. * the hopes of foiling most address harvesting spam bots. E.g.:
  1129. *
  1130. * <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101;
  1131. * x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111;
  1132. * &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a>
  1133. *
  1134. * Based on a filter by Matthew Wickline, posted to the BBEdit-Talk
  1135. * mailing list: <http://tinyurl.com/yu7ue>
  1136. *
  1137. */
  1138. showdown.subParser('encodeEmailAddress', function (addr) {
  1139. 'use strict';
  1140. var encode = [
  1141. function (ch) {
  1142. return '&#' + ch.charCodeAt(0) + ';';
  1143. },
  1144. function (ch) {
  1145. return '&#x' + ch.charCodeAt(0).toString(16) + ';';
  1146. },
  1147. function (ch) {
  1148. return ch;
  1149. }
  1150. ];
  1151. addr = 'mailto:' + addr;
  1152. addr = addr.replace(/./g, function (ch) {
  1153. if (ch === '@') {
  1154. // this *must* be encoded. I insist.
  1155. ch = encode[Math.floor(Math.random() * 2)](ch);
  1156. } else if (ch !== ':') {
  1157. // leave ':' alone (to spot mailto: later)
  1158. var r = Math.random();
  1159. // roughly 10% raw, 45% hex, 45% dec
  1160. ch = (
  1161. r > 0.9 ? encode[2](ch) : r > 0.45 ? encode[1](ch) : encode[0](ch)
  1162. );
  1163. }
  1164. return ch;
  1165. });
  1166. addr = '<a href="' + addr + '">' + addr + '</a>';
  1167. addr = addr.replace(/">.+:/g, '">'); // strip the mailto: from the visible part
  1168. return addr;
  1169. });
  1170. /**
  1171. * Within tags -- meaning between < and > -- encode [\ ` * _] so they
  1172. * don't conflict with their use in Markdown for code, italics and strong.
  1173. */
  1174. showdown.subParser('escapeSpecialCharsWithinTagAttributes', function (text) {
  1175. 'use strict';
  1176. // Build a regex to find HTML tags and comments. See Friedl's
  1177. // "Mastering Regular Expressions", 2nd Ed., pp. 200-201.
  1178. var regex = /(<[a-z\/!$]("[^"]*"|'[^']*'|[^'">])*>|<!(--.*?--\s*)+>)/gi;
  1179. text = text.replace(regex, function (wholeMatch) {
  1180. var tag = wholeMatch.replace(/(.)<\/?code>(?=.)/g, '$1`');
  1181. tag = showdown.helper.escapeCharacters(tag, '\\`*_', false);
  1182. return tag;
  1183. });
  1184. return text;
  1185. });
  1186. /**
  1187. * Handle github codeblocks prior to running HashHTML so that
  1188. * HTML contained within the codeblock gets escaped properly
  1189. * Example:
  1190. * ```ruby
  1191. * def hello_world(x)
  1192. * puts "Hello, #{x}"
  1193. * end
  1194. * ```
  1195. */
  1196. showdown.subParser('githubCodeBlocks', function (text, options, globals) {
  1197. 'use strict';
  1198. // early exit if option is not enabled
  1199. if (!options.ghCodeBlocks) {
  1200. return text;
  1201. }
  1202. text += '~0';
  1203. text = text.replace(/(?:^|\n)```(.*)\n([\s\S]*?)\n```/g, function (wholeMatch, m1, m2) {
  1204. var language = m1,
  1205. codeblock = m2,
  1206. end = '\n';
  1207. if (options.omitExtraWLInCodeBlocks) {
  1208. end = '';
  1209. }
  1210. codeblock = showdown.subParser('encodeCode')(codeblock);
  1211. codeblock = showdown.subParser('detab')(codeblock);
  1212. codeblock = codeblock.replace(/^\n+/g, ''); // trim leading newlines
  1213. codeblock = codeblock.replace(/\n+$/g, ''); // trim trailing whitespace
  1214. codeblock = '<pre><code' + (language ? ' class="' + language + ' language-' + language + '"' : '') + '>' + codeblock + end + '</code></pre>';
  1215. return showdown.subParser('hashBlock')(codeblock, options, globals);
  1216. });
  1217. // attacklab: strip sentinel
  1218. text = text.replace(/~0/, '');
  1219. return text;
  1220. });
  1221. showdown.subParser('hashBlock', function (text, options, globals) {
  1222. 'use strict';
  1223. text = text.replace(/(^\n+|\n+$)/g, '');
  1224. return '\n\n~K' + (globals.gHtmlBlocks.push(text) - 1) + 'K\n\n';
  1225. });
  1226. showdown.subParser('hashElement', function (text, options, globals) {
  1227. 'use strict';
  1228. return function (wholeMatch, m1) {
  1229. var blockText = m1;
  1230. // Undo double lines
  1231. blockText = blockText.replace(/\n\n/g, '\n');
  1232. blockText = blockText.replace(/^\n/, '');
  1233. // strip trailing blank lines
  1234. blockText = blockText.replace(/\n+$/g, '');
  1235. // Replace the element text with a marker ("~KxK" where x is its key)
  1236. blockText = '\n\n~K' + (globals.gHtmlBlocks.push(blockText) - 1) + 'K\n\n';
  1237. return blockText;
  1238. };
  1239. });
  1240. showdown.subParser('hashHTMLBlocks', function (text, options, globals) {
  1241. 'use strict';
  1242. // attacklab: Double up blank lines to reduce lookaround
  1243. text = text.replace(/\n/g, '\n\n');
  1244. // Hashify HTML blocks:
  1245. // We only want to do this for block-level HTML tags, such as headers,
  1246. // lists, and tables. That's because we still want to wrap <p>s around
  1247. // "paragraphs" that are wrapped in non-block-level tags, such as anchors,
  1248. // phrase emphasis, and spans. The list of tags we're looking for is
  1249. // hard-coded:
  1250. //var block_tags_a =
  1251. // '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';
  1252. // var block_tags_b =
  1253. // 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|style|section|header|footer|nav|article|aside';
  1254. // First, look for nested blocks, e.g.:
  1255. // <div>
  1256. // <div>
  1257. // tags for inner block must be indented.
  1258. // </div>
  1259. // </div>
  1260. //
  1261. // The outermost tags must start at the left margin for this to match, and
  1262. // the inner nested divs must be indented.
  1263. // We need to do this before the next, more liberal match, because the next
  1264. // match will start at the first `<div>` and stop at the first `</div>`.
  1265. // attacklab: This regex can be expensive when it fails.
  1266. /*
  1267. var text = text.replace(/
  1268. ( // save in $1
  1269. ^ // start of line (with /m)
  1270. <($block_tags_a) // start tag = $2
  1271. \b // word break
  1272. // attacklab: hack around khtml/pcre bug...
  1273. [^\r]*?\n // any number of lines, minimally matching
  1274. </\2> // the matching end tag
  1275. [ \t]* // trailing spaces/tabs
  1276. (?=\n+) // followed by a newline
  1277. ) // attacklab: there are sentinel newlines at end of document
  1278. /gm,function(){...}};
  1279. */
  1280. 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,
  1281. showdown.subParser('hashElement')(text, options, globals));
  1282. //
  1283. // Now match more liberally, simply from `\n<tag>` to `</tag>\n`
  1284. //
  1285. /*
  1286. var text = text.replace(/
  1287. ( // save in $1
  1288. ^ // start of line (with /m)
  1289. <($block_tags_b) // start tag = $2
  1290. \b // word break
  1291. // attacklab: hack around khtml/pcre bug...
  1292. [^\r]*? // any number of lines, minimally matching
  1293. </\2> // the matching end tag
  1294. [ \t]* // trailing spaces/tabs
  1295. (?=\n+) // followed by a newline
  1296. ) // attacklab: there are sentinel newlines at end of document
  1297. /gm,function(){...}};
  1298. */
  1299. 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,
  1300. showdown.subParser('hashElement')(text, options, globals));
  1301. // Special case just for <hr />. It was easier to make a special case than
  1302. // to make the other regex more complicated.
  1303. /*
  1304. text = text.replace(/
  1305. ( // save in $1
  1306. \n\n // Starting after a blank line
  1307. [ ]{0,3}
  1308. (<(hr) // start tag = $2
  1309. \b // word break
  1310. ([^<>])*? //
  1311. \/?>) // the matching end tag
  1312. [ \t]*
  1313. (?=\n{2,}) // followed by a blank line
  1314. )
  1315. /g,showdown.subParser('hashElement')(text, options, globals));
  1316. */
  1317. text = text.replace(/(\n[ ]{0,3}(<(hr)\b([^<>])*?\/?>)[ \t]*(?=\n{2,}))/g,
  1318. showdown.subParser('hashElement')(text, options, globals));
  1319. // Special case for standalone HTML comments:
  1320. /*
  1321. text = text.replace(/
  1322. ( // save in $1
  1323. \n\n // Starting after a blank line
  1324. [ ]{0,3} // attacklab: g_tab_width - 1
  1325. <!
  1326. (--[^\r]*?--\s*)+
  1327. >
  1328. [ \t]*
  1329. (?=\n{2,}) // followed by a blank line
  1330. )
  1331. /g,showdown.subParser('hashElement')(text, options, globals));
  1332. */
  1333. text = text.replace(/(\n\n[ ]{0,3}<!(--[^\r]*?--\s*)+>[ \t]*(?=\n{2,}))/g,
  1334. showdown.subParser('hashElement')(text, options, globals));
  1335. // PHP and ASP-style processor instructions (<?...?> and <%...%>)
  1336. /*
  1337. text = text.replace(/
  1338. (?:
  1339. \n\n // Starting after a blank line
  1340. )
  1341. ( // save in $1
  1342. [ ]{0,3} // attacklab: g_tab_width - 1
  1343. (?:
  1344. <([?%]) // $2
  1345. [^\r]*?
  1346. \2>
  1347. )
  1348. [ \t]*
  1349. (?=\n{2,}) // followed by a blank line
  1350. )
  1351. /g,showdown.subParser('hashElement')(text, options, globals));
  1352. */
  1353. text = text.replace(/(?:\n\n)([ ]{0,3}(?:<([?%])[^\r]*?\2>)[ \t]*(?=\n{2,}))/g,
  1354. showdown.subParser('hashElement')(text, options, globals));
  1355. // attacklab: Undo double lines (see comment at top of this function)
  1356. text = text.replace(/\n\n/g, '\n');
  1357. return text;
  1358. });
  1359. showdown.subParser('headers', function (text, options, globals) {
  1360. 'use strict';
  1361. var prefixHeader = options.prefixHeaderId,
  1362. headerLevelStart = (isNaN(parseInt(options.headerLevelStart))) ? 1 : parseInt(options.headerLevelStart),
  1363. // Set text-style headers:
  1364. // Header 1
  1365. // ========
  1366. //
  1367. // Header 2
  1368. // --------
  1369. //
  1370. setextRegexH1 = (options.smoothLivePreview) ? /^(.+)[ \t]*\n={2,}[ \t]*\n+/gm : /^(.+)[ \t]*\n=+[ \t]*\n+/gm,
  1371. setextRegexH2 = (options.smoothLivePreview) ? /^(.+)[ \t]*\n-{2,}[ \t]*\n+/gm : /^(.+)[ \t]*\n-+[ \t]*\n+/gm;
  1372. text = text.replace(setextRegexH1, function (wholeMatch, m1) {
  1373. var spanGamut = showdown.subParser('spanGamut')(m1, options, globals),
  1374. hID = (options.noHeaderId) ? '' : ' id="' + headerId(m1) + '"',
  1375. hLevel = headerLevelStart,
  1376. hashBlock = '<h' + hLevel + hID + '>' + spanGamut + '</h' + hLevel + '>';
  1377. return showdown.subParser('hashBlock')(hashBlock, options, globals);
  1378. });
  1379. text = text.replace(setextRegexH2, function (matchFound, m1) {
  1380. var spanGamut = showdown.subParser('spanGamut')(m1, options, globals),
  1381. hID = (options.noHeaderId) ? '' : ' id="' + headerId(m1) + '"',
  1382. hLevel = headerLevelStart + 1,
  1383. hashBlock = '<h' + hLevel + hID + '>' + spanGamut + '</h' + hLevel + '>';
  1384. return showdown.subParser('hashBlock')(hashBlock, options, globals);
  1385. });
  1386. // atx-style headers:
  1387. // # Header 1
  1388. // ## Header 2
  1389. // ## Header 2 with closing hashes ##
  1390. // ...
  1391. // ###### Header 6
  1392. //
  1393. text = text.replace(/^(#{1,6})[ \t]*(.+?)[ \t]*#*\n+/gm, function (wholeMatch, m1, m2) {
  1394. var span = showdown.subParser('spanGamut')(m2, options, globals),
  1395. hID = (options.noHeaderId) ? '' : ' id="' + headerId(m2) + '"',
  1396. hLevel = headerLevelStart - 1 + m1.length,
  1397. header = '<h' + hLevel + hID + '>' + span + '</h' + hLevel + '>';
  1398. return showdown.subParser('hashBlock')(header, options, globals);
  1399. });
  1400. function headerId(m) {
  1401. var title, escapedId = m.replace(/[^\w]/g, '').toLowerCase();
  1402. if (globals.hashLinkCounts[escapedId]) {
  1403. title = escapedId + '-' + (globals.hashLinkCounts[escapedId]++);
  1404. } else {
  1405. title = escapedId;
  1406. globals.hashLinkCounts[escapedId] = 1;
  1407. }
  1408. // Prefix id to prevent causing inadvertent pre-existing style matches.
  1409. if (prefixHeader === true) {
  1410. prefixHeader = 'section';
  1411. }
  1412. if (showdown.helper.isString(prefixHeader)) {
  1413. return prefixHeader + title;
  1414. }
  1415. return title;
  1416. }
  1417. return text;
  1418. });
  1419. /**
  1420. * Turn Markdown image shortcuts into <img> tags.
  1421. */
  1422. showdown.subParser('images', function (text, options, globals) {
  1423. 'use strict';
  1424. var inlineRegExp = /!\[(.*?)]\s?\([ \t]*()<?(\S+?)>?(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*(?:(['"])(.*?)\6[ \t]*)?\)/g,
  1425. referenceRegExp = /!\[(.*?)][ ]?(?:\n[ ]*)?\[(.*?)]()()()()()/g;
  1426. function writeImageTag (wholeMatch, altText, linkId, url, width, height, m5, title) {
  1427. var gUrls = globals.gUrls,
  1428. gTitles = globals.gTitles,
  1429. gDims = globals.gDimensions;
  1430. linkId = linkId.toLowerCase();
  1431. if (!title) {
  1432. title = '';
  1433. }
  1434. if (url === '' || url === null) {
  1435. if (linkId === '' || linkId === null) {
  1436. // lower-case and turn embedded newlines into spaces
  1437. linkId = altText.toLowerCase().replace(/ ?\n/g, ' ');
  1438. }
  1439. url = '#' + linkId;
  1440. if (!showdown.helper.isUndefined(gUrls[linkId])) {
  1441. url = gUrls[linkId];
  1442. if (!showdown.helper.isUndefined(gTitles[linkId])) {
  1443. title = gTitles[linkId];
  1444. }
  1445. if (!showdown.helper.isUndefined(gDims[linkId])) {
  1446. width = gDims[linkId].width;
  1447. height = gDims[linkId].height;
  1448. }
  1449. } else {
  1450. return wholeMatch;
  1451. }
  1452. }
  1453. altText = altText.replace(/"/g, '&quot;');
  1454. url = showdown.helper.escapeCharacters(url, '*_', false);
  1455. var result = '<img src="' + url + '" alt="' + altText + '"';
  1456. if (title) {
  1457. title = title.replace(/"/g, '&quot;');
  1458. title = showdown.helper.escapeCharacters(title, '*_', false);
  1459. result += ' title="' + title + '"';
  1460. }
  1461. if (width && height) {
  1462. width = (width === '*') ? 'auto' : width;
  1463. height = (height === '*') ? 'auto' : height;
  1464. result += ' width="' + width + '"';
  1465. result += ' height="' + height + '"';
  1466. }
  1467. result += ' />';
  1468. return result;
  1469. }
  1470. // First, handle reference-style labeled images: ![alt text][id]
  1471. text = text.replace(referenceRegExp, writeImageTag);
  1472. // Next, handle inline images: ![alt text](url =<width>x<height> "optional title")
  1473. text = text.replace(inlineRegExp, writeImageTag);
  1474. return text;
  1475. });
  1476. showdown.subParser('italicsAndBold', function (text, options) {
  1477. 'use strict';
  1478. if (options.literalMidWordUnderscores) {
  1479. //underscores
  1480. // Since we are consuming a \s character, we need to add it
  1481. text = text.replace(/(^|\s)__(?=\S)([^]+?)__(?=\s|$)/gm, '$1<strong>$2</strong>');
  1482. text = text.replace(/(^|\s)_(?=\S)([^]+?)_(?=\s|$)/gm, '$1<em>$2</em>');
  1483. //asterisks
  1484. text = text.replace(/\*\*(?=\S)([^]+?)\*\*/g, '<strong>$1</strong>');
  1485. text = text.replace(/\*(?=\S)([^]+?)\*/g, '<em>$1</em>');
  1486. } else {
  1487. // <strong> must go first:
  1488. text = text.replace(/(\*\*|__)(?=\S)([^\r]*?\S[*_]*)\1/g, '<strong>$2</strong>');
  1489. text = text.replace(/(\*|_)(?=\S)([^\r]*?\S)\1/g, '<em>$2</em>');
  1490. }
  1491. return text;
  1492. });
  1493. /**
  1494. * Form HTML ordered (numbered) and unordered (bulleted) lists.
  1495. */
  1496. showdown.subParser('lists', function (text, options, globals) {
  1497. 'use strict';
  1498. var spl = '~1';
  1499. /**
  1500. * Process the contents of a single ordered or unordered list, splitting it
  1501. * into individual list items.
  1502. * @param {string} listStr
  1503. * @returns {string}
  1504. */
  1505. function processListItems (listStr) {
  1506. // The $g_list_level global keeps track of when we're inside a list.
  1507. // Each time we enter a list, we increment it; when we leave a list,
  1508. // we decrement. If it's zero, we're not in a list anymore.
  1509. //
  1510. // We do this because when we're not inside a list, we want to treat
  1511. // something like this:
  1512. //
  1513. // I recommend upgrading to version
  1514. // 8. Oops, now this line is treated
  1515. // as a sub-list.
  1516. //
  1517. // As a single paragraph, despite the fact that the second line starts
  1518. // with a digit-period-space sequence.
  1519. //
  1520. // Whereas when we're inside a list (or sub-list), that line will be
  1521. // treated as the start of a sub-list. What a kludge, huh? This is
  1522. // an aspect of Markdown's syntax that's hard to parse perfectly
  1523. // without resorting to mind-reading. Perhaps the solution is to
  1524. // change the syntax rules such that sub-lists must start with a
  1525. // starting cardinal number; e.g. "1." or "a.".
  1526. globals.gListLevel++;
  1527. // trim trailing blank lines:
  1528. listStr = listStr.replace(/\n{2,}$/, '\n');
  1529. // attacklab: add sentinel to emulate \z
  1530. listStr += '~0';
  1531. var rgx = /(\n)?(^[ \t]*)([*+-]|\d+[.])[ \t]+((\[(x| )?])?[ \t]*[^\r]+?(\n{1,2}))(?=\n*(~0|\2([*+-]|\d+[.])[ \t]+))/gm;
  1532. listStr = listStr.replace(rgx, function (wholeMatch, m1, m2, m3, m4, taskbtn, checked) {
  1533. checked = (checked && checked.trim() !== '');
  1534. var item = showdown.subParser('outdent')(m4, options, globals);
  1535. //m1 - LeadingLine
  1536. if (m1 || (item.search(/\n{2,}/) > -1)) {
  1537. item = showdown.subParser('blockGamut')(item, options, globals);
  1538. } else {
  1539. if (taskbtn && options.tasklists) {
  1540. item = item.replace(taskbtn, function () {
  1541. var otp = '<input type="checkbox" disabled style="margin: 0px 0.35em 0.25em -1.6em; vertical-align: middle;"';
  1542. if (checked) {
  1543. otp += ' checked';
  1544. }
  1545. otp += '>';
  1546. return otp;
  1547. });
  1548. }
  1549. // Recursion for sub-lists:
  1550. item = showdown.subParser('lists')(item, options, globals);
  1551. item = item.replace(/\n$/, ''); // chomp(item)
  1552. item = showdown.subParser('spanGamut')(item, options, globals);
  1553. }
  1554. // this is a "hack" to differentiate between ordered and unordered lists
  1555. // related to issue #142
  1556. var tp = (m3.search(/[*+-]/g) > -1) ? 'ul' : 'ol',
  1557. bulletStyle = '';
  1558. if (taskbtn) {
  1559. bulletStyle = ' class="task-list-item" style="list-style-type: none;"';
  1560. }
  1561. return spl + tp + '<li' + bulletStyle + '>' + item + '</li>\n';
  1562. });
  1563. // attacklab: strip sentinel
  1564. listStr = listStr.replace(/~0/g, '');
  1565. globals.gListLevel--;
  1566. return listStr;
  1567. }
  1568. /**
  1569. * Slit consecutive ol/ul lists (related to issue 142)
  1570. * @param {Array} results
  1571. * @param {string} listType
  1572. * @returns {string|*}
  1573. */
  1574. function splitConsecutiveLists (results, listType) {
  1575. // parsing html with regex...
  1576. // This will surely fail if some extension decides to change paragraph markup directly
  1577. var cthulhu = /(<p[^>]+?>|<p>|<\/p>)/img,
  1578. holder = [[]],
  1579. res = '',
  1580. y = 0;
  1581. // Initialize first sublist
  1582. holder[0].type = listType;
  1583. for (var i = 0; i < results.length; ++i) {
  1584. var txt = results[i].slice(2),
  1585. nListType = results[i].slice(0, 2);
  1586. if (listType !== nListType) {
  1587. y++;
  1588. holder[y] = [];
  1589. holder[y].type = nListType;
  1590. listType = nListType;
  1591. }
  1592. holder[y].push(txt);
  1593. }
  1594. for (i = 0; i < holder.length; ++i) {
  1595. res += '<' + holder[i].type + '>\n';
  1596. for (var ii = 0; ii < holder[i].length; ++ii) {
  1597. if (holder[i].length > 1 && ii === holder[i].length - 1 && !cthulhu.test(holder[i][ii - 1])) {
  1598. //holder[i][ii] = holder[i][ii].replace(cthulhu, '');
  1599. }
  1600. res += holder[i][ii];
  1601. }
  1602. res += '</' + holder[i].type + '>\n';
  1603. }
  1604. return res;
  1605. }
  1606. // attacklab: add sentinel to hack around khtml/safari bug:
  1607. // http://bugs.webkit.org/show_bug.cgi?id=11231
  1608. text += '~0';
  1609. // Re-usable pattern to match any entire ul or ol list:
  1610. var wholeList = /^(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm;
  1611. if (globals.gListLevel) {
  1612. text = text.replace(wholeList, function (wholeMatch, m1, m2) {
  1613. var listType = (m2.search(/[*+-]/g) > -1) ? 'ul' : 'ol',
  1614. result = processListItems(m1);
  1615. // Turn double returns into triple returns, so that we can make a
  1616. // paragraph for the last item in a list, if necessary:
  1617. //list = list.replace(/\n{2,}/g, '\n\n\n');
  1618. //result = processListItems(list);
  1619. // Trim any trailing whitespace, to put the closing `</$list_type>`
  1620. // up on the preceding line, to get it past the current stupid
  1621. // HTML block parser. This is a hack to work around the terrible
  1622. // hack that is the HTML block parser.
  1623. result = result.replace(/\s+$/, '');
  1624. var splRes = result.split(spl);
  1625. splRes.shift();
  1626. result = splitConsecutiveLists(splRes, listType);
  1627. return result;
  1628. });
  1629. } else {
  1630. wholeList = /(\n\n|^\n?)(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/g;
  1631. //wholeList = /(\n\n|^\n?)( {0,3}([*+-]|\d+\.)[ \t]+[\s\S]+?)(?=(~0)|(\n\n(?!\t| {2,}| {0,3}([*+-]|\d+\.)[ \t])))/g;
  1632. text = text.replace(wholeList, function (wholeMatch, m1, m2, m3) {
  1633. // Turn double returns into triple returns, so that we can make a
  1634. // paragraph for the last item in a list, if necessary:
  1635. var list = m2.replace(/\n{2,}/g, '\n\n\n'),
  1636. //var list = (m2.slice(-2) !== '~0') ? m2 + '\n' : m2, //add a newline after the list
  1637. listType = (m3.search(/[*+-]/g) > -1) ? 'ul' : 'ol',
  1638. result = processListItems(list),
  1639. splRes = result.split(spl);
  1640. splRes.shift();
  1641. return m1 + splitConsecutiveLists(splRes, listType) + '\n';
  1642. });
  1643. }
  1644. // attacklab: strip sentinel
  1645. text = text.replace(/~0/, '');
  1646. return text;
  1647. });
  1648. /**
  1649. * Remove one level of line-leading tabs or spaces
  1650. */
  1651. showdown.subParser('outdent', function (text) {
  1652. 'use strict';
  1653. // attacklab: hack around Konqueror 3.5.4 bug:
  1654. // "----------bug".replace(/^-/g,"") == "bug"
  1655. text = text.replace(/^(\t|[ ]{1,4})/gm, '~0'); // attacklab: g_tab_width
  1656. // attacklab: clean up hack
  1657. text = text.replace(/~0/g, '');
  1658. return text;
  1659. });
  1660. /**
  1661. *
  1662. */
  1663. showdown.subParser('paragraphs', function (text, options, globals) {
  1664. 'use strict';
  1665. // Strip leading and trailing lines:
  1666. text = text.replace(/^\n+/g, '');
  1667. text = text.replace(/\n+$/g, '');
  1668. var grafs = text.split(/\n{2,}/g),
  1669. grafsOut = [],
  1670. end = grafs.length; // Wrap <p> tags
  1671. for (var i = 0; i < end; i++) {
  1672. var str = grafs[i];
  1673. // if this is an HTML marker, copy it
  1674. if (str.search(/~K(\d+)K/g) >= 0) {
  1675. grafsOut.push(str);
  1676. } else if (str.search(/\S/) >= 0) {
  1677. str = showdown.subParser('spanGamut')(str, options, globals);
  1678. str = str.replace(/^([ \t]*)/g, '<p>');
  1679. str += '</p>';
  1680. grafsOut.push(str);
  1681. }
  1682. }
  1683. /** Unhashify HTML blocks */
  1684. end = grafsOut.length;
  1685. for (i = 0; i < end; i++) {
  1686. // if this is a marker for an html block...
  1687. while (grafsOut[i].search(/~K(\d+)K/) >= 0) {
  1688. var blockText = globals.gHtmlBlocks[RegExp.$1];
  1689. blockText = blockText.replace(/\$/g, '$$$$'); // Escape any dollar signs
  1690. grafsOut[i] = grafsOut[i].replace(/~K\d+K/, blockText);
  1691. }
  1692. }
  1693. return grafsOut.join('\n\n');
  1694. });
  1695. /**
  1696. * Run extension
  1697. */
  1698. showdown.subParser('runExtension', function (ext, text, options, globals) {
  1699. 'use strict';
  1700. if (ext.filter) {
  1701. text = ext.filter(text, globals.converter, options);
  1702. } else if (ext.regex) {
  1703. // TODO remove this when old extension loading mechanism is deprecated
  1704. var re = ext.regex;
  1705. if (!re instanceof RegExp) {
  1706. re = new RegExp(re, 'g');
  1707. }
  1708. text = text.replace(re, ext.replace);
  1709. }
  1710. return text;
  1711. });
  1712. /**
  1713. * These are all the transformations that occur *within* block-level
  1714. * tags like paragraphs, headers, and list items.
  1715. */
  1716. showdown.subParser('spanGamut', function (text, options, globals) {
  1717. 'use strict';
  1718. text = showdown.subParser('codeSpans')(text, options, globals);
  1719. text = showdown.subParser('escapeSpecialCharsWithinTagAttributes')(text, options, globals);
  1720. text = showdown.subParser('encodeBackslashEscapes')(text, options, globals);
  1721. // Process anchor and image tags. Images must come first,
  1722. // because ![foo][f] looks like an anchor.
  1723. text = showdown.subParser('images')(text, options, globals);
  1724. text = showdown.subParser('anchors')(text, options, globals);
  1725. // Make links out of things like `<http://example.com/>`
  1726. // Must come after _DoAnchors(), because you can use < and >
  1727. // delimiters in inline links like [this](<url>).
  1728. text = showdown.subParser('autoLinks')(text, options, globals);
  1729. text = showdown.subParser('encodeAmpsAndAngles')(text, options, globals);
  1730. text = showdown.subParser('italicsAndBold')(text, options, globals);
  1731. text = showdown.subParser('strikethrough')(text, options, globals);
  1732. // Do hard breaks:
  1733. text = text.replace(/ +\n/g, ' <br />\n');
  1734. return text;
  1735. });
  1736. showdown.subParser('strikethrough', function (text, options) {
  1737. 'use strict';
  1738. if (options.strikethrough) {
  1739. text = text.replace(/(?:~T){2}([^~]+)(?:~T){2}/g, '<del>$1</del>');
  1740. }
  1741. return text;
  1742. });
  1743. /**
  1744. * Strip any lines consisting only of spaces and tabs.
  1745. * This makes subsequent regexs easier to write, because we can
  1746. * match consecutive blank lines with /\n+/ instead of something
  1747. * contorted like /[ \t]*\n+/
  1748. */
  1749. showdown.subParser('stripBlankLines', function (text) {
  1750. 'use strict';
  1751. return text.replace(/^[ \t]+$/mg, '');
  1752. });
  1753. /**
  1754. * Strips link definitions from text, stores the URLs and titles in
  1755. * hash references.
  1756. * Link defs are in the form: ^[id]: url "optional title"
  1757. *
  1758. * ^[ ]{0,3}\[(.+)\]: // id = $1 attacklab: g_tab_width - 1
  1759. * [ \t]*
  1760. * \n? // maybe *one* newline
  1761. * [ \t]*
  1762. * <?(\S+?)>? // url = $2
  1763. * [ \t]*
  1764. * \n? // maybe one newline
  1765. * [ \t]*
  1766. * (?:
  1767. * (\n*) // any lines skipped = $3 attacklab: lookbehind removed
  1768. * ["(]
  1769. * (.+?) // title = $4
  1770. * [")]
  1771. * [ \t]*
  1772. * )? // title is optional
  1773. * (?:\n+|$)
  1774. * /gm,
  1775. * function(){...});
  1776. *
  1777. */
  1778. showdown.subParser('stripLinkDefinitions', function (text, options, globals) {
  1779. 'use strict';
  1780. var regex = /^ {0,3}\[(.+)]:[ \t]*\n?[ \t]*<?(\S+?)>?(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*\n?[ \t]*(?:(\n*)["|'(](.+?)["|')][ \t]*)?(?:\n+|(?=~0))/gm;
  1781. // attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
  1782. text += '~0';
  1783. text = text.replace(regex, function (wholeMatch, linkId, url, width, height, blankLines, title) {
  1784. linkId = linkId.toLowerCase();
  1785. globals.gUrls[linkId] = showdown.subParser('encodeAmpsAndAngles')(url); // Link IDs are case-insensitive
  1786. if (blankLines) {
  1787. // Oops, found blank lines, so it's not a title.
  1788. // Put back the parenthetical statement we stole.
  1789. return blankLines + title;
  1790. } else {
  1791. if (title) {
  1792. globals.gTitles[linkId] = title.replace(/"|'/g, '&quot;');
  1793. }
  1794. if (options.parseImgDimensions && width && height) {
  1795. globals.gDimensions[linkId] = {
  1796. width: width,
  1797. height: height
  1798. };
  1799. }
  1800. }
  1801. // Completely remove the definition from the text
  1802. return '';
  1803. });
  1804. // attacklab: strip sentinel
  1805. text = text.replace(/~0/, '');
  1806. return text;
  1807. });
  1808. showdown.subParser('tables', function (text, options, globals) {
  1809. 'use strict';
  1810. var table = function () {
  1811. var tables = {},
  1812. filter;
  1813. tables.th = function (header, style) {
  1814. var id = '';
  1815. header = header.trim();
  1816. if (header === '') {
  1817. return '';
  1818. }
  1819. if (options.tableHeaderId) {
  1820. id = ' id="' + header.replace(/ /g, '_').toLowerCase() + '"';
  1821. }
  1822. if (!style || style.trim() === '') {
  1823. style = '';
  1824. } else {
  1825. style = ' style="' + style + '"';
  1826. }
  1827. return '<th' + id + style + '>' + header + '</th>';
  1828. };
  1829. tables.td = function (cell, style) {
  1830. var subText = showdown.subParser('spanGamut')(cell.trim(), options, globals);
  1831. if (!style || style.trim() === '') {
  1832. style = '';
  1833. } else {
  1834. style = ' style="' + style + '"';
  1835. }
  1836. return '<td' + style + '>' + subText + '</td>';
  1837. };
  1838. tables.ths = function () {
  1839. var out = '',
  1840. i = 0,
  1841. hs = [].slice.apply(arguments[0]),
  1842. style = [].slice.apply(arguments[1]);
  1843. for (i; i < hs.length; i += 1) {
  1844. out += tables.th(hs[i], style[i]) + '\n';
  1845. }
  1846. return out;
  1847. };
  1848. tables.tds = function () {
  1849. var out = '',
  1850. i = 0,
  1851. ds = [].slice.apply(arguments[0]),
  1852. style = [].slice.apply(arguments[1]);
  1853. for (i; i < ds.length; i += 1) {
  1854. out += tables.td(ds[i], style[i]) + '\n';
  1855. }
  1856. return out;
  1857. };
  1858. tables.thead = function () {
  1859. var out,
  1860. hs = [].slice.apply(arguments[0]),
  1861. style = [].slice.apply(arguments[1]);
  1862. out = '<thead>\n';
  1863. out += '<tr>\n';
  1864. out += tables.ths.apply(this, [hs, style]);
  1865. out += '</tr>\n';
  1866. out += '</thead>\n';
  1867. return out;
  1868. };
  1869. tables.tr = function () {
  1870. var out,
  1871. cs = [].slice.apply(arguments[0]),
  1872. style = [].slice.apply(arguments[1]);
  1873. out = '<tr>\n';
  1874. out += tables.tds.apply(this, [cs, style]);
  1875. out += '</tr>\n';
  1876. return out;
  1877. };
  1878. filter = function (text) {
  1879. var i = 0,
  1880. lines = text.split('\n'),
  1881. line,
  1882. hs,
  1883. out = [];
  1884. for (i; i < lines.length; i += 1) {
  1885. line = lines[i];
  1886. // looks like a table heading
  1887. if (line.trim().match(/^[|].*[|]$/)) {
  1888. line = line.trim();
  1889. var tbl = [],
  1890. align = lines[i + 1].trim(),
  1891. styles = [],
  1892. j = 0;
  1893. if (align.match(/^[|][-=|: ]+[|]$/)) {
  1894. styles = align.substring(1, align.length - 1).split('|');
  1895. for (j = 0; j < styles.length; ++j) {
  1896. styles[j] = styles[j].trim();
  1897. if (styles[j].match(/^[:][-=| ]+[:]$/)) {
  1898. styles[j] = 'text-align:center;';
  1899. } else if (styles[j].match(/^[-=| ]+[:]$/)) {
  1900. styles[j] = 'text-align:right;';
  1901. } else if (styles[j].match(/^[:][-=| ]+$/)) {
  1902. styles[j] = 'text-align:left;';
  1903. } else {
  1904. styles[j] = '';
  1905. }
  1906. }
  1907. }
  1908. tbl.push('<table>');
  1909. hs = line.substring(1, line.length - 1).split('|');
  1910. if (styles.length === 0) {
  1911. for (j = 0; j < hs.length; ++j) {
  1912. styles.push('text-align:left');
  1913. }
  1914. }
  1915. tbl.push(tables.thead.apply(this, [hs, styles]));
  1916. line = lines[++i];
  1917. if (!line.trim().match(/^[|][-=|: ]+[|]$/)) {
  1918. // not a table rolling back
  1919. line = lines[--i];
  1920. } else {
  1921. line = lines[++i];
  1922. tbl.push('<tbody>');
  1923. while (line.trim().match(/^[|].*[|]$/)) {
  1924. line = line.trim();
  1925. tbl.push(tables.tr.apply(this, [line.substring(1, line.length - 1).split('|'), styles]));
  1926. line = lines[++i];
  1927. }
  1928. tbl.push('</tbody>');
  1929. tbl.push('</table>');
  1930. // we are done with this table and we move along
  1931. out.push(tbl.join('\n'));
  1932. continue;
  1933. }
  1934. }
  1935. out.push(line);
  1936. }
  1937. return out.join('\n');
  1938. };
  1939. return {parse: filter};
  1940. };
  1941. if (options.tables) {
  1942. var tableParser = table();
  1943. return tableParser.parse(text);
  1944. } else {
  1945. return text;
  1946. }
  1947. });
  1948. /**
  1949. * Swap back in all the special characters we've hidden.
  1950. */
  1951. showdown.subParser('unescapeSpecialChars', function (text) {
  1952. 'use strict';
  1953. text = text.replace(/~E(\d+)E/g, function (wholeMatch, m1) {
  1954. var charCodeToReplace = parseInt(m1);
  1955. return String.fromCharCode(charCodeToReplace);
  1956. });
  1957. return text;
  1958. });
  1959. var root = this;
  1960. // CommonJS/nodeJS Loader
  1961. if (typeof module !== 'undefined' && module.exports) {
  1962. module.exports = showdown;
  1963. // AMD Loader
  1964. } else if (typeof define === 'function' && define.amd) {
  1965. define('showdown', function () {
  1966. 'use strict';
  1967. return showdown;
  1968. });
  1969. // Regular Browser loader
  1970. } else {
  1971. root.showdown = showdown;
  1972. }
  1973. }).call(this);
  1974. //# sourceMappingURL=showdown.js.map