prism-show-invisibles.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. (function () {
  2. if (
  3. typeof self !== 'undefined' && !self.Prism ||
  4. typeof global !== 'undefined' && !global.Prism
  5. ) {
  6. return;
  7. }
  8. var invisibles = {
  9. 'tab': /\t/,
  10. 'crlf': /\r\n/,
  11. 'lf': /\n/,
  12. 'cr': /\r/,
  13. 'space': / /
  14. };
  15. /**
  16. * Handles the recursive calling of `addInvisibles` for one token.
  17. *
  18. * @param {Object|Array} tokens The grammar or array which contains the token.
  19. * @param {string|number} name The name or index of the token in `tokens`.
  20. */
  21. function handleToken(tokens, name) {
  22. var value = tokens[name];
  23. var type = Prism.util.type(value);
  24. switch (type) {
  25. case 'RegExp':
  26. var inside = {};
  27. tokens[name] = {
  28. pattern: value,
  29. inside: inside
  30. };
  31. addInvisibles(inside);
  32. break;
  33. case 'Array':
  34. for (var i = 0, l = value.length; i < l; i++) {
  35. handleToken(value, i);
  36. }
  37. break;
  38. default: // 'Object'
  39. var inside = value.inside || (value.inside = {});
  40. addInvisibles(inside);
  41. break;
  42. }
  43. }
  44. /**
  45. * Recursively adds patterns to match invisible characters to the given grammar (if not added already).
  46. *
  47. * @param {Object} grammar
  48. */
  49. function addInvisibles(grammar) {
  50. if (!grammar || grammar['tab']) {
  51. return;
  52. }
  53. // assign invisibles here to "mark" the grammar in case of self references
  54. for (var name in invisibles) {
  55. if (invisibles.hasOwnProperty(name)) {
  56. grammar[name] = invisibles[name];
  57. }
  58. }
  59. for (var name in grammar) {
  60. if (grammar.hasOwnProperty(name) && !invisibles[name]) {
  61. if (name === 'rest') {
  62. addInvisibles(grammar['rest']);
  63. } else {
  64. handleToken(grammar, name);
  65. }
  66. }
  67. }
  68. }
  69. Prism.hooks.add('before-highlight', function (env) {
  70. addInvisibles(env.grammar);
  71. });
  72. })();