showdown.js 74 KB

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