showdown.js 52 KB

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