showdown.js 60 KB

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