showdown.js 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290
  1. ;/*! showdown 23-08-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. * POLYFILLS
  453. */
  454. if (showdown.helper.isUndefined(console)) {
  455. console = {
  456. warn: function (msg) {
  457. 'use strict';
  458. alert(msg);
  459. },
  460. log: function (msg) {
  461. 'use strict';
  462. alert(msg);
  463. }
  464. };
  465. }
  466. /**
  467. * Created by Estevao on 31-05-2015.
  468. */
  469. /**
  470. * Showdown Converter class
  471. * @class
  472. * @param {object} [converterOptions]
  473. * @returns {Converter}
  474. */
  475. showdown.Converter = function (converterOptions) {
  476. 'use strict';
  477. var
  478. /**
  479. * Options used by this converter
  480. * @private
  481. * @type {{}}
  482. */
  483. options = {},
  484. /**
  485. * Language extensions used by this converter
  486. * @private
  487. * @type {Array}
  488. */
  489. langExtensions = [],
  490. /**
  491. * Output modifiers extensions used by this converter
  492. * @private
  493. * @type {Array}
  494. */
  495. outputModifiers = [],
  496. /**
  497. * The parser Order
  498. * @private
  499. * @type {string[]}
  500. */
  501. parserOrder = [
  502. 'githubCodeBlocks',
  503. 'hashHTMLBlocks',
  504. 'stripLinkDefinitions',
  505. 'blockGamut',
  506. 'unescapeSpecialChars'
  507. ];
  508. _constructor();
  509. /**
  510. * Converter constructor
  511. * @private
  512. */
  513. function _constructor() {
  514. converterOptions = converterOptions || {};
  515. for (var gOpt in globalOptions) {
  516. if (globalOptions.hasOwnProperty(gOpt)) {
  517. options[gOpt] = globalOptions[gOpt];
  518. }
  519. }
  520. // Merge options
  521. if (typeof converterOptions === 'object') {
  522. for (var opt in converterOptions) {
  523. if (converterOptions.hasOwnProperty(opt)) {
  524. options[opt] = converterOptions[opt];
  525. }
  526. }
  527. } else {
  528. throw Error('Converter expects the passed parameter to be an object, but ' + typeof converterOptions +
  529. ' was passed instead.');
  530. }
  531. if (options.extensions) {
  532. showdown.helper.forEach(options.extensions, _parseExtension);
  533. }
  534. }
  535. /**
  536. * Parse extension
  537. * @param {*} ext
  538. * @param {string} [name='']
  539. * @private
  540. */
  541. function _parseExtension(ext, name) {
  542. name = name || null;
  543. // If it's a string, the extension was previously loaded
  544. if (showdown.helper.isString(ext)) {
  545. ext = showdown.helper.stdExtName(ext);
  546. name = ext;
  547. // LEGACY_SUPPORT CODE
  548. if (showdown.extensions[ext]) {
  549. console.warn('DEPRECATION WARNING: ' + ext + ' is an old extension that uses a deprecated loading method.' +
  550. 'Please inform the developer that the extension should be updated!');
  551. legacyExtensionLoading(showdown.extensions[ext], ext);
  552. return;
  553. // END LEGACY SUPPORT CODE
  554. } else if (!showdown.helper.isUndefined(extensions[ext])) {
  555. ext = extensions[ext];
  556. } else {
  557. throw Error('Extension "' + ext + '" could not be loaded. It was either not found or is not a valid extension.');
  558. }
  559. }
  560. if (typeof ext === 'function') {
  561. ext = ext();
  562. }
  563. if (!showdown.helper.isArray(ext)) {
  564. ext = [ext];
  565. }
  566. var validExt = validate(ext, name);
  567. if (!validExt.valid) {
  568. throw Error(validExt.error);
  569. }
  570. for (var i = 0; i < ext.length; ++i) {
  571. switch (ext[i].type) {
  572. case 'lang':
  573. langExtensions.push(ext[i]);
  574. break;
  575. case 'output':
  576. outputModifiers.push(ext[i]);
  577. break;
  578. default:
  579. // should never reach here
  580. throw Error('Extension loader error: Type unrecognized!!!');
  581. }
  582. }
  583. }
  584. /**
  585. * LEGACY_SUPPORT
  586. * @param {*} ext
  587. * @param {string} name
  588. */
  589. function legacyExtensionLoading(ext, name) {
  590. if (typeof ext === 'function') {
  591. ext = ext(new showdown.Converter());
  592. }
  593. if (!showdown.helper.isArray(ext)) {
  594. ext = [ext];
  595. }
  596. var valid = validate(ext, name);
  597. if (!valid.valid) {
  598. throw Error(valid.error);
  599. }
  600. for (var i = 0; i < ext.length; ++i) {
  601. switch (ext[i].type) {
  602. case 'lang':
  603. langExtensions.push(ext[i]);
  604. break;
  605. case 'output':
  606. outputModifiers.push(ext[i]);
  607. break;
  608. default:// should never reach here
  609. throw Error('Extension loader error: Type unrecognized!!!');
  610. }
  611. }
  612. }
  613. /**
  614. * Converts a markdown string into HTML
  615. * @param {string} text
  616. * @returns {*}
  617. */
  618. this.makeHtml = function (text) {
  619. //check if text is not falsy
  620. if (!text) {
  621. return text;
  622. }
  623. var globals = {
  624. gHtmlBlocks: [],
  625. gUrls: {},
  626. gTitles: {},
  627. gDimensions: {},
  628. gListLevel: 0,
  629. hashLinkCounts: {},
  630. langExtensions: langExtensions,
  631. outputModifiers: outputModifiers,
  632. converter: this
  633. };
  634. // attacklab: Replace ~ with ~T
  635. // This lets us use tilde as an escape char to avoid md5 hashes
  636. // The choice of character is arbitrary; anything that isn't
  637. // magic in Markdown will work.
  638. text = text.replace(/~/g, '~T');
  639. // attacklab: Replace $ with ~D
  640. // RegExp interprets $ as a special character
  641. // when it's in a replacement string
  642. text = text.replace(/\$/g, '~D');
  643. // Standardize line endings
  644. text = text.replace(/\r\n/g, '\n'); // DOS to Unix
  645. text = text.replace(/\r/g, '\n'); // Mac to Unix
  646. // Make sure text begins and ends with a couple of newlines:
  647. text = '\n\n' + text + '\n\n';
  648. // detab
  649. text = showdown.subParser('detab')(text, options, globals);
  650. // stripBlankLines
  651. text = showdown.subParser('stripBlankLines')(text, options, globals);
  652. //run languageExtensions
  653. showdown.helper.forEach(langExtensions, function (ext) {
  654. text = showdown.subParser('runExtension')(ext, text, options, globals);
  655. });
  656. // Run all registered parsers
  657. for (var i = 0; i < parserOrder.length; ++i) {
  658. var name = parserOrder[i];
  659. text = parsers[name](text, options, globals);
  660. }
  661. // attacklab: Restore dollar signs
  662. text = text.replace(/~D/g, '$$');
  663. // attacklab: Restore tildes
  664. text = text.replace(/~T/g, '~');
  665. // Run output modifiers
  666. showdown.helper.forEach(outputModifiers, function (ext) {
  667. text = showdown.subParser('runExtension')(ext, text, options, globals);
  668. });
  669. return text;
  670. };
  671. /**
  672. * Set an option of this Converter instance
  673. * @param {string} key
  674. * @param {*} value
  675. */
  676. this.setOption = function (key, value) {
  677. options[key] = value;
  678. };
  679. /**
  680. * Get the option of this Converter instance
  681. * @param {string} key
  682. * @returns {*}
  683. */
  684. this.getOption = function (key) {
  685. return options[key];
  686. };
  687. /**
  688. * Get the options of this Converter instance
  689. * @returns {{}}
  690. */
  691. this.getOptions = function () {
  692. return options;
  693. };
  694. /**
  695. * Add extension to THIS converter
  696. * @param {{}} extension
  697. * @param {string} [name=null]
  698. */
  699. this.addExtension = function (extension, name) {
  700. name = name || null;
  701. _parseExtension(extension, name);
  702. };
  703. /**
  704. * Use a global registered extension with THIS converter
  705. * @param {string} extensionName Name of the previously registered extension
  706. */
  707. this.useExtension = function (extensionName) {
  708. _parseExtension(extensionName);
  709. };
  710. /**
  711. * Set the flavor THIS converter should use
  712. * @param {string} name
  713. */
  714. this.setFlavor = function (name) {
  715. if (flavor.hasOwnProperty(name)) {
  716. var preset = flavor[name];
  717. for (var option in preset) {
  718. if (preset.hasOwnProperty(option)) {
  719. options[option] = preset[option];
  720. }
  721. }
  722. }
  723. };
  724. /**
  725. * Remove an extension from THIS converter.
  726. * Note: This is a costly operation. It's better to initialize a new converter
  727. * and specify the extensions you wish to use
  728. * @param {Array} extension
  729. */
  730. this.removeExtension = function (extension) {
  731. if (!showdown.helper.isArray(extension)) {
  732. extension = [extension];
  733. }
  734. for (var a = 0; a < extension.length; ++a) {
  735. var ext = extension[a];
  736. for (var i = 0; i < langExtensions.length; ++i) {
  737. if (langExtensions[i] === ext) {
  738. langExtensions[i].splice(i, 1);
  739. }
  740. }
  741. for (var ii = 0; ii < outputModifiers.length; ++i) {
  742. if (outputModifiers[ii] === ext) {
  743. outputModifiers[ii].splice(i, 1);
  744. }
  745. }
  746. }
  747. };
  748. /**
  749. * Get all extension of THIS converter
  750. * @returns {{language: Array, output: Array}}
  751. */
  752. this.getAllExtensions = function () {
  753. return {
  754. language: langExtensions,
  755. output: outputModifiers
  756. };
  757. };
  758. };
  759. /**
  760. * Turn Markdown link shortcuts into XHTML <a> tags.
  761. */
  762. showdown.subParser('anchors', function (text, config, globals) {
  763. 'use strict';
  764. var writeAnchorTag = function (wholeMatch, m1, m2, m3, m4, m5, m6, m7) {
  765. if (showdown.helper.isUndefined(m7)) {
  766. m7 = '';
  767. }
  768. wholeMatch = m1;
  769. var linkText = m2,
  770. linkId = m3.toLowerCase(),
  771. url = m4,
  772. title = m7;
  773. if (!url) {
  774. if (!linkId) {
  775. // lower-case and turn embedded newlines into spaces
  776. linkId = linkText.toLowerCase().replace(/ ?\n/g, ' ');
  777. }
  778. url = '#' + linkId;
  779. if (!showdown.helper.isUndefined(globals.gUrls[linkId])) {
  780. url = globals.gUrls[linkId];
  781. if (!showdown.helper.isUndefined(globals.gTitles[linkId])) {
  782. title = globals.gTitles[linkId];
  783. }
  784. } else {
  785. if (wholeMatch.search(/\(\s*\)$/m) > -1) {
  786. // Special case for explicit empty url
  787. url = '';
  788. } else {
  789. return wholeMatch;
  790. }
  791. }
  792. }
  793. url = showdown.helper.escapeCharacters(url, '*_', false);
  794. var result = '<a href="' + url + '"';
  795. if (title !== '' && title !== null) {
  796. title = title.replace(/"/g, '&quot;');
  797. title = showdown.helper.escapeCharacters(title, '*_', false);
  798. result += ' title="' + title + '"';
  799. }
  800. result += '>' + linkText + '</a>';
  801. return result;
  802. };
  803. // First, handle reference-style links: [link text] [id]
  804. /*
  805. text = text.replace(/
  806. ( // wrap whole match in $1
  807. \[
  808. (
  809. (?:
  810. \[[^\]]*\] // allow brackets nested one level
  811. |
  812. [^\[] // or anything else
  813. )*
  814. )
  815. \]
  816. [ ]? // one optional space
  817. (?:\n[ ]*)? // one optional newline followed by spaces
  818. \[
  819. (.*?) // id = $3
  820. \]
  821. )()()()() // pad remaining backreferences
  822. /g,_DoAnchors_callback);
  823. */
  824. text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g, writeAnchorTag);
  825. //
  826. // Next, inline-style links: [link text](url "optional title")
  827. //
  828. /*
  829. text = text.replace(/
  830. ( // wrap whole match in $1
  831. \[
  832. (
  833. (?:
  834. \[[^\]]*\] // allow brackets nested one level
  835. |
  836. [^\[\]] // or anything else
  837. )
  838. )
  839. \]
  840. \( // literal paren
  841. [ \t]*
  842. () // no id, so leave $3 empty
  843. <?(.*?)>? // href = $4
  844. [ \t]*
  845. ( // $5
  846. (['"]) // quote char = $6
  847. (.*?) // Title = $7
  848. \6 // matching quote
  849. [ \t]* // ignore any spaces/tabs between closing quote and )
  850. )? // title is optional
  851. \)
  852. )
  853. /g,writeAnchorTag);
  854. */
  855. text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\]\([ \t]*()<?(.*?(?:\(.*?\).*?)?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,
  856. writeAnchorTag);
  857. //
  858. // Last, handle reference-style shortcuts: [link text]
  859. // These must come last in case you've also got [link test][1]
  860. // or [link test](/foo)
  861. //
  862. /*
  863. text = text.replace(/
  864. ( // wrap whole match in $1
  865. \[
  866. ([^\[\]]+) // link text = $2; can't contain '[' or ']'
  867. \]
  868. )()()()()() // pad rest of backreferences
  869. /g, writeAnchorTag);
  870. */
  871. text = text.replace(/(\[([^\[\]]+)\])()()()()()/g, writeAnchorTag);
  872. return text;
  873. });
  874. showdown.subParser('autoLinks', function (text, options) {
  875. 'use strict';
  876. //simpleURLRegex = /\b(((https?|ftp|dict):\/\/|www\.)[-.+~:?#@!$&'()*,;=[\]\w]+)\b/gi,
  877. var simpleURLRegex = /\b(((https?|ftp|dict):\/\/|www\.)[^'">\s]+\.[^'">\s]+)(?=\s|$)(?!["<>])/gi,
  878. delimUrlRegex = /<(((https?|ftp|dict):\/\/|www\.)[^'">\s]+)>/gi,
  879. simpleMailRegex = /\b(?:mailto:)?([-.\w]+@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)\b/gi,
  880. delimMailRegex = /<(?:mailto:)?([-.\w]+@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi;
  881. text = text.replace(delimUrlRegex, '<a href=\"$1\">$1</a>');
  882. text = text.replace(delimMailRegex, replaceMail);
  883. //simpleURLRegex = /\b(((https?|ftp|dict):\/\/|www\.)[-.+~:?#@!$&'()*,;=[\]\w]+)\b/gi,
  884. // Email addresses: <address@domain.foo>
  885. if (options.simplifiedAutoLink) {
  886. text = text.replace(simpleURLRegex, '<a href=\"$1\">$1</a>');
  887. text = text.replace(simpleMailRegex, replaceMail);
  888. }
  889. function replaceMail(wholeMatch, m1) {
  890. var unescapedStr = showdown.subParser('unescapeSpecialChars')(m1);
  891. return showdown.subParser('encodeEmailAddress')(unescapedStr);
  892. }
  893. return text;
  894. });
  895. /**
  896. * These are all the transformations that form block-level
  897. * tags like paragraphs, headers, and list items.
  898. */
  899. showdown.subParser('blockGamut', function (text, options, globals) {
  900. 'use strict';
  901. text = showdown.subParser('headers')(text, options, globals);
  902. // Do Horizontal Rules:
  903. var key = showdown.subParser('hashBlock')('<hr />', options, globals);
  904. text = text.replace(/^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$/gm, key);
  905. text = text.replace(/^[ ]{0,2}([ ]?\-[ ]?){3,}[ \t]*$/gm, key);
  906. text = text.replace(/^[ ]{0,2}([ ]?_[ ]?){3,}[ \t]*$/gm, key);
  907. text = showdown.subParser('tables')(text, options, globals);
  908. text = showdown.subParser('lists')(text, options, globals);
  909. text = showdown.subParser('codeBlocks')(text, options, globals);
  910. text = showdown.subParser('blockQuotes')(text, options, globals);
  911. // We already ran _HashHTMLBlocks() before, in Markdown(), but that
  912. // was to escape raw HTML in the original Markdown source. This time,
  913. // we're escaping the markup we've just created, so that we don't wrap
  914. // <p> tags around block-level tags.
  915. text = showdown.subParser('hashHTMLBlocks')(text, options, globals);
  916. text = showdown.subParser('paragraphs')(text, options, globals);
  917. return text;
  918. });
  919. showdown.subParser('blockQuotes', function (text, options, globals) {
  920. 'use strict';
  921. /*
  922. text = text.replace(/
  923. ( // Wrap whole match in $1
  924. (
  925. ^[ \t]*>[ \t]? // '>' at the start of a line
  926. .+\n // rest of the first line
  927. (.+\n)* // subsequent consecutive lines
  928. \n* // blanks
  929. )+
  930. )
  931. /gm, function(){...});
  932. */
  933. text = text.replace(/((^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+)/gm, function (wholeMatch, m1) {
  934. var bq = m1;
  935. // attacklab: hack around Konqueror 3.5.4 bug:
  936. // "----------bug".replace(/^-/g,"") == "bug"
  937. bq = bq.replace(/^[ \t]*>[ \t]?/gm, '~0'); // trim one level of quoting
  938. // attacklab: clean up hack
  939. bq = bq.replace(/~0/g, '');
  940. bq = bq.replace(/^[ \t]+$/gm, ''); // trim whitespace-only lines
  941. bq = showdown.subParser('blockGamut')(bq, options, globals); // recurse
  942. bq = bq.replace(/(^|\n)/g, '$1 ');
  943. // These leading spaces screw with <pre> content, so we need to fix that:
  944. bq = bq.replace(/(\s*<pre>[^\r]+?<\/pre>)/gm, function (wholeMatch, m1) {
  945. var pre = m1;
  946. // attacklab: hack around Konqueror 3.5.4 bug:
  947. pre = pre.replace(/^ /mg, '~0');
  948. pre = pre.replace(/~0/g, '');
  949. return pre;
  950. });
  951. return showdown.subParser('hashBlock')('<blockquote>\n' + bq + '\n</blockquote>', options, globals);
  952. });
  953. return text;
  954. });
  955. /**
  956. * Process Markdown `<pre><code>` blocks.
  957. */
  958. showdown.subParser('codeBlocks', function (text, options, globals) {
  959. 'use strict';
  960. /*
  961. text = text.replace(text,
  962. /(?:\n\n|^)
  963. ( // $1 = the code block -- one or more lines, starting with a space/tab
  964. (?:
  965. (?:[ ]{4}|\t) // Lines must start with a tab or a tab-width of spaces - attacklab: g_tab_width
  966. .*\n+
  967. )+
  968. )
  969. (\n*[ ]{0,3}[^ \t\n]|(?=~0)) // attacklab: g_tab_width
  970. /g,function(){...});
  971. */
  972. // attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
  973. text += '~0';
  974. var pattern = /(?:\n\n|^)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=~0))/g;
  975. text = text.replace(pattern, function (wholeMatch, m1, m2) {
  976. var codeblock = m1,
  977. nextChar = m2,
  978. end = '\n';
  979. codeblock = showdown.subParser('outdent')(codeblock);
  980. codeblock = showdown.subParser('encodeCode')(codeblock);
  981. codeblock = showdown.subParser('detab')(codeblock);
  982. codeblock = codeblock.replace(/^\n+/g, ''); // trim leading newlines
  983. codeblock = codeblock.replace(/\n+$/g, ''); // trim trailing newlines
  984. if (options.omitExtraWLInCodeBlocks) {
  985. end = '';
  986. }
  987. codeblock = '<pre><code>' + codeblock + end + '</code></pre>';
  988. return showdown.subParser('hashBlock')(codeblock, options, globals) + nextChar;
  989. });
  990. // attacklab: strip sentinel
  991. text = text.replace(/~0/, '');
  992. return text;
  993. });
  994. /**
  995. *
  996. * * Backtick quotes are used for <code></code> spans.
  997. *
  998. * * You can use multiple backticks as the delimiters if you want to
  999. * include literal backticks in the code span. So, this input:
  1000. *
  1001. * Just type ``foo `bar` baz`` at the prompt.
  1002. *
  1003. * Will translate to:
  1004. *
  1005. * <p>Just type <code>foo `bar` baz</code> at the prompt.</p>
  1006. *
  1007. * There's no arbitrary limit to the number of backticks you
  1008. * can use as delimters. If you need three consecutive backticks
  1009. * in your code, use four for delimiters, etc.
  1010. *
  1011. * * You can use spaces to get literal backticks at the edges:
  1012. *
  1013. * ... type `` `bar` `` ...
  1014. *
  1015. * Turns to:
  1016. *
  1017. * ... type <code>`bar`</code> ...
  1018. */
  1019. showdown.subParser('codeSpans', function (text) {
  1020. 'use strict';
  1021. //special case -> literal html code tag
  1022. text = text.replace(/(<code[^><]*?>)([^]*?)<\/code>/g, function (wholeMatch, tag, c) {
  1023. c = c.replace(/^([ \t]*)/g, ''); // leading whitespace
  1024. c = c.replace(/[ \t]*$/g, ''); // trailing whitespace
  1025. c = showdown.subParser('encodeCode')(c);
  1026. return tag + c + '</code>';
  1027. });
  1028. /*
  1029. text = text.replace(/
  1030. (^|[^\\]) // Character before opening ` can't be a backslash
  1031. (`+) // $2 = Opening run of `
  1032. ( // $3 = The code block
  1033. [^\r]*?
  1034. [^`] // attacklab: work around lack of lookbehind
  1035. )
  1036. \2 // Matching closer
  1037. (?!`)
  1038. /gm, function(){...});
  1039. */
  1040. text = text.replace(/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/gm,
  1041. function (wholeMatch, m1, m2, m3) {
  1042. var c = m3;
  1043. c = c.replace(/^([ \t]*)/g, ''); // leading whitespace
  1044. c = c.replace(/[ \t]*$/g, ''); // trailing whitespace
  1045. c = showdown.subParser('encodeCode')(c);
  1046. return m1 + '<code>' + c + '</code>';
  1047. }
  1048. );
  1049. return text;
  1050. });
  1051. /**
  1052. * Convert all tabs to spaces
  1053. */
  1054. showdown.subParser('detab', function (text) {
  1055. 'use strict';
  1056. // expand first n-1 tabs
  1057. text = text.replace(/\t(?=\t)/g, ' '); // g_tab_width
  1058. // replace the nth with two sentinels
  1059. text = text.replace(/\t/g, '~A~B');
  1060. // use the sentinel to anchor our regex so it doesn't explode
  1061. text = text.replace(/~B(.+?)~A/g, function (wholeMatch, m1) {
  1062. var leadingText = m1,
  1063. numSpaces = 4 - leadingText.length % 4; // g_tab_width
  1064. // there *must* be a better way to do this:
  1065. for (var i = 0; i < numSpaces; i++) {
  1066. leadingText += ' ';
  1067. }
  1068. return leadingText;
  1069. });
  1070. // clean up sentinels
  1071. text = text.replace(/~A/g, ' '); // g_tab_width
  1072. text = text.replace(/~B/g, '');
  1073. return text;
  1074. });
  1075. /**
  1076. * Smart processing for ampersands and angle brackets that need to be encoded.
  1077. */
  1078. showdown.subParser('encodeAmpsAndAngles', function (text) {
  1079. 'use strict';
  1080. // Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
  1081. // http://bumppo.net/projects/amputator/
  1082. text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g, '&amp;');
  1083. // Encode naked <'s
  1084. text = text.replace(/<(?![a-z\/?\$!])/gi, '&lt;');
  1085. return text;
  1086. });
  1087. /**
  1088. * Returns the string, with after processing the following backslash escape sequences.
  1089. *
  1090. * attacklab: The polite way to do this is with the new escapeCharacters() function:
  1091. *
  1092. * text = escapeCharacters(text,"\\",true);
  1093. * text = escapeCharacters(text,"`*_{}[]()>#+-.!",true);
  1094. *
  1095. * ...but we're sidestepping its use of the (slow) RegExp constructor
  1096. * as an optimization for Firefox. This function gets called a LOT.
  1097. */
  1098. showdown.subParser('encodeBackslashEscapes', function (text) {
  1099. 'use strict';
  1100. text = text.replace(/\\(\\)/g, showdown.helper.escapeCharactersCallback);
  1101. text = text.replace(/\\([`*_{}\[\]()>#+-.!])/g, showdown.helper.escapeCharactersCallback);
  1102. return text;
  1103. });
  1104. /**
  1105. * Encode/escape certain characters inside Markdown code runs.
  1106. * The point is that in code, these characters are literals,
  1107. * and lose their special Markdown meanings.
  1108. */
  1109. showdown.subParser('encodeCode', function (text) {
  1110. 'use strict';
  1111. // Encode all ampersands; HTML entities are not
  1112. // entities within a Markdown code span.
  1113. text = text.replace(/&/g, '&amp;');
  1114. // Do the angle bracket song and dance:
  1115. text = text.replace(/</g, '&lt;');
  1116. text = text.replace(/>/g, '&gt;');
  1117. // Now, escape characters that are magic in Markdown:
  1118. text = showdown.helper.escapeCharacters(text, '*_{}[]\\', false);
  1119. // jj the line above breaks this:
  1120. //---
  1121. //* Item
  1122. // 1. Subitem
  1123. // special char: *
  1124. // ---
  1125. return text;
  1126. });
  1127. /**
  1128. * Input: an email address, e.g. "foo@example.com"
  1129. *
  1130. * Output: the email address as a mailto link, with each character
  1131. * of the address encoded as either a decimal or hex entity, in
  1132. * the hopes of foiling most address harvesting spam bots. E.g.:
  1133. *
  1134. * <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101;
  1135. * x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111;
  1136. * &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a>
  1137. *
  1138. * Based on a filter by Matthew Wickline, posted to the BBEdit-Talk
  1139. * mailing list: <http://tinyurl.com/yu7ue>
  1140. *
  1141. */
  1142. showdown.subParser('encodeEmailAddress', function (addr) {
  1143. 'use strict';
  1144. var encode = [
  1145. function (ch) {
  1146. return '&#' + ch.charCodeAt(0) + ';';
  1147. },
  1148. function (ch) {
  1149. return '&#x' + ch.charCodeAt(0).toString(16) + ';';
  1150. },
  1151. function (ch) {
  1152. return ch;
  1153. }
  1154. ];
  1155. addr = 'mailto:' + addr;
  1156. addr = addr.replace(/./g, function (ch) {
  1157. if (ch === '@') {
  1158. // this *must* be encoded. I insist.
  1159. ch = encode[Math.floor(Math.random() * 2)](ch);
  1160. } else if (ch !== ':') {
  1161. // leave ':' alone (to spot mailto: later)
  1162. var r = Math.random();
  1163. // roughly 10% raw, 45% hex, 45% dec
  1164. ch = (
  1165. r > 0.9 ? encode[2](ch) : r > 0.45 ? encode[1](ch) : encode[0](ch)
  1166. );
  1167. }
  1168. return ch;
  1169. });
  1170. addr = '<a href="' + addr + '">' + addr + '</a>';
  1171. addr = addr.replace(/">.+:/g, '">'); // strip the mailto: from the visible part
  1172. return addr;
  1173. });
  1174. /**
  1175. * Within tags -- meaning between < and > -- encode [\ ` * _] so they
  1176. * don't conflict with their use in Markdown for code, italics and strong.
  1177. */
  1178. showdown.subParser('escapeSpecialCharsWithinTagAttributes', function (text) {
  1179. 'use strict';
  1180. // Build a regex to find HTML tags and comments. See Friedl's
  1181. // "Mastering Regular Expressions", 2nd Ed., pp. 200-201.
  1182. var regex = /(<[a-z\/!$]("[^"]*"|'[^']*'|[^'">])*>|<!(--.*?--\s*)+>)/gi;
  1183. text = text.replace(regex, function (wholeMatch) {
  1184. var tag = wholeMatch.replace(/(.)<\/?code>(?=.)/g, '$1`');
  1185. tag = showdown.helper.escapeCharacters(tag, '\\`*_', false);
  1186. return tag;
  1187. });
  1188. return text;
  1189. });
  1190. /**
  1191. * Handle github codeblocks prior to running HashHTML so that
  1192. * HTML contained within the codeblock gets escaped properly
  1193. * Example:
  1194. * ```ruby
  1195. * def hello_world(x)
  1196. * puts "Hello, #{x}"
  1197. * end
  1198. * ```
  1199. */
  1200. showdown.subParser('githubCodeBlocks', function (text, options, globals) {
  1201. 'use strict';
  1202. // early exit if option is not enabled
  1203. if (!options.ghCodeBlocks) {
  1204. return text;
  1205. }
  1206. text += '~0';
  1207. text = text.replace(/(?:^|\n)```(.*)\n([\s\S]*?)\n```/g, function (wholeMatch, language, codeblock) {
  1208. var end = (options.omitExtraWLInCodeBlocks) ? '' : '\n';
  1209. codeblock = showdown.subParser('encodeCode')(codeblock);
  1210. codeblock = showdown.subParser('detab')(codeblock);
  1211. codeblock = codeblock.replace(/^\n+/g, ''); // trim leading newlines
  1212. codeblock = codeblock.replace(/\n+$/g, ''); // trim trailing whitespace
  1213. codeblock = '<pre><code' + (language ? ' class="' + language + ' language-' + language + '"' : '') + '>' + codeblock + end + '</code></pre>';
  1214. return showdown.subParser('hashBlock')(codeblock, options, globals);
  1215. });
  1216. // attacklab: strip sentinel
  1217. text = text.replace(/~0/, '');
  1218. return text;
  1219. });
  1220. showdown.subParser('hashBlock', function (text, options, globals) {
  1221. 'use strict';
  1222. text = text.replace(/(^\n+|\n+$)/g, '');
  1223. return '\n\n~K' + (globals.gHtmlBlocks.push(text) - 1) + 'K\n\n';
  1224. });
  1225. showdown.subParser('hashElement', function (text, options, globals) {
  1226. 'use strict';
  1227. return function (wholeMatch, m1) {
  1228. var blockText = m1;
  1229. // Undo double lines
  1230. blockText = blockText.replace(/\n\n/g, '\n');
  1231. blockText = blockText.replace(/^\n/, '');
  1232. // strip trailing blank lines
  1233. blockText = blockText.replace(/\n+$/g, '');
  1234. // Replace the element text with a marker ("~KxK" where x is its key)
  1235. blockText = '\n\n~K' + (globals.gHtmlBlocks.push(blockText) - 1) + 'K\n\n';
  1236. return blockText;
  1237. };
  1238. });
  1239. showdown.subParser('hashHTMLBlocks', function (text, options, globals) {
  1240. 'use strict';
  1241. // attacklab: Double up blank lines to reduce lookaround
  1242. text = text.replace(/\n/g, '\n\n');
  1243. // Hashify HTML blocks:
  1244. // We only want to do this for block-level HTML tags, such as headers,
  1245. // lists, and tables. That's because we still want to wrap <p>s around
  1246. // "paragraphs" that are wrapped in non-block-level tags, such as anchors,
  1247. // phrase emphasis, and spans. The list of tags we're looking for is
  1248. // hard-coded:
  1249. //var block_tags_a =
  1250. // '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';
  1251. // var block_tags_b =
  1252. // 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|style|section|header|footer|nav|article|aside';
  1253. // First, look for nested blocks, e.g.:
  1254. // <div>
  1255. // <div>
  1256. // tags for inner block must be indented.
  1257. // </div>
  1258. // </div>
  1259. //
  1260. // The outermost tags must start at the left margin for this to match, and
  1261. // the inner nested divs must be indented.
  1262. // We need to do this before the next, more liberal match, because the next
  1263. // match will start at the first `<div>` and stop at the first `</div>`.
  1264. // attacklab: This regex can be expensive when it fails.
  1265. /*
  1266. var text = text.replace(/
  1267. ( // save in $1
  1268. ^ // start of line (with /m)
  1269. <($block_tags_a) // start tag = $2
  1270. \b // word break
  1271. // attacklab: hack around khtml/pcre bug...
  1272. [^\r]*?\n // any number of lines, minimally matching
  1273. </\2> // the matching end tag
  1274. [ \t]* // trailing spaces/tabs
  1275. (?=\n+) // followed by a newline
  1276. ) // attacklab: there are sentinel newlines at end of document
  1277. /gm,function(){...}};
  1278. */
  1279. 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,
  1280. showdown.subParser('hashElement')(text, options, globals));
  1281. //
  1282. // Now match more liberally, simply from `\n<tag>` to `</tag>\n`
  1283. //
  1284. /*
  1285. var text = text.replace(/
  1286. ( // save in $1
  1287. ^ // start of line (with /m)
  1288. <($block_tags_b) // start tag = $2
  1289. \b // word break
  1290. // attacklab: hack around khtml/pcre bug...
  1291. [^\r]*? // any number of lines, minimally matching
  1292. </\2> // the matching end tag
  1293. [ \t]* // trailing spaces/tabs
  1294. (?=\n+) // followed by a newline
  1295. ) // attacklab: there are sentinel newlines at end of document
  1296. /gm,function(){...}};
  1297. */
  1298. 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,
  1299. showdown.subParser('hashElement')(text, options, globals));
  1300. // Special case just for <hr />. It was easier to make a special case than
  1301. // to make the other regex more complicated.
  1302. /*
  1303. text = text.replace(/
  1304. ( // save in $1
  1305. \n\n // Starting after a blank line
  1306. [ ]{0,3}
  1307. (<(hr) // start tag = $2
  1308. \b // word break
  1309. ([^<>])*? //
  1310. \/?>) // the matching end tag
  1311. [ \t]*
  1312. (?=\n{2,}) // followed by a blank line
  1313. )
  1314. /g,showdown.subParser('hashElement')(text, options, globals));
  1315. */
  1316. text = text.replace(/(\n[ ]{0,3}(<(hr)\b([^<>])*?\/?>)[ \t]*(?=\n{2,}))/g,
  1317. showdown.subParser('hashElement')(text, options, globals));
  1318. // Special case for standalone HTML comments:
  1319. /*
  1320. text = text.replace(/
  1321. ( // save in $1
  1322. \n\n // Starting after a blank line
  1323. [ ]{0,3} // attacklab: g_tab_width - 1
  1324. <!
  1325. (--[^\r]*?--\s*)+
  1326. >
  1327. [ \t]*
  1328. (?=\n{2,}) // followed by a blank line
  1329. )
  1330. /g,showdown.subParser('hashElement')(text, options, globals));
  1331. */
  1332. text = text.replace(/(\n\n[ ]{0,3}<!(--[^\r]*?--\s*)+>[ \t]*(?=\n{2,}))/g,
  1333. showdown.subParser('hashElement')(text, options, globals));
  1334. // PHP and ASP-style processor instructions (<?...?> and <%...%>)
  1335. /*
  1336. text = text.replace(/
  1337. (?:
  1338. \n\n // Starting after a blank line
  1339. )
  1340. ( // save in $1
  1341. [ ]{0,3} // attacklab: g_tab_width - 1
  1342. (?:
  1343. <([?%]) // $2
  1344. [^\r]*?
  1345. \2>
  1346. )
  1347. [ \t]*
  1348. (?=\n{2,}) // followed by a blank line
  1349. )
  1350. /g,showdown.subParser('hashElement')(text, options, globals));
  1351. */
  1352. text = text.replace(/(?:\n\n)([ ]{0,3}(?:<([?%])[^\r]*?\2>)[ \t]*(?=\n{2,}))/g,
  1353. showdown.subParser('hashElement')(text, options, globals));
  1354. // attacklab: Undo double lines (see comment at top of this function)
  1355. text = text.replace(/\n\n/g, '\n');
  1356. return text;
  1357. });
  1358. showdown.subParser('headers', function (text, options, globals) {
  1359. 'use strict';
  1360. var prefixHeader = options.prefixHeaderId,
  1361. headerLevelStart = (isNaN(parseInt(options.headerLevelStart))) ? 1 : parseInt(options.headerLevelStart),
  1362. // Set text-style headers:
  1363. // Header 1
  1364. // ========
  1365. //
  1366. // Header 2
  1367. // --------
  1368. //
  1369. setextRegexH1 = (options.smoothLivePreview) ? /^(.+)[ \t]*\n={2,}[ \t]*\n+/gm : /^(.+)[ \t]*\n=+[ \t]*\n+/gm,
  1370. setextRegexH2 = (options.smoothLivePreview) ? /^(.+)[ \t]*\n-{2,}[ \t]*\n+/gm : /^(.+)[ \t]*\n-+[ \t]*\n+/gm;
  1371. text = text.replace(setextRegexH1, function (wholeMatch, m1) {
  1372. var spanGamut = showdown.subParser('spanGamut')(m1, options, globals),
  1373. hID = (options.noHeaderId) ? '' : ' id="' + headerId(m1) + '"',
  1374. hLevel = headerLevelStart,
  1375. hashBlock = '<h' + hLevel + hID + '>' + spanGamut + '</h' + hLevel + '>';
  1376. return showdown.subParser('hashBlock')(hashBlock, options, globals);
  1377. });
  1378. text = text.replace(setextRegexH2, function (matchFound, m1) {
  1379. var spanGamut = showdown.subParser('spanGamut')(m1, options, globals),
  1380. hID = (options.noHeaderId) ? '' : ' id="' + headerId(m1) + '"',
  1381. hLevel = headerLevelStart + 1,
  1382. hashBlock = '<h' + hLevel + hID + '>' + spanGamut + '</h' + hLevel + '>';
  1383. return showdown.subParser('hashBlock')(hashBlock, options, globals);
  1384. });
  1385. // atx-style headers:
  1386. // # Header 1
  1387. // ## Header 2
  1388. // ## Header 2 with closing hashes ##
  1389. // ...
  1390. // ###### Header 6
  1391. //
  1392. text = text.replace(/^(#{1,6})[ \t]*(.+?)[ \t]*#*\n+/gm, function (wholeMatch, m1, m2) {
  1393. var span = showdown.subParser('spanGamut')(m2, options, globals),
  1394. hID = (options.noHeaderId) ? '' : ' id="' + headerId(m2) + '"',
  1395. hLevel = headerLevelStart - 1 + m1.length,
  1396. header = '<h' + hLevel + hID + '>' + span + '</h' + hLevel + '>';
  1397. return showdown.subParser('hashBlock')(header, options, globals);
  1398. });
  1399. function headerId(m) {
  1400. var title, escapedId = m.replace(/[^\w]/g, '').toLowerCase();
  1401. if (globals.hashLinkCounts[escapedId]) {
  1402. title = escapedId + '-' + (globals.hashLinkCounts[escapedId]++);
  1403. } else {
  1404. title = escapedId;
  1405. globals.hashLinkCounts[escapedId] = 1;
  1406. }
  1407. // Prefix id to prevent causing inadvertent pre-existing style matches.
  1408. if (prefixHeader === true) {
  1409. prefixHeader = 'section';
  1410. }
  1411. if (showdown.helper.isString(prefixHeader)) {
  1412. return prefixHeader + title;
  1413. }
  1414. return title;
  1415. }
  1416. return text;
  1417. });
  1418. /**
  1419. * Turn Markdown image shortcuts into <img> tags.
  1420. */
  1421. showdown.subParser('images', function (text, options, globals) {
  1422. 'use strict';
  1423. var inlineRegExp = /!\[(.*?)]\s?\([ \t]*()<?(\S+?)>?(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*(?:(['"])(.*?)\6[ \t]*)?\)/g,
  1424. referenceRegExp = /!\[(.*?)][ ]?(?:\n[ ]*)?\[(.*?)]()()()()()/g;
  1425. function writeImageTag (wholeMatch, altText, linkId, url, width, height, m5, title) {
  1426. var gUrls = globals.gUrls,
  1427. gTitles = globals.gTitles,
  1428. gDims = globals.gDimensions;
  1429. linkId = linkId.toLowerCase();
  1430. if (!title) {
  1431. title = '';
  1432. }
  1433. if (url === '' || url === null) {
  1434. if (linkId === '' || linkId === null) {
  1435. // lower-case and turn embedded newlines into spaces
  1436. linkId = altText.toLowerCase().replace(/ ?\n/g, ' ');
  1437. }
  1438. url = '#' + linkId;
  1439. if (!showdown.helper.isUndefined(gUrls[linkId])) {
  1440. url = gUrls[linkId];
  1441. if (!showdown.helper.isUndefined(gTitles[linkId])) {
  1442. title = gTitles[linkId];
  1443. }
  1444. if (!showdown.helper.isUndefined(gDims[linkId])) {
  1445. width = gDims[linkId].width;
  1446. height = gDims[linkId].height;
  1447. }
  1448. } else {
  1449. return wholeMatch;
  1450. }
  1451. }
  1452. altText = altText.replace(/"/g, '&quot;');
  1453. altText = showdown.helper.escapeCharacters(altText, '*_', false);
  1454. url = showdown.helper.escapeCharacters(url, '*_', false);
  1455. var result = '<img src="' + url + '" alt="' + altText + '"';
  1456. if (title) {
  1457. title = title.replace(/"/g, '&quot;');
  1458. title = showdown.helper.escapeCharacters(title, '*_', false);
  1459. result += ' title="' + title + '"';
  1460. }
  1461. if (width && height) {
  1462. width = (width === '*') ? 'auto' : width;
  1463. height = (height === '*') ? 'auto' : height;
  1464. result += ' width="' + width + '"';
  1465. result += ' height="' + height + '"';
  1466. }
  1467. result += ' />';
  1468. return result;
  1469. }
  1470. // First, handle reference-style labeled images: ![alt text][id]
  1471. text = text.replace(referenceRegExp, writeImageTag);
  1472. // Next, handle inline images: ![alt text](url =<width>x<height> "optional title")
  1473. text = text.replace(inlineRegExp, writeImageTag);
  1474. return text;
  1475. });
  1476. showdown.subParser('italicsAndBold', function (text, options) {
  1477. 'use strict';
  1478. if (options.literalMidWordUnderscores) {
  1479. //underscores
  1480. // Since we are consuming a \s character, we need to add it
  1481. text = text.replace(/(^|\s|>|\b)__(?=\S)([^]+?)__(?=\b|<|\s|$)/gm, '$1<strong>$2</strong>');
  1482. text = text.replace(/(^|\s|>|\b)_(?=\S)([^]+?)_(?=\b|<|\s|$)/gm, '$1<em>$2</em>');
  1483. //asterisks
  1484. text = text.replace(/\*\*(?=\S)([^]+?)\*\*/g, '<strong>$1</strong>');
  1485. text = text.replace(/\*(?=\S)([^]+?)\*/g, '<em>$1</em>');
  1486. } else {
  1487. // <strong> must go first:
  1488. text = text.replace(/(\*\*|__)(?=\S)([^\r]*?\S[*_]*)\1/g, '<strong>$2</strong>');
  1489. text = text.replace(/(\*|_)(?=\S)([^\r]*?\S)\1/g, '<em>$2</em>');
  1490. }
  1491. return text;
  1492. });
  1493. /**
  1494. * Form HTML ordered (numbered) and unordered (bulleted) lists.
  1495. */
  1496. showdown.subParser('lists', function (text, options, globals) {
  1497. 'use strict';
  1498. /**
  1499. * Process the contents of a single ordered or unordered list, splitting it
  1500. * into individual list items.
  1501. * @param {string} listStr
  1502. * @returns {string}
  1503. */
  1504. function processListItems (listStr, trimTrailing) {
  1505. // The $g_list_level global keeps track of when we're inside a list.
  1506. // Each time we enter a list, we increment it; when we leave a list,
  1507. // we decrement. If it's zero, we're not in a list anymore.
  1508. //
  1509. // We do this because when we're not inside a list, we want to treat
  1510. // something like this:
  1511. //
  1512. // I recommend upgrading to version
  1513. // 8. Oops, now this line is treated
  1514. // as a sub-list.
  1515. //
  1516. // As a single paragraph, despite the fact that the second line starts
  1517. // with a digit-period-space sequence.
  1518. //
  1519. // Whereas when we're inside a list (or sub-list), that line will be
  1520. // treated as the start of a sub-list. What a kludge, huh? This is
  1521. // an aspect of Markdown's syntax that's hard to parse perfectly
  1522. // without resorting to mind-reading. Perhaps the solution is to
  1523. // change the syntax rules such that sub-lists must start with a
  1524. // starting cardinal number; e.g. "1." or "a.".
  1525. globals.gListLevel++;
  1526. // trim trailing blank lines:
  1527. listStr = listStr.replace(/\n{2,}$/, '\n');
  1528. // attacklab: add sentinel to emulate \z
  1529. listStr += '~0';
  1530. var rgx = /(\n)?(^[ \t]*)([*+-]|\d+[.])[ \t]+((\[(x| )?])?[ \t]*[^\r]+?(\n{1,2}))(?=\n*(~0|\2([*+-]|\d+[.])[ \t]+))/gm,
  1531. isParagraphed = (/\n[ \t]*\n(?!~0)/.test(listStr));
  1532. listStr = listStr.replace(rgx, function (wholeMatch, m1, m2, m3, m4, taskbtn, checked) {
  1533. checked = (checked && checked.trim() !== '');
  1534. var item = showdown.subParser('outdent')(m4, options, globals),
  1535. bulletStyle = '';
  1536. // Support for github tasklists
  1537. if (taskbtn && options.tasklists) {
  1538. bulletStyle = ' class="task-list-item" style="list-style-type: none;"';
  1539. item = item.replace(/^[ \t]*\[(x| )?]/m, function () {
  1540. var otp = '<input type="checkbox" disabled style="margin: 0px 0.35em 0.25em -1.6em; vertical-align: middle;"';
  1541. if (checked) {
  1542. otp += ' checked';
  1543. }
  1544. otp += '>';
  1545. return otp;
  1546. });
  1547. }
  1548. // m1 - Leading line or
  1549. // Has a double return (multi paragraph) or
  1550. // Has sublist
  1551. if (m1 || (item.search(/\n{2,}/) > -1)) {
  1552. item = showdown.subParser('githubCodeBlocks')(item, options, globals);
  1553. item = showdown.subParser('blockGamut')(item, options, globals);
  1554. } else {
  1555. // Recursion for sub-lists:
  1556. item = showdown.subParser('lists')(item, options, globals);
  1557. item = item.replace(/\n$/, ''); // chomp(item)
  1558. if (isParagraphed) {
  1559. item = showdown.subParser('paragraphs')(item, options, globals);
  1560. } else {
  1561. item = showdown.subParser('spanGamut')(item, options, globals);
  1562. }
  1563. }
  1564. item = '\n<li' + bulletStyle + '>' + item + '</li>\n';
  1565. return item;
  1566. });
  1567. // attacklab: strip sentinel
  1568. listStr = listStr.replace(/~0/g, '');
  1569. globals.gListLevel--;
  1570. if (trimTrailing) {
  1571. listStr = listStr.replace(/\s+$/, '');
  1572. }
  1573. return listStr;
  1574. }
  1575. /**
  1576. * Check and parse consecutive lists (better fix for issue #142)
  1577. * @param {string} list
  1578. * @param {string} listType
  1579. * @returns {string}
  1580. */
  1581. function parseConsecutiveLists(list, listType, trimTrailing) {
  1582. // check if we caught 2 or more consecutive lists by mistake
  1583. // we use the counterRgx, meaning if listType is UL we look for UL and vice versa
  1584. var counterRxg = (listType === 'ul') ? /^ {0,2}\d+\.[ \t]/gm : /^ {0,2}[*+-][ \t]/gm,
  1585. subLists = [],
  1586. result = '';
  1587. if (list.search(counterRxg) !== -1) {
  1588. (function parseCL(txt) {
  1589. var pos = txt.search(counterRxg);
  1590. if (pos !== -1) {
  1591. // slice
  1592. result += '\n\n<' + listType + '>' + processListItems(txt.slice(0, pos), !!trimTrailing) + '</' + listType + '>\n\n';
  1593. // invert counterType and listType
  1594. listType = (listType === 'ul') ? 'ol' : 'ul';
  1595. counterRxg = (listType === 'ul') ? /^ {0,2}\d+\.[ \t]/gm : /^ {0,2}[*+-][ \t]/gm;
  1596. //recurse
  1597. parseCL(txt.slice(pos));
  1598. } else {
  1599. result += '\n\n<' + listType + '>' + processListItems(txt, !!trimTrailing) + '</' + listType + '>\n\n';
  1600. }
  1601. })(list);
  1602. for (var i = 0; i < subLists.length; ++i) {
  1603. }
  1604. } else {
  1605. result = '\n\n<' + listType + '>' + processListItems(list, !!trimTrailing) + '</' + listType + '>\n\n';
  1606. }
  1607. return result;
  1608. }
  1609. // attacklab: add sentinel to hack around khtml/safari bug:
  1610. // http://bugs.webkit.org/show_bug.cgi?id=11231
  1611. text += '~0';
  1612. // Re-usable pattern to match any entire ul or ol list:
  1613. var wholeList = /^(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm;
  1614. if (globals.gListLevel) {
  1615. text = text.replace(wholeList, function (wholeMatch, list, m2) {
  1616. var listType = (m2.search(/[*+-]/g) > -1) ? 'ul' : 'ol';
  1617. return parseConsecutiveLists(list, listType, true);
  1618. });
  1619. } else {
  1620. wholeList = /(\n\n|^\n?)(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm;
  1621. //wholeList = /(\n\n|^\n?)( {0,3}([*+-]|\d+\.)[ \t]+[\s\S]+?)(?=(~0)|(\n\n(?!\t| {2,}| {0,3}([*+-]|\d+\.)[ \t])))/g;
  1622. text = text.replace(wholeList, function (wholeMatch, m1, list, m3) {
  1623. var listType = (m3.search(/[*+-]/g) > -1) ? 'ul' : 'ol';
  1624. return parseConsecutiveLists(list, listType);
  1625. });
  1626. }
  1627. // attacklab: strip sentinel
  1628. text = text.replace(/~0/, '');
  1629. return text;
  1630. });
  1631. /**
  1632. * Remove one level of line-leading tabs or spaces
  1633. */
  1634. showdown.subParser('outdent', function (text) {
  1635. 'use strict';
  1636. // attacklab: hack around Konqueror 3.5.4 bug:
  1637. // "----------bug".replace(/^-/g,"") == "bug"
  1638. text = text.replace(/^(\t|[ ]{1,4})/gm, '~0'); // attacklab: g_tab_width
  1639. // attacklab: clean up hack
  1640. text = text.replace(/~0/g, '');
  1641. return text;
  1642. });
  1643. /**
  1644. *
  1645. */
  1646. showdown.subParser('paragraphs', function (text, options, globals) {
  1647. 'use strict';
  1648. // Strip leading and trailing lines:
  1649. text = text.replace(/^\n+/g, '');
  1650. text = text.replace(/\n+$/g, '');
  1651. var grafs = text.split(/\n{2,}/g),
  1652. grafsOut = [],
  1653. end = grafs.length; // Wrap <p> tags
  1654. for (var i = 0; i < end; i++) {
  1655. var str = grafs[i];
  1656. // if this is an HTML marker, copy it
  1657. if (str.search(/~K(\d+)K/g) >= 0) {
  1658. grafsOut.push(str);
  1659. } else if (str.search(/\S/) >= 0) {
  1660. str = showdown.subParser('spanGamut')(str, options, globals);
  1661. str = str.replace(/^([ \t]*)/g, '<p>');
  1662. str += '</p>';
  1663. grafsOut.push(str);
  1664. }
  1665. }
  1666. /** Unhashify HTML blocks */
  1667. end = grafsOut.length;
  1668. for (i = 0; i < end; i++) {
  1669. // if this is a marker for an html block...
  1670. while (grafsOut[i].search(/~K(\d+)K/) >= 0) {
  1671. var blockText = globals.gHtmlBlocks[RegExp.$1];
  1672. blockText = blockText.replace(/\$/g, '$$$$'); // Escape any dollar signs
  1673. grafsOut[i] = grafsOut[i].replace(/~K\d+K/, blockText);
  1674. }
  1675. }
  1676. return grafsOut.join('\n\n');
  1677. });
  1678. /**
  1679. * Run extension
  1680. */
  1681. showdown.subParser('runExtension', function (ext, text, options, globals) {
  1682. 'use strict';
  1683. if (ext.filter) {
  1684. text = ext.filter(text, globals.converter, options);
  1685. } else if (ext.regex) {
  1686. // TODO remove this when old extension loading mechanism is deprecated
  1687. var re = ext.regex;
  1688. if (!re instanceof RegExp) {
  1689. re = new RegExp(re, 'g');
  1690. }
  1691. text = text.replace(re, ext.replace);
  1692. }
  1693. return text;
  1694. });
  1695. /**
  1696. * These are all the transformations that occur *within* block-level
  1697. * tags like paragraphs, headers, and list items.
  1698. */
  1699. showdown.subParser('spanGamut', function (text, options, globals) {
  1700. 'use strict';
  1701. text = showdown.subParser('codeSpans')(text, options, globals);
  1702. text = showdown.subParser('escapeSpecialCharsWithinTagAttributes')(text, options, globals);
  1703. text = showdown.subParser('encodeBackslashEscapes')(text, options, globals);
  1704. // Process anchor and image tags. Images must come first,
  1705. // because ![foo][f] looks like an anchor.
  1706. text = showdown.subParser('images')(text, options, globals);
  1707. text = showdown.subParser('anchors')(text, options, globals);
  1708. // Make links out of things like `<http://example.com/>`
  1709. // Must come after _DoAnchors(), because you can use < and >
  1710. // delimiters in inline links like [this](<url>).
  1711. text = showdown.subParser('autoLinks')(text, options, globals);
  1712. text = showdown.subParser('encodeAmpsAndAngles')(text, options, globals);
  1713. text = showdown.subParser('italicsAndBold')(text, options, globals);
  1714. text = showdown.subParser('strikethrough')(text, options, globals);
  1715. // Do hard breaks:
  1716. text = text.replace(/ +\n/g, ' <br />\n');
  1717. return text;
  1718. });
  1719. showdown.subParser('strikethrough', function (text, options) {
  1720. 'use strict';
  1721. if (options.strikethrough) {
  1722. text = text.replace(/(?:~T){2}([^~]+)(?:~T){2}/g, '<del>$1</del>');
  1723. }
  1724. return text;
  1725. });
  1726. /**
  1727. * Strip any lines consisting only of spaces and tabs.
  1728. * This makes subsequent regexs easier to write, because we can
  1729. * match consecutive blank lines with /\n+/ instead of something
  1730. * contorted like /[ \t]*\n+/
  1731. */
  1732. showdown.subParser('stripBlankLines', function (text) {
  1733. 'use strict';
  1734. return text.replace(/^[ \t]+$/mg, '');
  1735. });
  1736. /**
  1737. * Strips link definitions from text, stores the URLs and titles in
  1738. * hash references.
  1739. * Link defs are in the form: ^[id]: url "optional title"
  1740. *
  1741. * ^[ ]{0,3}\[(.+)\]: // id = $1 attacklab: g_tab_width - 1
  1742. * [ \t]*
  1743. * \n? // maybe *one* newline
  1744. * [ \t]*
  1745. * <?(\S+?)>? // url = $2
  1746. * [ \t]*
  1747. * \n? // maybe one newline
  1748. * [ \t]*
  1749. * (?:
  1750. * (\n*) // any lines skipped = $3 attacklab: lookbehind removed
  1751. * ["(]
  1752. * (.+?) // title = $4
  1753. * [")]
  1754. * [ \t]*
  1755. * )? // title is optional
  1756. * (?:\n+|$)
  1757. * /gm,
  1758. * function(){...});
  1759. *
  1760. */
  1761. showdown.subParser('stripLinkDefinitions', function (text, options, globals) {
  1762. 'use strict';
  1763. 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;
  1764. // attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
  1765. text += '~0';
  1766. text = text.replace(regex, function (wholeMatch, linkId, url, width, height, blankLines, title) {
  1767. linkId = linkId.toLowerCase();
  1768. globals.gUrls[linkId] = showdown.subParser('encodeAmpsAndAngles')(url); // Link IDs are case-insensitive
  1769. if (blankLines) {
  1770. // Oops, found blank lines, so it's not a title.
  1771. // Put back the parenthetical statement we stole.
  1772. return blankLines + title;
  1773. } else {
  1774. if (title) {
  1775. globals.gTitles[linkId] = title.replace(/"|'/g, '&quot;');
  1776. }
  1777. if (options.parseImgDimensions && width && height) {
  1778. globals.gDimensions[linkId] = {
  1779. width: width,
  1780. height: height
  1781. };
  1782. }
  1783. }
  1784. // Completely remove the definition from the text
  1785. return '';
  1786. });
  1787. // attacklab: strip sentinel
  1788. text = text.replace(/~0/, '');
  1789. return text;
  1790. });
  1791. showdown.subParser('tables', function (text, options, globals) {
  1792. 'use strict';
  1793. var table = function () {
  1794. var tables = {},
  1795. filter;
  1796. tables.th = function (header, style) {
  1797. var id = '';
  1798. header = header.trim();
  1799. if (header === '') {
  1800. return '';
  1801. }
  1802. if (options.tableHeaderId) {
  1803. id = ' id="' + header.replace(/ /g, '_').toLowerCase() + '"';
  1804. }
  1805. header = showdown.subParser('spanGamut')(header, options, globals);
  1806. if (!style || style.trim() === '') {
  1807. style = '';
  1808. } else {
  1809. style = ' style="' + style + '"';
  1810. }
  1811. return '<th' + id + style + '>' + header + '</th>';
  1812. };
  1813. tables.td = function (cell, style) {
  1814. var subText = showdown.subParser('spanGamut')(cell.trim(), options, globals);
  1815. if (!style || style.trim() === '') {
  1816. style = '';
  1817. } else {
  1818. style = ' style="' + style + '"';
  1819. }
  1820. return '<td' + style + '>' + subText + '</td>';
  1821. };
  1822. tables.ths = function () {
  1823. var out = '',
  1824. i = 0,
  1825. hs = [].slice.apply(arguments[0]),
  1826. style = [].slice.apply(arguments[1]);
  1827. for (i; i < hs.length; i += 1) {
  1828. out += tables.th(hs[i], style[i]) + '\n';
  1829. }
  1830. return out;
  1831. };
  1832. tables.tds = function () {
  1833. var out = '',
  1834. i = 0,
  1835. ds = [].slice.apply(arguments[0]),
  1836. style = [].slice.apply(arguments[1]);
  1837. for (i; i < ds.length; i += 1) {
  1838. out += tables.td(ds[i], style[i]) + '\n';
  1839. }
  1840. return out;
  1841. };
  1842. tables.thead = function () {
  1843. var out,
  1844. hs = [].slice.apply(arguments[0]),
  1845. style = [].slice.apply(arguments[1]);
  1846. out = '<thead>\n';
  1847. out += '<tr>\n';
  1848. out += tables.ths.apply(this, [hs, style]);
  1849. out += '</tr>\n';
  1850. out += '</thead>\n';
  1851. return out;
  1852. };
  1853. tables.tr = function () {
  1854. var out,
  1855. cs = [].slice.apply(arguments[0]),
  1856. style = [].slice.apply(arguments[1]);
  1857. out = '<tr>\n';
  1858. out += tables.tds.apply(this, [cs, style]);
  1859. out += '</tr>\n';
  1860. return out;
  1861. };
  1862. filter = function (text) {
  1863. var i = 0,
  1864. lines = text.split('\n'),
  1865. line,
  1866. hs,
  1867. out = [];
  1868. for (i; i < lines.length; i += 1) {
  1869. line = lines[i];
  1870. // looks like a table heading
  1871. if (line.trim().match(/^[|].*[|]$/)) {
  1872. line = line.trim();
  1873. var tbl = [],
  1874. align = lines[i + 1].trim(),
  1875. styles = [],
  1876. j = 0;
  1877. if (align.match(/^[|][-=|: ]+[|]$/)) {
  1878. styles = align.substring(1, align.length - 1).split('|');
  1879. for (j = 0; j < styles.length; ++j) {
  1880. styles[j] = styles[j].trim();
  1881. if (styles[j].match(/^[:][-=| ]+[:]$/)) {
  1882. styles[j] = 'text-align:center;';
  1883. } else if (styles[j].match(/^[-=| ]+[:]$/)) {
  1884. styles[j] = 'text-align:right;';
  1885. } else if (styles[j].match(/^[:][-=| ]+$/)) {
  1886. styles[j] = 'text-align:left;';
  1887. } else {
  1888. styles[j] = '';
  1889. }
  1890. }
  1891. }
  1892. tbl.push('<table>');
  1893. hs = line.substring(1, line.length - 1).split('|');
  1894. if (styles.length === 0) {
  1895. for (j = 0; j < hs.length; ++j) {
  1896. styles.push('text-align:left');
  1897. }
  1898. }
  1899. tbl.push(tables.thead.apply(this, [hs, styles]));
  1900. line = lines[++i];
  1901. if (!line.trim().match(/^[|][-=|: ]+[|]$/)) {
  1902. // not a table rolling back
  1903. line = lines[--i];
  1904. } else {
  1905. line = lines[++i];
  1906. tbl.push('<tbody>');
  1907. while (line.trim().match(/^[|].*[|]$/)) {
  1908. line = line.trim();
  1909. tbl.push(tables.tr.apply(this, [line.substring(1, line.length - 1).split('|'), styles]));
  1910. line = lines[++i];
  1911. }
  1912. tbl.push('</tbody>');
  1913. tbl.push('</table>');
  1914. // we are done with this table and we move along
  1915. out.push(tbl.join('\n'));
  1916. continue;
  1917. }
  1918. }
  1919. out.push(line);
  1920. }
  1921. return out.join('\n');
  1922. };
  1923. return {parse: filter};
  1924. };
  1925. if (options.tables) {
  1926. var tableParser = table();
  1927. return tableParser.parse(text);
  1928. } else {
  1929. return text;
  1930. }
  1931. });
  1932. /**
  1933. * Swap back in all the special characters we've hidden.
  1934. */
  1935. showdown.subParser('unescapeSpecialChars', function (text) {
  1936. 'use strict';
  1937. text = text.replace(/~E(\d+)E/g, function (wholeMatch, m1) {
  1938. var charCodeToReplace = parseInt(m1);
  1939. return String.fromCharCode(charCodeToReplace);
  1940. });
  1941. return text;
  1942. });
  1943. var root = this;
  1944. // CommonJS/nodeJS Loader
  1945. if (typeof module !== 'undefined' && module.exports) {
  1946. module.exports = showdown;
  1947. // AMD Loader
  1948. } else if (typeof define === 'function' && define.amd) {
  1949. define('showdown', function () {
  1950. 'use strict';
  1951. return showdown;
  1952. });
  1953. // Regular Browser loader
  1954. } else {
  1955. root.showdown = showdown;
  1956. }
  1957. }).call(this);
  1958. //# sourceMappingURL=showdown.js.map