showdown.js 70 KB

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