prism-file-highlight.js 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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. var LOADING_MESSAGE = 'Loading…';
  10. var FAILURE_MESSAGE = function (status, message) {
  11. return '✖ Error ' + status + ' while fetching file: ' + message;
  12. };
  13. var FAILURE_EMPTY_MESSAGE = '✖ Error: File does not exist or is empty';
  14. var EXTENSIONS = {
  15. 'js': 'javascript',
  16. 'py': 'python',
  17. 'rb': 'ruby',
  18. 'ps1': 'powershell',
  19. 'psm1': 'powershell',
  20. 'sh': 'bash',
  21. 'bat': 'batch',
  22. 'h': 'c',
  23. 'tex': 'latex'
  24. };
  25. var STATUS_ATTR = 'data-src-status';
  26. var STATUS_LOADING = 'loading';
  27. var STATUS_LOADED = 'loaded';
  28. var STATUS_FAILED = 'failed';
  29. var SELECTOR = 'pre[data-src]:not([' + STATUS_ATTR + '="' + STATUS_LOADED + '"])'
  30. + ':not([' + STATUS_ATTR + '="' + STATUS_LOADING + '"])';
  31. /**
  32. * Loads the given file.
  33. *
  34. * @param {string} src The URL or path of the source file to load.
  35. * @param {(result: string) => void} success
  36. * @param {(reason: string) => void} error
  37. */
  38. function loadFile(src, success, error) {
  39. var xhr = new XMLHttpRequest();
  40. xhr.open('GET', src, true);
  41. xhr.onreadystatechange = function () {
  42. if (xhr.readyState == 4) {
  43. if (xhr.status < 400 && xhr.responseText) {
  44. success(xhr.responseText);
  45. } else {
  46. if (xhr.status >= 400) {
  47. error(FAILURE_MESSAGE(xhr.status, xhr.statusText));
  48. } else {
  49. error(FAILURE_EMPTY_MESSAGE);
  50. }
  51. }
  52. }
  53. };
  54. xhr.send(null);
  55. }
  56. /**
  57. * Parses the given range.
  58. *
  59. * This returns a range with inclusive ends.
  60. *
  61. * @param {string | null | undefined} range
  62. * @returns {[number, number | undefined] | undefined}
  63. */
  64. function parseRange(range) {
  65. var m = /^\s*(\d+)\s*(?:(,)\s*(?:(\d+)\s*)?)?$/.exec(range || '');
  66. if (m) {
  67. var start = Number(m[1]);
  68. var comma = m[2];
  69. var end = m[3];
  70. if (!comma) {
  71. return [start, start];
  72. }
  73. if (!end) {
  74. return [start, undefined];
  75. }
  76. return [start, Number(end)];
  77. }
  78. return undefined;
  79. }
  80. Prism.hooks.add('before-highlightall', function (env) {
  81. env.selector += ', ' + SELECTOR;
  82. });
  83. Prism.hooks.add('before-sanity-check', function (env) {
  84. var pre = /** @type {HTMLPreElement} */ (env.element);
  85. if (pre.matches(SELECTOR)) {
  86. env.code = ''; // fast-path the whole thing and go to complete
  87. pre.setAttribute(STATUS_ATTR, STATUS_LOADING); // mark as loading
  88. // add code element with loading message
  89. var code = pre.appendChild(document.createElement('CODE'));
  90. code.textContent = LOADING_MESSAGE;
  91. var src = pre.getAttribute('data-src');
  92. var language = env.language;
  93. if (language === 'none') {
  94. // the language might be 'none' because there is no language set;
  95. // in this case, we want to use the extension as the language
  96. var extension = (/\.(\w+)$/.exec(src) || [, 'none'])[1];
  97. language = EXTENSIONS[extension] || extension;
  98. }
  99. // set language classes
  100. Prism.util.setLanguage(code, language);
  101. Prism.util.setLanguage(pre, language);
  102. // preload the language
  103. var autoloader = Prism.plugins.autoloader;
  104. if (autoloader) {
  105. autoloader.loadLanguages(language);
  106. }
  107. // load file
  108. loadFile(
  109. src,
  110. function (text) {
  111. // mark as loaded
  112. pre.setAttribute(STATUS_ATTR, STATUS_LOADED);
  113. // handle data-range
  114. var range = parseRange(pre.getAttribute('data-range'));
  115. if (range) {
  116. var lines = text.split(/\r\n?|\n/g);
  117. // the range is one-based and inclusive on both ends
  118. var start = range[0];
  119. var end = range[1] == null ? lines.length : range[1];
  120. if (start < 0) { start += lines.length; }
  121. start = Math.max(0, Math.min(start - 1, lines.length));
  122. if (end < 0) { end += lines.length; }
  123. end = Math.max(0, Math.min(end, lines.length));
  124. text = lines.slice(start, end).join('\n');
  125. // add data-start for line numbers
  126. if (!pre.hasAttribute('data-start')) {
  127. pre.setAttribute('data-start', String(start + 1));
  128. }
  129. }
  130. // highlight code
  131. code.textContent = text;
  132. Prism.highlightElement(code);
  133. },
  134. function (error) {
  135. // mark as failed
  136. pre.setAttribute(STATUS_ATTR, STATUS_FAILED);
  137. code.textContent = error;
  138. }
  139. );
  140. }
  141. });
  142. Prism.plugins.fileHighlight = {
  143. /**
  144. * Executes the File Highlight plugin for all matching `pre` elements under the given container.
  145. *
  146. * Note: Elements which are already loaded or currently loading will not be touched by this method.
  147. *
  148. * @param {ParentNode} [container=document]
  149. */
  150. highlight: function highlight(container) {
  151. var elements = (container || document).querySelectorAll(SELECTOR);
  152. for (var i = 0, element; (element = elements[i++]);) {
  153. Prism.highlightElement(element);
  154. }
  155. }
  156. };
  157. var logged = false;
  158. /** @deprecated Use `Prism.plugins.fileHighlight.highlight` instead. */
  159. Prism.fileHighlight = function () {
  160. if (!logged) {
  161. console.warn('Prism.fileHighlight is deprecated. Use `Prism.plugins.fileHighlight.highlight` instead.');
  162. logged = true;
  163. }
  164. Prism.plugins.fileHighlight.highlight.apply(this, arguments);
  165. };
  166. }());