showdown.js 65 KB

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