showdown.js 58 KB

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