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.

2928 lines
87 KiB

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