prism-normalize-whitespace.js 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. (function () {
  2. if (typeof Prism === 'undefined') {
  3. return;
  4. }
  5. var assign = Object.assign || function (obj1, obj2) {
  6. for (var name in obj2) {
  7. if (obj2.hasOwnProperty(name)) {
  8. obj1[name] = obj2[name];
  9. }
  10. }
  11. return obj1;
  12. };
  13. function NormalizeWhitespace(defaults) {
  14. this.defaults = assign({}, defaults);
  15. }
  16. function toCamelCase(value) {
  17. return value.replace(/-(\w)/g, function (match, firstChar) {
  18. return firstChar.toUpperCase();
  19. });
  20. }
  21. function tabLen(str) {
  22. var res = 0;
  23. for (var i = 0; i < str.length; ++i) {
  24. if (str.charCodeAt(i) == '\t'.charCodeAt(0)) {
  25. res += 3;
  26. }
  27. }
  28. return str.length + res;
  29. }
  30. var settingsConfig = {
  31. 'remove-trailing': 'boolean',
  32. 'remove-indent': 'boolean',
  33. 'left-trim': 'boolean',
  34. 'right-trim': 'boolean',
  35. 'break-lines': 'number',
  36. 'indent': 'number',
  37. 'remove-initial-line-feed': 'boolean',
  38. 'tabs-to-spaces': 'number',
  39. 'spaces-to-tabs': 'number',
  40. };
  41. NormalizeWhitespace.prototype = {
  42. setDefaults: function (defaults) {
  43. this.defaults = assign(this.defaults, defaults);
  44. },
  45. normalize: function (input, settings) {
  46. settings = assign(this.defaults, settings);
  47. for (var name in settings) {
  48. var methodName = toCamelCase(name);
  49. if (name !== 'normalize' && methodName !== 'setDefaults' &&
  50. settings[name] && this[methodName]) {
  51. input = this[methodName].call(this, input, settings[name]);
  52. }
  53. }
  54. return input;
  55. },
  56. /*
  57. * Normalization methods
  58. */
  59. leftTrim: function (input) {
  60. return input.replace(/^\s+/, '');
  61. },
  62. rightTrim: function (input) {
  63. return input.replace(/\s+$/, '');
  64. },
  65. tabsToSpaces: function (input, spaces) {
  66. spaces = spaces|0 || 4;
  67. return input.replace(/\t/g, new Array(++spaces).join(' '));
  68. },
  69. spacesToTabs: function (input, spaces) {
  70. spaces = spaces|0 || 4;
  71. return input.replace(RegExp(' {' + spaces + '}', 'g'), '\t');
  72. },
  73. removeTrailing: function (input) {
  74. return input.replace(/\s*?$/gm, '');
  75. },
  76. // Support for deprecated plugin remove-initial-line-feed
  77. removeInitialLineFeed: function (input) {
  78. return input.replace(/^(?:\r?\n|\r)/, '');
  79. },
  80. removeIndent: function (input) {
  81. var indents = input.match(/^[^\S\n\r]*(?=\S)/gm);
  82. if (!indents || !indents[0].length) {
  83. return input;
  84. }
  85. indents.sort(function (a, b) { return a.length - b.length; });
  86. if (!indents[0].length) {
  87. return input;
  88. }
  89. return input.replace(RegExp('^' + indents[0], 'gm'), '');
  90. },
  91. indent: function (input, tabs) {
  92. return input.replace(/^[^\S\n\r]*(?=\S)/gm, new Array(++tabs).join('\t') + '$&');
  93. },
  94. breakLines: function (input, characters) {
  95. characters = (characters === true) ? 80 : characters|0 || 80;
  96. var lines = input.split('\n');
  97. for (var i = 0; i < lines.length; ++i) {
  98. if (tabLen(lines[i]) <= characters) {
  99. continue;
  100. }
  101. var line = lines[i].split(/(\s+)/g);
  102. var len = 0;
  103. for (var j = 0; j < line.length; ++j) {
  104. var tl = tabLen(line[j]);
  105. len += tl;
  106. if (len > characters) {
  107. line[j] = '\n' + line[j];
  108. len = tl;
  109. }
  110. }
  111. lines[i] = line.join('');
  112. }
  113. return lines.join('\n');
  114. }
  115. };
  116. // Support node modules
  117. if (typeof module !== 'undefined' && module.exports) {
  118. module.exports = NormalizeWhitespace;
  119. }
  120. Prism.plugins.NormalizeWhitespace = new NormalizeWhitespace({
  121. 'remove-trailing': true,
  122. 'remove-indent': true,
  123. 'left-trim': true,
  124. 'right-trim': true,
  125. /*'break-lines': 80,
  126. 'indent': 2,
  127. 'remove-initial-line-feed': false,
  128. 'tabs-to-spaces': 4,
  129. 'spaces-to-tabs': 4*/
  130. });
  131. Prism.hooks.add('before-sanity-check', function (env) {
  132. var Normalizer = Prism.plugins.NormalizeWhitespace;
  133. // Check settings
  134. if (env.settings && env.settings['whitespace-normalization'] === false) {
  135. return;
  136. }
  137. // Check classes
  138. if (!Prism.util.isActive(env.element, 'whitespace-normalization', true)) {
  139. return;
  140. }
  141. // Simple mode if there is no env.element
  142. if ((!env.element || !env.element.parentNode) && env.code) {
  143. env.code = Normalizer.normalize(env.code, env.settings);
  144. return;
  145. }
  146. // Normal mode
  147. var pre = env.element.parentNode;
  148. if (!env.code || !pre || pre.nodeName.toLowerCase() !== 'pre') {
  149. return;
  150. }
  151. if (env.settings == null) { env.settings = {}; }
  152. // Read settings from 'data-' attributes
  153. for (var key in settingsConfig) {
  154. if (Object.hasOwnProperty.call(settingsConfig, key)) {
  155. var settingType = settingsConfig[key];
  156. if (pre.hasAttribute('data-' + key)) {
  157. try {
  158. var value = JSON.parse(pre.getAttribute('data-' + key) || 'true');
  159. if (typeof value === settingType) {
  160. env.settings[key] = value;
  161. }
  162. } catch (_error) {
  163. // ignore error
  164. }
  165. }
  166. }
  167. }
  168. var children = pre.childNodes;
  169. var before = '';
  170. var after = '';
  171. var codeFound = false;
  172. // Move surrounding whitespace from the <pre> tag into the <code> tag
  173. for (var i = 0; i < children.length; ++i) {
  174. var node = children[i];
  175. if (node == env.element) {
  176. codeFound = true;
  177. } else if (node.nodeName === '#text') {
  178. if (codeFound) {
  179. after += node.nodeValue;
  180. } else {
  181. before += node.nodeValue;
  182. }
  183. pre.removeChild(node);
  184. --i;
  185. }
  186. }
  187. if (!env.element.children.length || !Prism.plugins.KeepMarkup) {
  188. env.code = before + env.code + after;
  189. env.code = Normalizer.normalize(env.code, env.settings);
  190. } else {
  191. // Preserve markup for keep-markup plugin
  192. var html = before + env.element.innerHTML + after;
  193. env.element.innerHTML = Normalizer.normalize(html, env.settings);
  194. env.code = env.element.textContent;
  195. }
  196. });
  197. }());