showdown.js 71 KB

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