prism-show-invisibles.js 1.7 KB

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