showdown.js 62 KB

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