showdown.js 69 KB

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