showdown.js 88 KB

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