showdown.js 83 KB

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