showdown.js 71 KB

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