showdown.js 91 KB

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