prism-data-uri-highlight.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. (function () {
  2. if (typeof Prism === 'undefined') {
  3. return;
  4. }
  5. var autoLinkerProcess = function (grammar) {
  6. if (Prism.plugins.autolinker) {
  7. Prism.plugins.autolinker.processGrammar(grammar);
  8. }
  9. return grammar;
  10. };
  11. var dataURI = {
  12. pattern: /(.)\bdata:[^\/]+\/[^,]+,(?:(?!\1)[\s\S]|\\\1)+(?=\1)/,
  13. lookbehind: true,
  14. inside: {
  15. 'language-css': {
  16. pattern: /(data:[^\/]+\/(?:[^+,]+\+)?css,)[\s\S]+/,
  17. lookbehind: true
  18. },
  19. 'language-javascript': {
  20. pattern: /(data:[^\/]+\/(?:[^+,]+\+)?javascript,)[\s\S]+/,
  21. lookbehind: true
  22. },
  23. 'language-json': {
  24. pattern: /(data:[^\/]+\/(?:[^+,]+\+)?json,)[\s\S]+/,
  25. lookbehind: true
  26. },
  27. 'language-markup': {
  28. pattern: /(data:[^\/]+\/(?:[^+,]+\+)?(?:html|xml),)[\s\S]+/,
  29. lookbehind: true
  30. }
  31. }
  32. };
  33. // Tokens that may contain URLs
  34. var candidates = ['url', 'attr-value', 'string'];
  35. Prism.plugins.dataURIHighlight = {
  36. processGrammar: function (grammar) {
  37. // Abort if grammar has already been processed
  38. if (!grammar || grammar['data-uri']) {
  39. return;
  40. }
  41. Prism.languages.DFS(grammar, function (key, def, type) {
  42. if (candidates.indexOf(type) > -1 && !Array.isArray(def)) {
  43. if (!def.pattern) {
  44. def = this[key] = {
  45. pattern: def
  46. };
  47. }
  48. def.inside = def.inside || {};
  49. if (type == 'attr-value') {
  50. Prism.languages.insertBefore('inside', def.inside['url-link'] ? 'url-link' : 'punctuation', {
  51. 'data-uri': dataURI
  52. }, def);
  53. } else {
  54. if (def.inside['url-link']) {
  55. Prism.languages.insertBefore('inside', 'url-link', {
  56. 'data-uri': dataURI
  57. }, def);
  58. } else {
  59. def.inside['data-uri'] = dataURI;
  60. }
  61. }
  62. }
  63. });
  64. grammar['data-uri'] = dataURI;
  65. }
  66. };
  67. Prism.hooks.add('before-highlight', function (env) {
  68. // Prepare the needed grammars for this code block
  69. if (dataURI.pattern.test(env.code)) {
  70. for (var p in dataURI.inside) {
  71. if (dataURI.inside.hasOwnProperty(p)) {
  72. if (!dataURI.inside[p].inside && dataURI.inside[p].pattern.test(env.code)) {
  73. var lang = p.match(/^language-(.+)/)[1];
  74. if (Prism.languages[lang]) {
  75. dataURI.inside[p].inside = {
  76. rest: autoLinkerProcess(Prism.languages[lang])
  77. };
  78. }
  79. }
  80. }
  81. }
  82. }
  83. Prism.plugins.dataURIHighlight.processGrammar(env.grammar);
  84. });
  85. }());