showdown.js 76 KB

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