showdown.js 81 KB

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