showdown.js 71 KB

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