showdown.js 71 KB

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