排队支付小程序
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2535 lines
71 KiB

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