showdown.js 69 KB

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