showdown.js 55 KB

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