showdown.js 70 KB

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