showdown.js 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535
  1. ;/*! showdown 25-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 matchPos = rgxFindMatchPos (str, left, right, flags),
  549. results = [];
  550. for (var i = 0; i < matchPos.length; ++i) {
  551. results.push([
  552. str.slice(matchPos[i].wholeMatch.start, matchPos[i].wholeMatch.end),
  553. str.slice(matchPos[i].match.start, matchPos[i].match.end),
  554. str.slice(matchPos[i].left.start, matchPos[i].left.end),
  555. str.slice(matchPos[i].right.start, matchPos[i].right.end)
  556. ]);
  557. }
  558. return results;
  559. };
  560. /**
  561. *
  562. * @param {string} str
  563. * @param {string|function} replacement
  564. * @param {string} left
  565. * @param {string} right
  566. * @param {string} flags
  567. * @returns {string}
  568. */
  569. showdown.helper.replaceRecursiveRegExp = function (str, replacement, left, right, flags) {
  570. 'use strict';
  571. if (!showdown.helper.isFunction(replacement)) {
  572. var repStr = replacement;
  573. replacement = function () {
  574. return repStr;
  575. };
  576. }
  577. var matchPos = rgxFindMatchPos(str, left, right, flags),
  578. finalStr = str,
  579. lng = matchPos.length;
  580. if (lng > 0) {
  581. var bits = [];
  582. if (matchPos[0].wholeMatch.start !== 0) {
  583. bits.push(str.slice(0, matchPos[0].wholeMatch.start));
  584. }
  585. for (var i = 0; i < lng; ++i) {
  586. bits.push(
  587. replacement(
  588. str.slice(matchPos[i].wholeMatch.start, matchPos[i].wholeMatch.end),
  589. str.slice(matchPos[i].match.start, matchPos[i].match.end),
  590. str.slice(matchPos[i].left.start, matchPos[i].left.end),
  591. str.slice(matchPos[i].right.start, matchPos[i].right.end)
  592. )
  593. );
  594. if (i < lng - 1) {
  595. bits.push(str.slice(matchPos[i].wholeMatch.end, matchPos[i + 1].wholeMatch.start));
  596. }
  597. }
  598. if (matchPos[lng - 1].wholeMatch.end < str.length) {
  599. bits.push(str.slice(matchPos[lng - 1].wholeMatch.end));
  600. }
  601. finalStr = bits.join('');
  602. }
  603. return finalStr;
  604. };
  605. /**
  606. * POLYFILLS
  607. */
  608. if (showdown.helper.isUndefined(console)) {
  609. console = {
  610. warn: function (msg) {
  611. 'use strict';
  612. alert(msg);
  613. },
  614. log: function (msg) {
  615. 'use strict';
  616. alert(msg);
  617. },
  618. error: function (msg) {
  619. 'use strict';
  620. throw msg;
  621. }
  622. };
  623. }
  624. /**
  625. * Created by Estevao on 31-05-2015.
  626. */
  627. /**
  628. * Showdown Converter class
  629. * @class
  630. * @param {object} [converterOptions]
  631. * @returns {Converter}
  632. */
  633. showdown.Converter = function (converterOptions) {
  634. 'use strict';
  635. var
  636. /**
  637. * Options used by this converter
  638. * @private
  639. * @type {{}}
  640. */
  641. options = {},
  642. /**
  643. * Language extensions used by this converter
  644. * @private
  645. * @type {Array}
  646. */
  647. langExtensions = [],
  648. /**
  649. * Output modifiers extensions used by this converter
  650. * @private
  651. * @type {Array}
  652. */
  653. outputModifiers = [],
  654. /**
  655. * Event listeners
  656. * @private
  657. * @type {{}}
  658. */
  659. listeners = {};
  660. _constructor();
  661. /**
  662. * Converter constructor
  663. * @private
  664. */
  665. function _constructor() {
  666. converterOptions = converterOptions || {};
  667. for (var gOpt in globalOptions) {
  668. if (globalOptions.hasOwnProperty(gOpt)) {
  669. options[gOpt] = globalOptions[gOpt];
  670. }
  671. }
  672. // Merge options
  673. if (typeof converterOptions === 'object') {
  674. for (var opt in converterOptions) {
  675. if (converterOptions.hasOwnProperty(opt)) {
  676. options[opt] = converterOptions[opt];
  677. }
  678. }
  679. } else {
  680. throw Error('Converter expects the passed parameter to be an object, but ' + typeof converterOptions +
  681. ' was passed instead.');
  682. }
  683. if (options.extensions) {
  684. showdown.helper.forEach(options.extensions, _parseExtension);
  685. }
  686. }
  687. /**
  688. * Parse extension
  689. * @param {*} ext
  690. * @param {string} [name='']
  691. * @private
  692. */
  693. function _parseExtension(ext, name) {
  694. name = name || null;
  695. // If it's a string, the extension was previously loaded
  696. if (showdown.helper.isString(ext)) {
  697. ext = showdown.helper.stdExtName(ext);
  698. name = ext;
  699. // LEGACY_SUPPORT CODE
  700. if (showdown.extensions[ext]) {
  701. console.warn('DEPRECATION WARNING: ' + ext + ' is an old extension that uses a deprecated loading method.' +
  702. 'Please inform the developer that the extension should be updated!');
  703. legacyExtensionLoading(showdown.extensions[ext], ext);
  704. return;
  705. // END LEGACY SUPPORT CODE
  706. } else if (!showdown.helper.isUndefined(extensions[ext])) {
  707. ext = extensions[ext];
  708. } else {
  709. throw Error('Extension "' + ext + '" could not be loaded. It was either not found or is not a valid extension.');
  710. }
  711. }
  712. if (typeof ext === 'function') {
  713. ext = ext();
  714. }
  715. if (!showdown.helper.isArray(ext)) {
  716. ext = [ext];
  717. }
  718. var validExt = validate(ext, name);
  719. if (!validExt.valid) {
  720. throw Error(validExt.error);
  721. }
  722. for (var i = 0; i < ext.length; ++i) {
  723. switch (ext[i].type) {
  724. case 'lang':
  725. langExtensions.push(ext[i]);
  726. break;
  727. case 'output':
  728. outputModifiers.push(ext[i]);
  729. break;
  730. }
  731. if (ext[i].hasOwnProperty(listeners)) {
  732. for (var ln in ext[i].listeners) {
  733. if (ext[i].listeners.hasOwnProperty(ln)) {
  734. listen(ln, ext[i].listeners[ln]);
  735. }
  736. }
  737. }
  738. }
  739. }
  740. /**
  741. * LEGACY_SUPPORT
  742. * @param {*} ext
  743. * @param {string} name
  744. */
  745. function legacyExtensionLoading(ext, name) {
  746. if (typeof ext === 'function') {
  747. ext = ext(new showdown.Converter());
  748. }
  749. if (!showdown.helper.isArray(ext)) {
  750. ext = [ext];
  751. }
  752. var valid = validate(ext, name);
  753. if (!valid.valid) {
  754. throw Error(valid.error);
  755. }
  756. for (var i = 0; i < ext.length; ++i) {
  757. switch (ext[i].type) {
  758. case 'lang':
  759. langExtensions.push(ext[i]);
  760. break;
  761. case 'output':
  762. outputModifiers.push(ext[i]);
  763. break;
  764. default:// should never reach here
  765. throw Error('Extension loader error: Type unrecognized!!!');
  766. }
  767. }
  768. }
  769. /**
  770. * Listen to an event
  771. * @param {string} name
  772. * @param {function} callback
  773. */
  774. function listen(name, callback) {
  775. if (!showdown.helper.isString(name)) {
  776. throw Error('Invalid argument in converter.listen() method: name must be a string, but ' + typeof name + ' given');
  777. }
  778. if (typeof callback !== 'function') {
  779. throw Error('Invalid argument in converter.listen() method: callback must be a function, but ' + typeof callback + ' given');
  780. }
  781. if (!listeners.hasOwnProperty(name)) {
  782. listeners[name] = [];
  783. }
  784. listeners[name].push(callback);
  785. }
  786. /**
  787. * Dispatch an event
  788. * @private
  789. * @param {string} evtName Event name
  790. * @param {string} text Text
  791. * @param {{}} options Converter Options
  792. * @returns {string}
  793. */
  794. this._dispatch = function dispatch (evtName, text, options) {
  795. if (listeners.hasOwnProperty(evtName)) {
  796. for (var ei = 0; ei < listeners[evtName].length; ++ei) {
  797. var nText = listeners[evtName][ei](evtName, text, this, options);
  798. if (nText && typeof nText !== 'undefined') {
  799. text = nText;
  800. }
  801. }
  802. }
  803. return text;
  804. };
  805. /**
  806. * Listen to an event
  807. * @param {string} name
  808. * @param {function} callback
  809. * @returns {showdown.Converter}
  810. */
  811. this.listen = function (name, callback) {
  812. listen(name, callback);
  813. return this;
  814. };
  815. /**
  816. * Converts a markdown string into HTML
  817. * @param {string} text
  818. * @returns {*}
  819. */
  820. this.makeHtml = function (text) {
  821. //check if text is not falsy
  822. if (!text) {
  823. return text;
  824. }
  825. var globals = {
  826. gHtmlBlocks: [],
  827. gHtmlMdBlocks: [],
  828. gHtmlSpans: [],
  829. gUrls: {},
  830. gTitles: {},
  831. gDimensions: {},
  832. gListLevel: 0,
  833. hashLinkCounts: {},
  834. langExtensions: langExtensions,
  835. outputModifiers: outputModifiers,
  836. converter: this,
  837. ghCodeBlocks: []
  838. };
  839. // attacklab: Replace ~ with ~T
  840. // This lets us use tilde as an escape char to avoid md5 hashes
  841. // The choice of character is arbitrary; anything that isn't
  842. // magic in Markdown will work.
  843. text = text.replace(/~/g, '~T');
  844. // attacklab: Replace $ with ~D
  845. // RegExp interprets $ as a special character
  846. // when it's in a replacement string
  847. text = text.replace(/\$/g, '~D');
  848. // Standardize line endings
  849. text = text.replace(/\r\n/g, '\n'); // DOS to Unix
  850. text = text.replace(/\r/g, '\n'); // Mac to Unix
  851. // Make sure text begins and ends with a couple of newlines:
  852. text = '\n\n' + text + '\n\n';
  853. // detab
  854. text = showdown.subParser('detab')(text, options, globals);
  855. // stripBlankLines
  856. text = showdown.subParser('stripBlankLines')(text, options, globals);
  857. //run languageExtensions
  858. showdown.helper.forEach(langExtensions, function (ext) {
  859. text = showdown.subParser('runExtension')(ext, text, options, globals);
  860. });
  861. // run the sub parsers
  862. text = showdown.subParser('githubCodeBlocks')(text, options, globals);
  863. text = showdown.subParser('hashHTMLBlocks')(text, options, globals);
  864. text = showdown.subParser('hashHTMLSpans')(text, options, globals);
  865. text = showdown.subParser('stripLinkDefinitions')(text, options, globals);
  866. text = showdown.subParser('blockGamut')(text, options, globals);
  867. text = showdown.subParser('unhashHTMLSpans')(text, options, globals);
  868. text = showdown.subParser('unescapeSpecialChars')(text, options, globals);
  869. // attacklab: Restore dollar signs
  870. text = text.replace(/~D/g, '$$');
  871. // attacklab: Restore tildes
  872. text = text.replace(/~T/g, '~');
  873. // Run output modifiers
  874. showdown.helper.forEach(outputModifiers, function (ext) {
  875. text = showdown.subParser('runExtension')(ext, text, options, globals);
  876. });
  877. return text;
  878. };
  879. /**
  880. * Set an option of this Converter instance
  881. * @param {string} key
  882. * @param {*} value
  883. */
  884. this.setOption = function (key, value) {
  885. options[key] = value;
  886. };
  887. /**
  888. * Get the option of this Converter instance
  889. * @param {string} key
  890. * @returns {*}
  891. */
  892. this.getOption = function (key) {
  893. return options[key];
  894. };
  895. /**
  896. * Get the options of this Converter instance
  897. * @returns {{}}
  898. */
  899. this.getOptions = function () {
  900. return options;
  901. };
  902. /**
  903. * Add extension to THIS converter
  904. * @param {{}} extension
  905. * @param {string} [name=null]
  906. */
  907. this.addExtension = function (extension, name) {
  908. name = name || null;
  909. _parseExtension(extension, name);
  910. };
  911. /**
  912. * Use a global registered extension with THIS converter
  913. * @param {string} extensionName Name of the previously registered extension
  914. */
  915. this.useExtension = function (extensionName) {
  916. _parseExtension(extensionName);
  917. };
  918. /**
  919. * Set the flavor THIS converter should use
  920. * @param {string} name
  921. */
  922. this.setFlavor = function (name) {
  923. if (flavor.hasOwnProperty(name)) {
  924. var preset = flavor[name];
  925. for (var option in preset) {
  926. if (preset.hasOwnProperty(option)) {
  927. options[option] = preset[option];
  928. }
  929. }
  930. }
  931. };
  932. /**
  933. * Remove an extension from THIS converter.
  934. * Note: This is a costly operation. It's better to initialize a new converter
  935. * and specify the extensions you wish to use
  936. * @param {Array} extension
  937. */
  938. this.removeExtension = function (extension) {
  939. if (!showdown.helper.isArray(extension)) {
  940. extension = [extension];
  941. }
  942. for (var a = 0; a < extension.length; ++a) {
  943. var ext = extension[a];
  944. for (var i = 0; i < langExtensions.length; ++i) {
  945. if (langExtensions[i] === ext) {
  946. langExtensions[i].splice(i, 1);
  947. }
  948. }
  949. for (var ii = 0; ii < outputModifiers.length; ++i) {
  950. if (outputModifiers[ii] === ext) {
  951. outputModifiers[ii].splice(i, 1);
  952. }
  953. }
  954. }
  955. };
  956. /**
  957. * Get all extension of THIS converter
  958. * @returns {{language: Array, output: Array}}
  959. */
  960. this.getAllExtensions = function () {
  961. return {
  962. language: langExtensions,
  963. output: outputModifiers
  964. };
  965. };
  966. };
  967. /**
  968. * Turn Markdown link shortcuts into XHTML <a> tags.
  969. */
  970. showdown.subParser('anchors', function (text, options, globals) {
  971. 'use strict';
  972. text = globals.converter._dispatch('anchors.before', text, options);
  973. var writeAnchorTag = function (wholeMatch, m1, m2, m3, m4, m5, m6, m7) {
  974. if (showdown.helper.isUndefined(m7)) {
  975. m7 = '';
  976. }
  977. wholeMatch = m1;
  978. var linkText = m2,
  979. linkId = m3.toLowerCase(),
  980. url = m4,
  981. title = m7;
  982. if (!url) {
  983. if (!linkId) {
  984. // lower-case and turn embedded newlines into spaces
  985. linkId = linkText.toLowerCase().replace(/ ?\n/g, ' ');
  986. }
  987. url = '#' + linkId;
  988. if (!showdown.helper.isUndefined(globals.gUrls[linkId])) {
  989. url = globals.gUrls[linkId];
  990. if (!showdown.helper.isUndefined(globals.gTitles[linkId])) {
  991. title = globals.gTitles[linkId];
  992. }
  993. } else {
  994. if (wholeMatch.search(/\(\s*\)$/m) > -1) {
  995. // Special case for explicit empty url
  996. url = '';
  997. } else {
  998. return wholeMatch;
  999. }
  1000. }
  1001. }
  1002. url = showdown.helper.escapeCharacters(url, '*_', false);
  1003. var result = '<a href="' + url + '"';
  1004. if (title !== '' && title !== null) {
  1005. title = title.replace(/"/g, '&quot;');
  1006. title = showdown.helper.escapeCharacters(title, '*_', false);
  1007. result += ' title="' + title + '"';
  1008. }
  1009. result += '>' + linkText + '</a>';
  1010. return result;
  1011. };
  1012. // First, handle reference-style links: [link text] [id]
  1013. /*
  1014. text = text.replace(/
  1015. ( // wrap whole match in $1
  1016. \[
  1017. (
  1018. (?:
  1019. \[[^\]]*\] // allow brackets nested one level
  1020. |
  1021. [^\[] // or anything else
  1022. )*
  1023. )
  1024. \]
  1025. [ ]? // one optional space
  1026. (?:\n[ ]*)? // one optional newline followed by spaces
  1027. \[
  1028. (.*?) // id = $3
  1029. \]
  1030. )()()()() // pad remaining backreferences
  1031. /g,_DoAnchors_callback);
  1032. */
  1033. text = text.replace(/(\[((?:\[[^\]]*]|[^\[\]])*)][ ]?(?:\n[ ]*)?\[(.*?)])()()()()/g, writeAnchorTag);
  1034. //
  1035. // Next, inline-style links: [link text](url "optional title")
  1036. //
  1037. /*
  1038. text = text.replace(/
  1039. ( // wrap whole match in $1
  1040. \[
  1041. (
  1042. (?:
  1043. \[[^\]]*\] // allow brackets nested one level
  1044. |
  1045. [^\[\]] // or anything else
  1046. )
  1047. )
  1048. \]
  1049. \( // literal paren
  1050. [ \t]*
  1051. () // no id, so leave $3 empty
  1052. <?(.*?)>? // href = $4
  1053. [ \t]*
  1054. ( // $5
  1055. (['"]) // quote char = $6
  1056. (.*?) // Title = $7
  1057. \6 // matching quote
  1058. [ \t]* // ignore any spaces/tabs between closing quote and )
  1059. )? // title is optional
  1060. \)
  1061. )
  1062. /g,writeAnchorTag);
  1063. */
  1064. text = text.replace(/(\[((?:\[[^\]]*]|[^\[\]])*)]\([ \t]*()<?(.*?(?:\(.*?\).*?)?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,
  1065. writeAnchorTag);
  1066. //
  1067. // Last, handle reference-style shortcuts: [link text]
  1068. // These must come last in case you've also got [link test][1]
  1069. // or [link test](/foo)
  1070. //
  1071. /*
  1072. text = text.replace(/
  1073. ( // wrap whole match in $1
  1074. \[
  1075. ([^\[\]]+) // link text = $2; can't contain '[' or ']'
  1076. \]
  1077. )()()()()() // pad rest of backreferences
  1078. /g, writeAnchorTag);
  1079. */
  1080. text = text.replace(/(\[([^\[\]]+)])()()()()()/g, writeAnchorTag);
  1081. text = globals.converter._dispatch('anchors.after', text, options);
  1082. return text;
  1083. });
  1084. showdown.subParser('autoLinks', function (text, options, globals) {
  1085. 'use strict';
  1086. text = globals.converter._dispatch('autoLinks.before', text, options);
  1087. var simpleURLRegex = /\b(((https?|ftp|dict):\/\/|www\.)[^'">\s]+\.[^'">\s]+)(?=\s|$)(?!["<>])/gi,
  1088. delimUrlRegex = /<(((https?|ftp|dict):\/\/|www\.)[^'">\s]+)>/gi,
  1089. simpleMailRegex = /(?:^|[ \n\t])([A-Za-z0-9!#$%&'*+-/=?^_`\{|}~\.]+@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)(?:$|[ \n\t])/gi,
  1090. delimMailRegex = /<(?:mailto:)?([-.\w]+@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi;
  1091. text = text.replace(delimUrlRegex, '<a href=\"$1\">$1</a>');
  1092. text = text.replace(delimMailRegex, replaceMail);
  1093. //simpleURLRegex = /\b(((https?|ftp|dict):\/\/|www\.)[-.+~:?#@!$&'()*,;=[\]\w]+)\b/gi,
  1094. // Email addresses: <address@domain.foo>
  1095. if (options.simplifiedAutoLink) {
  1096. text = text.replace(simpleURLRegex, '<a href=\"$1\">$1</a>');
  1097. text = text.replace(simpleMailRegex, replaceMail);
  1098. }
  1099. function replaceMail(wholeMatch, m1) {
  1100. var unescapedStr = showdown.subParser('unescapeSpecialChars')(m1);
  1101. return showdown.subParser('encodeEmailAddress')(unescapedStr);
  1102. }
  1103. text = globals.converter._dispatch('autoLinks.after', text, options);
  1104. return text;
  1105. });
  1106. /**
  1107. * These are all the transformations that form block-level
  1108. * tags like paragraphs, headers, and list items.
  1109. */
  1110. showdown.subParser('blockGamut', function (text, options, globals) {
  1111. 'use strict';
  1112. text = globals.converter._dispatch('blockGamut.before', text, options);
  1113. // we parse blockquotes first so that we can have headings and hrs
  1114. // inside blockquotes
  1115. text = showdown.subParser('blockQuotes')(text, options, globals);
  1116. text = showdown.subParser('headers')(text, options, globals);
  1117. // Do Horizontal Rules:
  1118. var key = showdown.subParser('hashBlock')('<hr />', options, globals);
  1119. text = text.replace(/^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$/gm, key);
  1120. text = text.replace(/^[ ]{0,2}([ ]?\-[ ]?){3,}[ \t]*$/gm, key);
  1121. text = text.replace(/^[ ]{0,2}([ ]?_[ ]?){3,}[ \t]*$/gm, key);
  1122. text = showdown.subParser('lists')(text, options, globals);
  1123. text = showdown.subParser('codeBlocks')(text, options, globals);
  1124. text = showdown.subParser('tables')(text, options, globals);
  1125. // We already ran _HashHTMLBlocks() before, in Markdown(), but that
  1126. // was to escape raw HTML in the original Markdown source. This time,
  1127. // we're escaping the markup we've just created, so that we don't wrap
  1128. // <p> tags around block-level tags.
  1129. text = showdown.subParser('hashHTMLBlocks')(text, options, globals);
  1130. text = showdown.subParser('paragraphs')(text, options, globals);
  1131. text = globals.converter._dispatch('blockGamut.after', text, options);
  1132. return text;
  1133. });
  1134. showdown.subParser('blockQuotes', function (text, options, globals) {
  1135. 'use strict';
  1136. text = globals.converter._dispatch('blockQuotes.before', text, options);
  1137. /*
  1138. text = text.replace(/
  1139. ( // Wrap whole match in $1
  1140. (
  1141. ^[ \t]*>[ \t]? // '>' at the start of a line
  1142. .+\n // rest of the first line
  1143. (.+\n)* // subsequent consecutive lines
  1144. \n* // blanks
  1145. )+
  1146. )
  1147. /gm, function(){...});
  1148. */
  1149. text = text.replace(/((^[ \t]{0,3}>[ \t]?.+\n(.+\n)*\n*)+)/gm, function (wholeMatch, m1) {
  1150. var bq = m1;
  1151. // attacklab: hack around Konqueror 3.5.4 bug:
  1152. // "----------bug".replace(/^-/g,"") == "bug"
  1153. bq = bq.replace(/^[ \t]*>[ \t]?/gm, '~0'); // trim one level of quoting
  1154. // attacklab: clean up hack
  1155. bq = bq.replace(/~0/g, '');
  1156. bq = bq.replace(/^[ \t]+$/gm, ''); // trim whitespace-only lines
  1157. bq = showdown.subParser('githubCodeBlocks')(bq, options, globals);
  1158. bq = showdown.subParser('blockGamut')(bq, options, globals); // recurse
  1159. bq = bq.replace(/(^|\n)/g, '$1 ');
  1160. // These leading spaces screw with <pre> content, so we need to fix that:
  1161. bq = bq.replace(/(\s*<pre>[^\r]+?<\/pre>)/gm, function (wholeMatch, m1) {
  1162. var pre = m1;
  1163. // attacklab: hack around Konqueror 3.5.4 bug:
  1164. pre = pre.replace(/^ /mg, '~0');
  1165. pre = pre.replace(/~0/g, '');
  1166. return pre;
  1167. });
  1168. return showdown.subParser('hashBlock')('<blockquote>\n' + bq + '\n</blockquote>', options, globals);
  1169. });
  1170. text = globals.converter._dispatch('blockQuotes.after', text, options);
  1171. return text;
  1172. });
  1173. /**
  1174. * Process Markdown `<pre><code>` blocks.
  1175. */
  1176. showdown.subParser('codeBlocks', function (text, options, globals) {
  1177. 'use strict';
  1178. text = globals.converter._dispatch('codeBlocks.before', text, options);
  1179. /*
  1180. text = text.replace(text,
  1181. /(?:\n\n|^)
  1182. ( // $1 = the code block -- one or more lines, starting with a space/tab
  1183. (?:
  1184. (?:[ ]{4}|\t) // Lines must start with a tab or a tab-width of spaces - attacklab: g_tab_width
  1185. .*\n+
  1186. )+
  1187. )
  1188. (\n*[ ]{0,3}[^ \t\n]|(?=~0)) // attacklab: g_tab_width
  1189. /g,function(){...});
  1190. */
  1191. // attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
  1192. text += '~0';
  1193. var pattern = /(?:\n\n|^)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=~0))/g;
  1194. text = text.replace(pattern, function (wholeMatch, m1, m2) {
  1195. var codeblock = m1,
  1196. nextChar = m2,
  1197. end = '\n';
  1198. codeblock = showdown.subParser('outdent')(codeblock);
  1199. codeblock = showdown.subParser('encodeCode')(codeblock);
  1200. codeblock = showdown.subParser('detab')(codeblock);
  1201. codeblock = codeblock.replace(/^\n+/g, ''); // trim leading newlines
  1202. codeblock = codeblock.replace(/\n+$/g, ''); // trim trailing newlines
  1203. if (options.omitExtraWLInCodeBlocks) {
  1204. end = '';
  1205. }
  1206. codeblock = '<pre><code>' + codeblock + end + '</code></pre>';
  1207. return showdown.subParser('hashBlock')(codeblock, options, globals) + nextChar;
  1208. });
  1209. // attacklab: strip sentinel
  1210. text = text.replace(/~0/, '');
  1211. text = globals.converter._dispatch('codeBlocks.after', text, options);
  1212. return text;
  1213. });
  1214. /**
  1215. *
  1216. * * Backtick quotes are used for <code></code> spans.
  1217. *
  1218. * * You can use multiple backticks as the delimiters if you want to
  1219. * include literal backticks in the code span. So, this input:
  1220. *
  1221. * Just type ``foo `bar` baz`` at the prompt.
  1222. *
  1223. * Will translate to:
  1224. *
  1225. * <p>Just type <code>foo `bar` baz</code> at the prompt.</p>
  1226. *
  1227. * There's no arbitrary limit to the number of backticks you
  1228. * can use as delimters. If you need three consecutive backticks
  1229. * in your code, use four for delimiters, etc.
  1230. *
  1231. * * You can use spaces to get literal backticks at the edges:
  1232. *
  1233. * ... type `` `bar` `` ...
  1234. *
  1235. * Turns to:
  1236. *
  1237. * ... type <code>`bar`</code> ...
  1238. */
  1239. showdown.subParser('codeSpans', function (text, options, globals) {
  1240. 'use strict';
  1241. text = globals.converter._dispatch('codeSpans.before', text, options);
  1242. /*
  1243. text = text.replace(/
  1244. (^|[^\\]) // Character before opening ` can't be a backslash
  1245. (`+) // $2 = Opening run of `
  1246. ( // $3 = The code block
  1247. [^\r]*?
  1248. [^`] // attacklab: work around lack of lookbehind
  1249. )
  1250. \2 // Matching closer
  1251. (?!`)
  1252. /gm, function(){...});
  1253. */
  1254. text = text.replace(/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/gm,
  1255. function (wholeMatch, m1, m2, m3) {
  1256. var c = m3;
  1257. c = c.replace(/^([ \t]*)/g, ''); // leading whitespace
  1258. c = c.replace(/[ \t]*$/g, ''); // trailing whitespace
  1259. c = showdown.subParser('encodeCode')(c);
  1260. return m1 + '<code>' + c + '</code>';
  1261. }
  1262. );
  1263. text = globals.converter._dispatch('codeSpans.after', text, options);
  1264. return text;
  1265. });
  1266. /**
  1267. * Convert all tabs to spaces
  1268. */
  1269. showdown.subParser('detab', function (text) {
  1270. 'use strict';
  1271. // expand first n-1 tabs
  1272. text = text.replace(/\t(?=\t)/g, ' '); // g_tab_width
  1273. // replace the nth with two sentinels
  1274. text = text.replace(/\t/g, '~A~B');
  1275. // use the sentinel to anchor our regex so it doesn't explode
  1276. text = text.replace(/~B(.+?)~A/g, function (wholeMatch, m1) {
  1277. var leadingText = m1,
  1278. numSpaces = 4 - leadingText.length % 4; // g_tab_width
  1279. // there *must* be a better way to do this:
  1280. for (var i = 0; i < numSpaces; i++) {
  1281. leadingText += ' ';
  1282. }
  1283. return leadingText;
  1284. });
  1285. // clean up sentinels
  1286. text = text.replace(/~A/g, ' '); // g_tab_width
  1287. text = text.replace(/~B/g, '');
  1288. return text;
  1289. });
  1290. /**
  1291. * Smart processing for ampersands and angle brackets that need to be encoded.
  1292. */
  1293. showdown.subParser('encodeAmpsAndAngles', function (text) {
  1294. 'use strict';
  1295. // Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
  1296. // http://bumppo.net/projects/amputator/
  1297. text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g, '&amp;');
  1298. // Encode naked <'s
  1299. text = text.replace(/<(?![a-z\/?\$!])/gi, '&lt;');
  1300. return text;
  1301. });
  1302. /**
  1303. * Returns the string, with after processing the following backslash escape sequences.
  1304. *
  1305. * attacklab: The polite way to do this is with the new escapeCharacters() function:
  1306. *
  1307. * text = escapeCharacters(text,"\\",true);
  1308. * text = escapeCharacters(text,"`*_{}[]()>#+-.!",true);
  1309. *
  1310. * ...but we're sidestepping its use of the (slow) RegExp constructor
  1311. * as an optimization for Firefox. This function gets called a LOT.
  1312. */
  1313. showdown.subParser('encodeBackslashEscapes', function (text) {
  1314. 'use strict';
  1315. text = text.replace(/\\(\\)/g, showdown.helper.escapeCharactersCallback);
  1316. text = text.replace(/\\([`*_{}\[\]()>#+-.!])/g, showdown.helper.escapeCharactersCallback);
  1317. return text;
  1318. });
  1319. /**
  1320. * Encode/escape certain characters inside Markdown code runs.
  1321. * The point is that in code, these characters are literals,
  1322. * and lose their special Markdown meanings.
  1323. */
  1324. showdown.subParser('encodeCode', function (text) {
  1325. 'use strict';
  1326. // Encode all ampersands; HTML entities are not
  1327. // entities within a Markdown code span.
  1328. text = text.replace(/&/g, '&amp;');
  1329. // Do the angle bracket song and dance:
  1330. text = text.replace(/</g, '&lt;');
  1331. text = text.replace(/>/g, '&gt;');
  1332. // Now, escape characters that are magic in Markdown:
  1333. text = showdown.helper.escapeCharacters(text, '*_{}[]\\', false);
  1334. // jj the line above breaks this:
  1335. //---
  1336. //* Item
  1337. // 1. Subitem
  1338. // special char: *
  1339. // ---
  1340. return text;
  1341. });
  1342. /**
  1343. * Input: an email address, e.g. "foo@example.com"
  1344. *
  1345. * Output: the email address as a mailto link, with each character
  1346. * of the address encoded as either a decimal or hex entity, in
  1347. * the hopes of foiling most address harvesting spam bots. E.g.:
  1348. *
  1349. * <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101;
  1350. * x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111;
  1351. * &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a>
  1352. *
  1353. * Based on a filter by Matthew Wickline, posted to the BBEdit-Talk
  1354. * mailing list: <http://tinyurl.com/yu7ue>
  1355. *
  1356. */
  1357. showdown.subParser('encodeEmailAddress', function (addr) {
  1358. 'use strict';
  1359. var encode = [
  1360. function (ch) {
  1361. return '&#' + ch.charCodeAt(0) + ';';
  1362. },
  1363. function (ch) {
  1364. return '&#x' + ch.charCodeAt(0).toString(16) + ';';
  1365. },
  1366. function (ch) {
  1367. return ch;
  1368. }
  1369. ];
  1370. addr = 'mailto:' + addr;
  1371. addr = addr.replace(/./g, function (ch) {
  1372. if (ch === '@') {
  1373. // this *must* be encoded. I insist.
  1374. ch = encode[Math.floor(Math.random() * 2)](ch);
  1375. } else if (ch !== ':') {
  1376. // leave ':' alone (to spot mailto: later)
  1377. var r = Math.random();
  1378. // roughly 10% raw, 45% hex, 45% dec
  1379. ch = (
  1380. r > 0.9 ? encode[2](ch) : r > 0.45 ? encode[1](ch) : encode[0](ch)
  1381. );
  1382. }
  1383. return ch;
  1384. });
  1385. addr = '<a href="' + addr + '">' + addr + '</a>';
  1386. addr = addr.replace(/">.+:/g, '">'); // strip the mailto: from the visible part
  1387. return addr;
  1388. });
  1389. /**
  1390. * Within tags -- meaning between < and > -- encode [\ ` * _] so they
  1391. * don't conflict with their use in Markdown for code, italics and strong.
  1392. */
  1393. showdown.subParser('escapeSpecialCharsWithinTagAttributes', function (text) {
  1394. 'use strict';
  1395. // Build a regex to find HTML tags and comments. See Friedl's
  1396. // "Mastering Regular Expressions", 2nd Ed., pp. 200-201.
  1397. var regex = /(<[a-z\/!$]("[^"]*"|'[^']*'|[^'">])*>|<!(--.*?--\s*)+>)/gi;
  1398. text = text.replace(regex, function (wholeMatch) {
  1399. var tag = wholeMatch.replace(/(.)<\/?code>(?=.)/g, '$1`');
  1400. tag = showdown.helper.escapeCharacters(tag, '\\`*_', false);
  1401. return tag;
  1402. });
  1403. return text;
  1404. });
  1405. /**
  1406. * Handle github codeblocks prior to running HashHTML so that
  1407. * HTML contained within the codeblock gets escaped properly
  1408. * Example:
  1409. * ```ruby
  1410. * def hello_world(x)
  1411. * puts "Hello, #{x}"
  1412. * end
  1413. * ```
  1414. */
  1415. showdown.subParser('githubCodeBlocks', function (text, options, globals) {
  1416. 'use strict';
  1417. // early exit if option is not enabled
  1418. if (!options.ghCodeBlocks) {
  1419. return text;
  1420. }
  1421. text = globals.converter._dispatch('githubCodeBlocks.before', text, options);
  1422. text += '~0';
  1423. text = text.replace(/(?:^|\n)```(.*)\n([\s\S]*?)\n```/g, function (wholeMatch, language, codeblock) {
  1424. var end = (options.omitExtraWLInCodeBlocks) ? '' : '\n';
  1425. // First parse the github code block
  1426. codeblock = showdown.subParser('encodeCode')(codeblock);
  1427. codeblock = showdown.subParser('detab')(codeblock);
  1428. codeblock = codeblock.replace(/^\n+/g, ''); // trim leading newlines
  1429. codeblock = codeblock.replace(/\n+$/g, ''); // trim trailing whitespace
  1430. codeblock = '<pre><code' + (language ? ' class="' + language + ' language-' + language + '"' : '') + '>' + codeblock + end + '</code></pre>';
  1431. codeblock = showdown.subParser('hashBlock')(codeblock, options, globals);
  1432. // Since GHCodeblocks can be false positives, we need to
  1433. // store the primitive text and the parsed text in a global var,
  1434. // and then return a token
  1435. return '\n\n~G' + (globals.ghCodeBlocks.push({text: wholeMatch, codeblock: codeblock}) - 1) + 'G\n\n';
  1436. });
  1437. // attacklab: strip sentinel
  1438. text = text.replace(/~0/, '');
  1439. return globals.converter._dispatch('githubCodeBlocks.after', text, options);
  1440. });
  1441. showdown.subParser('hashBlock', function (text, options, globals) {
  1442. 'use strict';
  1443. text = text.replace(/(^\n+|\n+$)/g, '');
  1444. return '\n\n~K' + (globals.gHtmlBlocks.push(text) - 1) + 'K\n\n';
  1445. });
  1446. showdown.subParser('hashElement', function (text, options, globals) {
  1447. 'use strict';
  1448. return function (wholeMatch, m1) {
  1449. var blockText = m1;
  1450. // Undo double lines
  1451. blockText = blockText.replace(/\n\n/g, '\n');
  1452. blockText = blockText.replace(/^\n/, '');
  1453. // strip trailing blank lines
  1454. blockText = blockText.replace(/\n+$/g, '');
  1455. // Replace the element text with a marker ("~KxK" where x is its key)
  1456. blockText = '\n\n~K' + (globals.gHtmlBlocks.push(blockText) - 1) + 'K\n\n';
  1457. return blockText;
  1458. };
  1459. });
  1460. showdown.subParser('hashHTMLBlocks', function (text, options, globals) {
  1461. 'use strict';
  1462. var blockTags = [
  1463. 'pre',
  1464. 'div',
  1465. 'h1',
  1466. 'h2',
  1467. 'h3',
  1468. 'h4',
  1469. 'h5',
  1470. 'h6',
  1471. 'blockquote',
  1472. 'table',
  1473. 'dl',
  1474. 'ol',
  1475. 'ul',
  1476. 'script',
  1477. 'noscript',
  1478. 'form',
  1479. 'fieldset',
  1480. 'iframe',
  1481. 'math',
  1482. 'style',
  1483. 'section',
  1484. 'header',
  1485. 'footer',
  1486. 'nav',
  1487. 'article',
  1488. 'aside',
  1489. 'address',
  1490. 'audio',
  1491. 'canvas',
  1492. 'figure',
  1493. 'hgroup',
  1494. 'output',
  1495. 'video',
  1496. 'p'
  1497. ],
  1498. repFunc = function (wholeMatch, match, left, right) {
  1499. var txt = wholeMatch;
  1500. // check if this html element is marked as markdown
  1501. // if so, it's contents should be parsed as markdown
  1502. if (left.search(/\bmarkdown\b/) !== -1) {
  1503. txt = left + globals.converter.makeHtml(match) + right;
  1504. }
  1505. return '\n\n~K' + (globals.gHtmlBlocks.push(txt) - 1) + 'K\n\n';
  1506. };
  1507. for (var i = 0; i < blockTags.length; ++i) {
  1508. text = showdown.helper.replaceRecursiveRegExp(text, repFunc, '^(?: |\\t){0,3}<' + blockTags[i] + '\\b[^>]*>', '</' + blockTags[i] + '>', 'gim');
  1509. }
  1510. // HR SPECIAL CASE
  1511. text = text.replace(/(\n[ ]{0,3}(<(hr)\b([^<>])*?\/?>)[ \t]*(?=\n{2,}))/g,
  1512. showdown.subParser('hashElement')(text, options, globals));
  1513. // Special case for standalone HTML comments:
  1514. text = text.replace(/(<!(--[^\r]*?--\s*)+>[ \t]*(?=\n{2,}))/g,
  1515. showdown.subParser('hashElement')(text, options, globals));
  1516. // PHP and ASP-style processor instructions (<?...?> and <%...%>)
  1517. text = text.replace(/(?:\n\n)([ ]{0,3}(?:<([?%])[^\r]*?\2>)[ \t]*(?=\n{2,}))/g,
  1518. showdown.subParser('hashElement')(text, options, globals));
  1519. return text;
  1520. });
  1521. /**
  1522. * Hash span elements that should not be parsed as markdown
  1523. */
  1524. showdown.subParser('hashHTMLSpans', function (text, config, globals) {
  1525. 'use strict';
  1526. var matches = showdown.helper.matchRecursiveRegExp(text, '<code\\b[^>]*>', '</code>', 'gi');
  1527. for (var i = 0; i < matches.length; ++i) {
  1528. text = text.replace(matches[i][0], '~L' + (globals.gHtmlSpans.push(matches[i][0]) - 1) + 'L');
  1529. }
  1530. return text;
  1531. });
  1532. /**
  1533. * Unhash HTML spans
  1534. */
  1535. showdown.subParser('unhashHTMLSpans', function (text, config, globals) {
  1536. 'use strict';
  1537. for (var i = 0; i < globals.gHtmlSpans.length; ++i) {
  1538. text = text.replace('~L' + i + 'L', globals.gHtmlSpans[i]);
  1539. }
  1540. return text;
  1541. });
  1542. showdown.subParser('headers', function (text, options, globals) {
  1543. 'use strict';
  1544. text = globals.converter._dispatch('headers.before', text, options);
  1545. var prefixHeader = options.prefixHeaderId,
  1546. headerLevelStart = (isNaN(parseInt(options.headerLevelStart))) ? 1 : parseInt(options.headerLevelStart),
  1547. // Set text-style headers:
  1548. // Header 1
  1549. // ========
  1550. //
  1551. // Header 2
  1552. // --------
  1553. //
  1554. setextRegexH1 = (options.smoothLivePreview) ? /^(.+)[ \t]*\n={2,}[ \t]*\n+/gm : /^(.+)[ \t]*\n=+[ \t]*\n+/gm,
  1555. setextRegexH2 = (options.smoothLivePreview) ? /^(.+)[ \t]*\n-{2,}[ \t]*\n+/gm : /^(.+)[ \t]*\n-+[ \t]*\n+/gm;
  1556. text = text.replace(setextRegexH1, function (wholeMatch, m1) {
  1557. var spanGamut = showdown.subParser('spanGamut')(m1, options, globals),
  1558. hID = (options.noHeaderId) ? '' : ' id="' + headerId(m1) + '"',
  1559. hLevel = headerLevelStart,
  1560. hashBlock = '<h' + hLevel + hID + '>' + spanGamut + '</h' + hLevel + '>';
  1561. return showdown.subParser('hashBlock')(hashBlock, options, globals);
  1562. });
  1563. text = text.replace(setextRegexH2, function (matchFound, m1) {
  1564. var spanGamut = showdown.subParser('spanGamut')(m1, options, globals),
  1565. hID = (options.noHeaderId) ? '' : ' id="' + headerId(m1) + '"',
  1566. hLevel = headerLevelStart + 1,
  1567. hashBlock = '<h' + hLevel + hID + '>' + spanGamut + '</h' + hLevel + '>';
  1568. return showdown.subParser('hashBlock')(hashBlock, options, globals);
  1569. });
  1570. // atx-style headers:
  1571. // # Header 1
  1572. // ## Header 2
  1573. // ## Header 2 with closing hashes ##
  1574. // ...
  1575. // ###### Header 6
  1576. //
  1577. text = text.replace(/^(#{1,6})[ \t]*(.+?)[ \t]*#*\n+/gm, function (wholeMatch, m1, m2) {
  1578. var span = showdown.subParser('spanGamut')(m2, options, globals),
  1579. hID = (options.noHeaderId) ? '' : ' id="' + headerId(m2) + '"',
  1580. hLevel = headerLevelStart - 1 + m1.length,
  1581. header = '<h' + hLevel + hID + '>' + span + '</h' + hLevel + '>';
  1582. return showdown.subParser('hashBlock')(header, options, globals);
  1583. });
  1584. function headerId(m) {
  1585. var title, escapedId = m.replace(/[^\w]/g, '').toLowerCase();
  1586. if (globals.hashLinkCounts[escapedId]) {
  1587. title = escapedId + '-' + (globals.hashLinkCounts[escapedId]++);
  1588. } else {
  1589. title = escapedId;
  1590. globals.hashLinkCounts[escapedId] = 1;
  1591. }
  1592. // Prefix id to prevent causing inadvertent pre-existing style matches.
  1593. if (prefixHeader === true) {
  1594. prefixHeader = 'section';
  1595. }
  1596. if (showdown.helper.isString(prefixHeader)) {
  1597. return prefixHeader + title;
  1598. }
  1599. return title;
  1600. }
  1601. text = globals.converter._dispatch('headers.after', text, options);
  1602. return text;
  1603. });
  1604. /**
  1605. * Turn Markdown image shortcuts into <img> tags.
  1606. */
  1607. showdown.subParser('images', function (text, options, globals) {
  1608. 'use strict';
  1609. text = globals.converter._dispatch('images.before', text, options);
  1610. var inlineRegExp = /!\[(.*?)]\s?\([ \t]*()<?(\S+?)>?(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*(?:(['"])(.*?)\6[ \t]*)?\)/g,
  1611. referenceRegExp = /!\[(.*?)][ ]?(?:\n[ ]*)?\[(.*?)]()()()()()/g;
  1612. function writeImageTag (wholeMatch, altText, linkId, url, width, height, m5, title) {
  1613. var gUrls = globals.gUrls,
  1614. gTitles = globals.gTitles,
  1615. gDims = globals.gDimensions;
  1616. linkId = linkId.toLowerCase();
  1617. if (!title) {
  1618. title = '';
  1619. }
  1620. if (url === '' || url === null) {
  1621. if (linkId === '' || linkId === null) {
  1622. // lower-case and turn embedded newlines into spaces
  1623. linkId = altText.toLowerCase().replace(/ ?\n/g, ' ');
  1624. }
  1625. url = '#' + linkId;
  1626. if (!showdown.helper.isUndefined(gUrls[linkId])) {
  1627. url = gUrls[linkId];
  1628. if (!showdown.helper.isUndefined(gTitles[linkId])) {
  1629. title = gTitles[linkId];
  1630. }
  1631. if (!showdown.helper.isUndefined(gDims[linkId])) {
  1632. width = gDims[linkId].width;
  1633. height = gDims[linkId].height;
  1634. }
  1635. } else {
  1636. return wholeMatch;
  1637. }
  1638. }
  1639. altText = altText.replace(/"/g, '&quot;');
  1640. altText = showdown.helper.escapeCharacters(altText, '*_', false);
  1641. url = showdown.helper.escapeCharacters(url, '*_', false);
  1642. var result = '<img src="' + url + '" alt="' + altText + '"';
  1643. if (title) {
  1644. title = title.replace(/"/g, '&quot;');
  1645. title = showdown.helper.escapeCharacters(title, '*_', false);
  1646. result += ' title="' + title + '"';
  1647. }
  1648. if (width && height) {
  1649. width = (width === '*') ? 'auto' : width;
  1650. height = (height === '*') ? 'auto' : height;
  1651. result += ' width="' + width + '"';
  1652. result += ' height="' + height + '"';
  1653. }
  1654. result += ' />';
  1655. return result;
  1656. }
  1657. // First, handle reference-style labeled images: ![alt text][id]
  1658. text = text.replace(referenceRegExp, writeImageTag);
  1659. // Next, handle inline images: ![alt text](url =<width>x<height> "optional title")
  1660. text = text.replace(inlineRegExp, writeImageTag);
  1661. text = globals.converter._dispatch('images.after', text, options);
  1662. return text;
  1663. });
  1664. showdown.subParser('italicsAndBold', function (text, options, globals) {
  1665. 'use strict';
  1666. text = globals.converter._dispatch('italicsAndBold.before', text, options);
  1667. if (options.literalMidWordUnderscores) {
  1668. //underscores
  1669. // Since we are consuming a \s character, we need to add it
  1670. text = text.replace(/(^|\s|>|\b)__(?=\S)([^]+?)__(?=\b|<|\s|$)/gm, '$1<strong>$2</strong>');
  1671. text = text.replace(/(^|\s|>|\b)_(?=\S)([^]+?)_(?=\b|<|\s|$)/gm, '$1<em>$2</em>');
  1672. //asterisks
  1673. text = text.replace(/(\*\*)(?=\S)([^\r]*?\S[*]*)\1/g, '<strong>$2</strong>');
  1674. text = text.replace(/(\*)(?=\S)([^\r]*?\S)\1/g, '<em>$2</em>');
  1675. } else {
  1676. // <strong> must go first:
  1677. text = text.replace(/(\*\*|__)(?=\S)([^\r]*?\S[*_]*)\1/g, '<strong>$2</strong>');
  1678. text = text.replace(/(\*|_)(?=\S)([^\r]*?\S)\1/g, '<em>$2</em>');
  1679. }
  1680. text = globals.converter._dispatch('italicsAndBold.after', text, options);
  1681. return text;
  1682. });
  1683. /**
  1684. * Form HTML ordered (numbered) and unordered (bulleted) lists.
  1685. */
  1686. showdown.subParser('lists', function (text, options, globals) {
  1687. 'use strict';
  1688. text = globals.converter._dispatch('lists.before', text, options);
  1689. /**
  1690. * Process the contents of a single ordered or unordered list, splitting it
  1691. * into individual list items.
  1692. * @param {string} listStr
  1693. * @param {boolean} trimTrailing
  1694. * @returns {string}
  1695. */
  1696. function processListItems (listStr, trimTrailing) {
  1697. // The $g_list_level global keeps track of when we're inside a list.
  1698. // Each time we enter a list, we increment it; when we leave a list,
  1699. // we decrement. If it's zero, we're not in a list anymore.
  1700. //
  1701. // We do this because when we're not inside a list, we want to treat
  1702. // something like this:
  1703. //
  1704. // I recommend upgrading to version
  1705. // 8. Oops, now this line is treated
  1706. // as a sub-list.
  1707. //
  1708. // As a single paragraph, despite the fact that the second line starts
  1709. // with a digit-period-space sequence.
  1710. //
  1711. // Whereas when we're inside a list (or sub-list), that line will be
  1712. // treated as the start of a sub-list. What a kludge, huh? This is
  1713. // an aspect of Markdown's syntax that's hard to parse perfectly
  1714. // without resorting to mind-reading. Perhaps the solution is to
  1715. // change the syntax rules such that sub-lists must start with a
  1716. // starting cardinal number; e.g. "1." or "a.".
  1717. globals.gListLevel++;
  1718. // trim trailing blank lines:
  1719. listStr = listStr.replace(/\n{2,}$/, '\n');
  1720. // attacklab: add sentinel to emulate \z
  1721. listStr += '~0';
  1722. var rgx = /(\n)?(^[ \t]*)([*+-]|\d+[.])[ \t]+((\[(x| )?])?[ \t]*[^\r]+?(\n{1,2}))(?=\n*(~0|\2([*+-]|\d+[.])[ \t]+))/gm,
  1723. isParagraphed = (/\n[ \t]*\n(?!~0)/.test(listStr));
  1724. listStr = listStr.replace(rgx, function (wholeMatch, m1, m2, m3, m4, taskbtn, checked) {
  1725. checked = (checked && checked.trim() !== '');
  1726. var item = showdown.subParser('outdent')(m4, options, globals),
  1727. bulletStyle = '';
  1728. // Support for github tasklists
  1729. if (taskbtn && options.tasklists) {
  1730. bulletStyle = ' class="task-list-item" style="list-style-type: none;"';
  1731. item = item.replace(/^[ \t]*\[(x| )?]/m, function () {
  1732. var otp = '<input type="checkbox" disabled style="margin: 0px 0.35em 0.25em -1.6em; vertical-align: middle;"';
  1733. if (checked) {
  1734. otp += ' checked';
  1735. }
  1736. otp += '>';
  1737. return otp;
  1738. });
  1739. }
  1740. // m1 - Leading line or
  1741. // Has a double return (multi paragraph) or
  1742. // Has sublist
  1743. if (m1 || (item.search(/\n{2,}/) > -1)) {
  1744. item = showdown.subParser('githubCodeBlocks')(item, options, globals);
  1745. item = showdown.subParser('blockGamut')(item, options, globals);
  1746. } else {
  1747. // Recursion for sub-lists:
  1748. item = showdown.subParser('lists')(item, options, globals);
  1749. item = item.replace(/\n$/, ''); // chomp(item)
  1750. if (isParagraphed) {
  1751. item = showdown.subParser('paragraphs')(item, options, globals);
  1752. } else {
  1753. item = showdown.subParser('spanGamut')(item, options, globals);
  1754. }
  1755. }
  1756. item = '\n<li' + bulletStyle + '>' + item + '</li>\n';
  1757. return item;
  1758. });
  1759. // attacklab: strip sentinel
  1760. listStr = listStr.replace(/~0/g, '');
  1761. globals.gListLevel--;
  1762. if (trimTrailing) {
  1763. listStr = listStr.replace(/\s+$/, '');
  1764. }
  1765. return listStr;
  1766. }
  1767. /**
  1768. * Check and parse consecutive lists (better fix for issue #142)
  1769. * @param {string} list
  1770. * @param {string} listType
  1771. * @param {boolean} trimTrailing
  1772. * @returns {string}
  1773. */
  1774. function parseConsecutiveLists(list, listType, trimTrailing) {
  1775. // check if we caught 2 or more consecutive lists by mistake
  1776. // we use the counterRgx, meaning if listType is UL we look for UL and vice versa
  1777. var counterRxg = (listType === 'ul') ? /^ {0,2}\d+\.[ \t]/gm : /^ {0,2}[*+-][ \t]/gm,
  1778. subLists = [],
  1779. result = '';
  1780. if (list.search(counterRxg) !== -1) {
  1781. (function parseCL(txt) {
  1782. var pos = txt.search(counterRxg);
  1783. if (pos !== -1) {
  1784. // slice
  1785. result += '\n\n<' + listType + '>' + processListItems(txt.slice(0, pos), !!trimTrailing) + '</' + listType + '>\n\n';
  1786. // invert counterType and listType
  1787. listType = (listType === 'ul') ? 'ol' : 'ul';
  1788. counterRxg = (listType === 'ul') ? /^ {0,2}\d+\.[ \t]/gm : /^ {0,2}[*+-][ \t]/gm;
  1789. //recurse
  1790. parseCL(txt.slice(pos));
  1791. } else {
  1792. result += '\n\n<' + listType + '>' + processListItems(txt, !!trimTrailing) + '</' + listType + '>\n\n';
  1793. }
  1794. })(list);
  1795. for (var i = 0; i < subLists.length; ++i) {
  1796. }
  1797. } else {
  1798. result = '\n\n<' + listType + '>' + processListItems(list, !!trimTrailing) + '</' + listType + '>\n\n';
  1799. }
  1800. return result;
  1801. }
  1802. // attacklab: add sentinel to hack around khtml/safari bug:
  1803. // http://bugs.webkit.org/show_bug.cgi?id=11231
  1804. text += '~0';
  1805. // Re-usable pattern to match any entire ul or ol list:
  1806. var wholeList = /^(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm;
  1807. if (globals.gListLevel) {
  1808. text = text.replace(wholeList, function (wholeMatch, list, m2) {
  1809. var listType = (m2.search(/[*+-]/g) > -1) ? 'ul' : 'ol';
  1810. return parseConsecutiveLists(list, listType, true);
  1811. });
  1812. } else {
  1813. wholeList = /(\n\n|^\n?)(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm;
  1814. //wholeList = /(\n\n|^\n?)( {0,3}([*+-]|\d+\.)[ \t]+[\s\S]+?)(?=(~0)|(\n\n(?!\t| {2,}| {0,3}([*+-]|\d+\.)[ \t])))/g;
  1815. text = text.replace(wholeList, function (wholeMatch, m1, list, m3) {
  1816. var listType = (m3.search(/[*+-]/g) > -1) ? 'ul' : 'ol';
  1817. return parseConsecutiveLists(list, listType);
  1818. });
  1819. }
  1820. // attacklab: strip sentinel
  1821. text = text.replace(/~0/, '');
  1822. text = globals.converter._dispatch('lists.after', text, options);
  1823. return text;
  1824. });
  1825. /**
  1826. * Remove one level of line-leading tabs or spaces
  1827. */
  1828. showdown.subParser('outdent', function (text) {
  1829. 'use strict';
  1830. // attacklab: hack around Konqueror 3.5.4 bug:
  1831. // "----------bug".replace(/^-/g,"") == "bug"
  1832. text = text.replace(/^(\t|[ ]{1,4})/gm, '~0'); // attacklab: g_tab_width
  1833. // attacklab: clean up hack
  1834. text = text.replace(/~0/g, '');
  1835. return text;
  1836. });
  1837. /**
  1838. *
  1839. */
  1840. showdown.subParser('paragraphs', function (text, options, globals) {
  1841. 'use strict';
  1842. text = globals.converter._dispatch('paragraphs.before', text, options);
  1843. // Strip leading and trailing lines:
  1844. text = text.replace(/^\n+/g, '');
  1845. text = text.replace(/\n+$/g, '');
  1846. var grafs = text.split(/\n{2,}/g),
  1847. grafsOut = [],
  1848. end = grafs.length; // Wrap <p> tags
  1849. for (var i = 0; i < end; i++) {
  1850. var str = grafs[i];
  1851. // if this is an HTML marker, copy it
  1852. if (str.search(/~(K|G)(\d+)\1/g) >= 0) {
  1853. grafsOut.push(str);
  1854. } else {
  1855. str = showdown.subParser('spanGamut')(str, options, globals);
  1856. str = str.replace(/^([ \t]*)/g, '<p>');
  1857. str += '</p>';
  1858. grafsOut.push(str);
  1859. }
  1860. }
  1861. /** Unhashify HTML blocks */
  1862. end = grafsOut.length;
  1863. console.log(text);
  1864. for (i = 0; i < end; i++) {
  1865. var blockText = '',
  1866. grafsOutIt = grafsOut[i],
  1867. child = false,
  1868. codeFlag = false;
  1869. // if this is a marker for an html block...
  1870. while (grafsOutIt.search(/~(K|G)(\d+)\1/) >= 0) {
  1871. var delim = RegExp.$1,
  1872. num = RegExp.$2;
  1873. if (delim === 'K') {
  1874. blockText = globals.gHtmlBlocks[num];
  1875. } else {
  1876. // we need to check if ghBlock is a false positive
  1877. blockText = (codeFlag) ? globals.ghCodeBlocks[num].text : globals.ghCodeBlocks[num].codeblock;
  1878. }
  1879. blockText = blockText.replace(/\$/g, '$$$$'); // Escape any dollar signs
  1880. grafsOutIt = grafsOutIt.replace(/(\n\n)?~(K|G)\d+\2(\n\n)?/, blockText);
  1881. // Check if grafsOutIt is a pre->code
  1882. if (/^<pre\b[^>]*>\s*<code\b[^>]*>/.test(grafsOutIt)) {
  1883. codeFlag = true;
  1884. }
  1885. child = true;
  1886. }
  1887. grafsOut[i] = grafsOutIt;
  1888. }
  1889. text = grafsOut.join('\n\n');
  1890. // Strip leading and trailing lines:
  1891. text = text.replace(/^\n+/g, '');
  1892. text = text.replace(/\n+$/g, '');
  1893. return globals.converter._dispatch('paragraphs.after', text, options);
  1894. });
  1895. /**
  1896. * Run extension
  1897. */
  1898. showdown.subParser('runExtension', function (ext, text, options, globals) {
  1899. 'use strict';
  1900. if (ext.filter) {
  1901. text = ext.filter(text, globals.converter, options);
  1902. } else if (ext.regex) {
  1903. // TODO remove this when old extension loading mechanism is deprecated
  1904. var re = ext.regex;
  1905. if (!re instanceof RegExp) {
  1906. re = new RegExp(re, 'g');
  1907. }
  1908. text = text.replace(re, ext.replace);
  1909. }
  1910. return text;
  1911. });
  1912. /**
  1913. * These are all the transformations that occur *within* block-level
  1914. * tags like paragraphs, headers, and list items.
  1915. */
  1916. showdown.subParser('spanGamut', function (text, options, globals) {
  1917. 'use strict';
  1918. text = globals.converter._dispatch('spanGamut.before', text, options);
  1919. text = showdown.subParser('codeSpans')(text, options, globals);
  1920. text = showdown.subParser('escapeSpecialCharsWithinTagAttributes')(text, options, globals);
  1921. text = showdown.subParser('encodeBackslashEscapes')(text, options, globals);
  1922. // Process anchor and image tags. Images must come first,
  1923. // because ![foo][f] looks like an anchor.
  1924. text = showdown.subParser('images')(text, options, globals);
  1925. text = showdown.subParser('anchors')(text, options, globals);
  1926. // Make links out of things like `<http://example.com/>`
  1927. // Must come after _DoAnchors(), because you can use < and >
  1928. // delimiters in inline links like [this](<url>).
  1929. text = showdown.subParser('autoLinks')(text, options, globals);
  1930. text = showdown.subParser('encodeAmpsAndAngles')(text, options, globals);
  1931. text = showdown.subParser('italicsAndBold')(text, options, globals);
  1932. text = showdown.subParser('strikethrough')(text, options, globals);
  1933. // Do hard breaks:
  1934. text = text.replace(/ +\n/g, ' <br />\n');
  1935. text = globals.converter._dispatch('spanGamut.after', text, options);
  1936. return text;
  1937. });
  1938. showdown.subParser('strikethrough', function (text, options, globals) {
  1939. 'use strict';
  1940. if (options.strikethrough) {
  1941. text = globals.converter._dispatch('strikethrough.before', text, options);
  1942. text = text.replace(/(?:~T){2}([\s\S]+?)(?:~T){2}/g, '<del>$1</del>');
  1943. text = globals.converter._dispatch('strikethrough.after', text, options);
  1944. }
  1945. return text;
  1946. });
  1947. /**
  1948. * Strip any lines consisting only of spaces and tabs.
  1949. * This makes subsequent regexs easier to write, because we can
  1950. * match consecutive blank lines with /\n+/ instead of something
  1951. * contorted like /[ \t]*\n+/
  1952. */
  1953. showdown.subParser('stripBlankLines', function (text) {
  1954. 'use strict';
  1955. return text.replace(/^[ \t]+$/mg, '');
  1956. });
  1957. /**
  1958. * Strips link definitions from text, stores the URLs and titles in
  1959. * hash references.
  1960. * Link defs are in the form: ^[id]: url "optional title"
  1961. *
  1962. * ^[ ]{0,3}\[(.+)\]: // id = $1 attacklab: g_tab_width - 1
  1963. * [ \t]*
  1964. * \n? // maybe *one* newline
  1965. * [ \t]*
  1966. * <?(\S+?)>? // url = $2
  1967. * [ \t]*
  1968. * \n? // maybe one newline
  1969. * [ \t]*
  1970. * (?:
  1971. * (\n*) // any lines skipped = $3 attacklab: lookbehind removed
  1972. * ["(]
  1973. * (.+?) // title = $4
  1974. * [")]
  1975. * [ \t]*
  1976. * )? // title is optional
  1977. * (?:\n+|$)
  1978. * /gm,
  1979. * function(){...});
  1980. *
  1981. */
  1982. showdown.subParser('stripLinkDefinitions', function (text, options, globals) {
  1983. 'use strict';
  1984. 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;
  1985. // attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
  1986. text += '~0';
  1987. text = text.replace(regex, function (wholeMatch, linkId, url, width, height, blankLines, title) {
  1988. linkId = linkId.toLowerCase();
  1989. globals.gUrls[linkId] = showdown.subParser('encodeAmpsAndAngles')(url); // Link IDs are case-insensitive
  1990. if (blankLines) {
  1991. // Oops, found blank lines, so it's not a title.
  1992. // Put back the parenthetical statement we stole.
  1993. return blankLines + title;
  1994. } else {
  1995. if (title) {
  1996. globals.gTitles[linkId] = title.replace(/"|'/g, '&quot;');
  1997. }
  1998. if (options.parseImgDimensions && width && height) {
  1999. globals.gDimensions[linkId] = {
  2000. width: width,
  2001. height: height
  2002. };
  2003. }
  2004. }
  2005. // Completely remove the definition from the text
  2006. return '';
  2007. });
  2008. // attacklab: strip sentinel
  2009. text = text.replace(/~0/, '');
  2010. return text;
  2011. });
  2012. showdown.subParser('tables', function (text, options, globals) {
  2013. 'use strict';
  2014. var table = function () {
  2015. var tables = {},
  2016. filter;
  2017. tables.th = function (header, style) {
  2018. var id = '';
  2019. header = header.trim();
  2020. if (header === '') {
  2021. return '';
  2022. }
  2023. if (options.tableHeaderId) {
  2024. id = ' id="' + header.replace(/ /g, '_').toLowerCase() + '"';
  2025. }
  2026. header = showdown.subParser('spanGamut')(header, options, globals);
  2027. if (!style || style.trim() === '') {
  2028. style = '';
  2029. } else {
  2030. style = ' style="' + style + '"';
  2031. }
  2032. return '<th' + id + style + '>' + header + '</th>';
  2033. };
  2034. tables.td = function (cell, style) {
  2035. var subText = showdown.subParser('spanGamut')(cell.trim(), options, globals);
  2036. if (!style || style.trim() === '') {
  2037. style = '';
  2038. } else {
  2039. style = ' style="' + style + '"';
  2040. }
  2041. return '<td' + style + '>' + subText + '</td>';
  2042. };
  2043. tables.ths = function () {
  2044. var out = '',
  2045. i = 0,
  2046. hs = [].slice.apply(arguments[0]),
  2047. style = [].slice.apply(arguments[1]);
  2048. for (i; i < hs.length; i += 1) {
  2049. out += tables.th(hs[i], style[i]) + '\n';
  2050. }
  2051. return out;
  2052. };
  2053. tables.tds = function () {
  2054. var out = '',
  2055. i = 0,
  2056. ds = [].slice.apply(arguments[0]),
  2057. style = [].slice.apply(arguments[1]);
  2058. for (i; i < ds.length; i += 1) {
  2059. out += tables.td(ds[i], style[i]) + '\n';
  2060. }
  2061. return out;
  2062. };
  2063. tables.thead = function () {
  2064. var out,
  2065. hs = [].slice.apply(arguments[0]),
  2066. style = [].slice.apply(arguments[1]);
  2067. out = '<thead>\n';
  2068. out += '<tr>\n';
  2069. out += tables.ths.apply(this, [hs, style]);
  2070. out += '</tr>\n';
  2071. out += '</thead>\n';
  2072. return out;
  2073. };
  2074. tables.tr = function () {
  2075. var out,
  2076. cs = [].slice.apply(arguments[0]),
  2077. style = [].slice.apply(arguments[1]);
  2078. out = '<tr>\n';
  2079. out += tables.tds.apply(this, [cs, style]);
  2080. out += '</tr>\n';
  2081. return out;
  2082. };
  2083. filter = function (text) {
  2084. var i = 0,
  2085. lines = text.split('\n'),
  2086. line,
  2087. hs,
  2088. out = [];
  2089. for (i; i < lines.length; i += 1) {
  2090. line = lines[i];
  2091. // looks like a table heading
  2092. if (line.trim().match(/^[|].*[|]$/)) {
  2093. line = line.trim();
  2094. var tbl = [],
  2095. align = lines[i + 1].trim(),
  2096. styles = [],
  2097. j = 0;
  2098. if (align.match(/^[|][-=|: ]+[|]$/)) {
  2099. styles = align.substring(1, align.length - 1).split('|');
  2100. for (j = 0; j < styles.length; ++j) {
  2101. styles[j] = styles[j].trim();
  2102. if (styles[j].match(/^[:][-=| ]+[:]$/)) {
  2103. styles[j] = 'text-align:center;';
  2104. } else if (styles[j].match(/^[-=| ]+[:]$/)) {
  2105. styles[j] = 'text-align:right;';
  2106. } else if (styles[j].match(/^[:][-=| ]+$/)) {
  2107. styles[j] = 'text-align:left;';
  2108. } else {
  2109. styles[j] = '';
  2110. }
  2111. }
  2112. }
  2113. tbl.push('<table>');
  2114. hs = line.substring(1, line.length - 1).split('|');
  2115. if (styles.length === 0) {
  2116. for (j = 0; j < hs.length; ++j) {
  2117. styles.push('text-align:left');
  2118. }
  2119. }
  2120. tbl.push(tables.thead.apply(this, [hs, styles]));
  2121. line = lines[++i];
  2122. if (!line.trim().match(/^[|][-=|: ]+[|]$/)) {
  2123. // not a table rolling back
  2124. line = lines[--i];
  2125. } else {
  2126. line = lines[++i];
  2127. tbl.push('<tbody>');
  2128. while (line.trim().match(/^[|].*[|]$/)) {
  2129. line = line.trim();
  2130. tbl.push(tables.tr.apply(this, [line.substring(1, line.length - 1).split('|'), styles]));
  2131. line = lines[++i];
  2132. }
  2133. tbl.push('</tbody>');
  2134. tbl.push('</table>');
  2135. // we are done with this table and we move along
  2136. out.push(tbl.join('\n'));
  2137. continue;
  2138. }
  2139. }
  2140. out.push(line);
  2141. }
  2142. return out.join('\n');
  2143. };
  2144. return {parse: filter};
  2145. };
  2146. if (options.tables) {
  2147. text = globals.converter._dispatch('tables.before', text, options);
  2148. var tableParser = table();
  2149. text = tableParser.parse(text);
  2150. text = globals.converter._dispatch('tables.after', text, options);
  2151. }
  2152. return text;
  2153. });
  2154. /**
  2155. * Swap back in all the special characters we've hidden.
  2156. */
  2157. showdown.subParser('unescapeSpecialChars', function (text) {
  2158. 'use strict';
  2159. text = text.replace(/~E(\d+)E/g, function (wholeMatch, m1) {
  2160. var charCodeToReplace = parseInt(m1);
  2161. return String.fromCharCode(charCodeToReplace);
  2162. });
  2163. return text;
  2164. });
  2165. var root = this;
  2166. // CommonJS/nodeJS Loader
  2167. if (typeof module !== 'undefined' && module.exports) {
  2168. module.exports = showdown;
  2169. // AMD Loader
  2170. } else if (typeof define === 'function' && define.amd) {
  2171. define(function () {
  2172. 'use strict';
  2173. return showdown;
  2174. });
  2175. // Regular Browser loader
  2176. } else {
  2177. root.showdown = showdown;
  2178. }
  2179. }).call(this);
  2180. //# sourceMappingURL=showdown.js.map