showdown.js 62 KB

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