showdown.js 70 KB

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