showdown.js 60 KB

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