showdown.js 59 KB

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