showdown.js 70 KB

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