showdown.js 84 KB

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