no-trailing-spaces.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. /**
  2. * @fileoverview Disallow trailing spaces at the end of lines.
  3. * @author Nodeca Team <https://github.com/nodeca>
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("../util/ast-utils");
  10. //------------------------------------------------------------------------------
  11. // Rule Definition
  12. //------------------------------------------------------------------------------
  13. module.exports = {
  14. meta: {
  15. type: "layout",
  16. docs: {
  17. description: "disallow trailing whitespace at the end of lines",
  18. category: "Stylistic Issues",
  19. recommended: false,
  20. url: "https://eslint.org/docs/rules/no-trailing-spaces"
  21. },
  22. fixable: "whitespace",
  23. schema: [
  24. {
  25. type: "object",
  26. properties: {
  27. skipBlankLines: {
  28. type: "boolean",
  29. default: false
  30. },
  31. ignoreComments: {
  32. type: "boolean",
  33. default: false
  34. }
  35. },
  36. additionalProperties: false
  37. }
  38. ]
  39. },
  40. create(context) {
  41. const sourceCode = context.getSourceCode();
  42. const BLANK_CLASS = "[ \t\u00a0\u2000-\u200b\u3000]",
  43. SKIP_BLANK = `^${BLANK_CLASS}*$`,
  44. NONBLANK = `${BLANK_CLASS}+$`;
  45. const options = context.options[0] || {},
  46. skipBlankLines = options.skipBlankLines || false,
  47. ignoreComments = options.ignoreComments || false;
  48. /**
  49. * Report the error message
  50. * @param {ASTNode} node node to report
  51. * @param {int[]} location range information
  52. * @param {int[]} fixRange Range based on the whole program
  53. * @returns {void}
  54. */
  55. function report(node, location, fixRange) {
  56. /*
  57. * Passing node is a bit dirty, because message data will contain big
  58. * text in `source`. But... who cares :) ?
  59. * One more kludge will not make worse the bloody wizardry of this
  60. * plugin.
  61. */
  62. context.report({
  63. node,
  64. loc: location,
  65. message: "Trailing spaces not allowed.",
  66. fix(fixer) {
  67. return fixer.removeRange(fixRange);
  68. }
  69. });
  70. }
  71. /**
  72. * Given a list of comment nodes, return the line numbers for those comments.
  73. * @param {Array} comments An array of comment nodes.
  74. * @returns {number[]} An array of line numbers containing comments.
  75. */
  76. function getCommentLineNumbers(comments) {
  77. const lines = new Set();
  78. comments.forEach(comment => {
  79. for (let i = comment.loc.start.line; i <= comment.loc.end.line; i++) {
  80. lines.add(i);
  81. }
  82. });
  83. return lines;
  84. }
  85. //--------------------------------------------------------------------------
  86. // Public
  87. //--------------------------------------------------------------------------
  88. return {
  89. Program: function checkTrailingSpaces(node) {
  90. /*
  91. * Let's hack. Since Espree does not return whitespace nodes,
  92. * fetch the source code and do matching via regexps.
  93. */
  94. const re = new RegExp(NONBLANK, "u"),
  95. skipMatch = new RegExp(SKIP_BLANK, "u"),
  96. lines = sourceCode.lines,
  97. linebreaks = sourceCode.getText().match(astUtils.createGlobalLinebreakMatcher()),
  98. comments = sourceCode.getAllComments(),
  99. commentLineNumbers = getCommentLineNumbers(comments);
  100. let totalLength = 0,
  101. fixRange = [];
  102. for (let i = 0, ii = lines.length; i < ii; i++) {
  103. const matches = re.exec(lines[i]);
  104. /*
  105. * Always add linebreak length to line length to accommodate for line break (\n or \r\n)
  106. * Because during the fix time they also reserve one spot in the array.
  107. * Usually linebreak length is 2 for \r\n (CRLF) and 1 for \n (LF)
  108. */
  109. const linebreakLength = linebreaks && linebreaks[i] ? linebreaks[i].length : 1;
  110. const lineLength = lines[i].length + linebreakLength;
  111. if (matches) {
  112. const location = {
  113. line: i + 1,
  114. column: matches.index
  115. };
  116. const rangeStart = totalLength + location.column;
  117. const rangeEnd = totalLength + lineLength - linebreakLength;
  118. const containingNode = sourceCode.getNodeByRangeIndex(rangeStart);
  119. if (containingNode && containingNode.type === "TemplateElement" &&
  120. rangeStart > containingNode.parent.range[0] &&
  121. rangeEnd < containingNode.parent.range[1]) {
  122. totalLength += lineLength;
  123. continue;
  124. }
  125. /*
  126. * If the line has only whitespace, and skipBlankLines
  127. * is true, don't report it
  128. */
  129. if (skipBlankLines && skipMatch.test(lines[i])) {
  130. totalLength += lineLength;
  131. continue;
  132. }
  133. fixRange = [rangeStart, rangeEnd];
  134. if (!ignoreComments || !commentLineNumbers.has(location.line)) {
  135. report(node, location, fixRange);
  136. }
  137. }
  138. totalLength += lineLength;
  139. }
  140. }
  141. };
  142. }
  143. };