showdown.js 68 KB

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