prism-unescaped-markup.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. (function () {
  2. if (typeof Prism === 'undefined' || typeof document === 'undefined') {
  3. return;
  4. }
  5. // https://developer.mozilla.org/en-US/docs/Web/API/Element/matches#Polyfill
  6. if (!Element.prototype.matches) {
  7. Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
  8. }
  9. Prism.plugins.UnescapedMarkup = true;
  10. Prism.hooks.add('before-highlightall', function (env) {
  11. env.selector += ', [class*="lang-"] script[type="text/plain"]'
  12. + ', [class*="language-"] script[type="text/plain"]'
  13. + ', script[type="text/plain"][class*="lang-"]'
  14. + ', script[type="text/plain"][class*="language-"]';
  15. });
  16. Prism.hooks.add('before-sanity-check', function (env) {
  17. /** @type {HTMLElement} */
  18. var element = env.element;
  19. if (element.matches('script[type="text/plain"]')) {
  20. // found a <script type="text/plain" ...> element
  21. // we convert this element to a regular <pre><code> code block
  22. var code = document.createElement('code');
  23. var pre = document.createElement('pre');
  24. // copy class name
  25. pre.className = code.className = element.className;
  26. // copy all "data-" attributes
  27. var dataset = element.dataset;
  28. Object.keys(dataset || {}).forEach(function (key) {
  29. if (Object.prototype.hasOwnProperty.call(dataset, key)) {
  30. pre.dataset[key] = dataset[key];
  31. }
  32. });
  33. code.textContent = env.code = env.code.replace(/&lt;\/script(?:>|&gt;)/gi, '</scri' + 'pt>');
  34. // change DOM
  35. pre.appendChild(code);
  36. element.parentNode.replaceChild(pre, element);
  37. env.element = code;
  38. return;
  39. }
  40. if (!env.code) {
  41. // no code
  42. var childNodes = element.childNodes;
  43. if (childNodes.length === 1 && childNodes[0].nodeName == '#comment') {
  44. // the only child is a comment -> use the comment's text
  45. element.textContent = env.code = childNodes[0].textContent;
  46. }
  47. }
  48. });
  49. }());