showdown.js 74 KB

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