diff --git a/lib/rules/indent.js b/lib/rules/indent.js index acc52463075..faa42481b7a 100644 --- a/lib/rules/indent.js +++ b/lib/rules/indent.js @@ -779,6 +779,19 @@ module.exports = { return (statement.type === "ExpressionStatement" || statement.type === "VariableDeclaration") && statement.parent.type === "Program"; } + /** + * Counts the number of linebreaks that follow the last non-whitespace character in a string + * @param {string} string The string to check + * @returns {number} The number of JavaScript linebreaks that follow the last non-whitespace character, + * or the total number of linebreaks if the string is all whitespace. + */ + function countTrailingLinebreaks(string) { + const trailingWhitespace = string.match(/\s*$/)[0]; + const linebreakMatches = trailingWhitespace.match(astUtils.createGlobalLinebreakMatcher()); + + return linebreakMatches === null ? 0 : linebreakMatches.length; + } + /** * Check indentation for lists of elements (arrays, objects, function params) * @param {ASTNode[]} elements List of elements that should be offset @@ -836,8 +849,12 @@ module.exports = { } else { const previousElement = elements[index - 1]; const firstTokenOfPreviousElement = previousElement && getFirstToken(previousElement); + const previousElementLastToken = previousElement && sourceCode.getLastToken(previousElement); - if (previousElement && sourceCode.getLastToken(previousElement).loc.end.line > startToken.loc.end.line) { + if ( + previousElement && + previousElementLastToken.loc.end.line - countTrailingLinebreaks(previousElementLastToken.value) > startToken.loc.end.line + ) { offsets.setDesiredOffsets(element.range, firstTokenOfPreviousElement, 0); } } diff --git a/tests/lib/rules/indent.js b/tests/lib/rules/indent.js index 3a6bc0c9937..92cfa2167d4 100644 --- a/tests/lib/rules/indent.js +++ b/tests/lib/rules/indent.js @@ -4607,6 +4607,16 @@ ruleTester.run("indent", rule, { ); } `, + unIndent` +
foo +
bar
+
+ `, + unIndent` + Foo bar  + baz qux. + + `, { code: unIndent` a(b @@ -9136,6 +9146,32 @@ ruleTester.run("indent", rule, { `, errors: expectedErrors([3, 8, 6, "Block"]) }, + { + code: unIndent` +
foo +
bar
+
+ `, + output: unIndent` +
foo +
bar
+
+ `, + errors: expectedErrors([2, 4, 0, "Punctuator"]) + }, + { + code: unIndent` + Foo bar  + baz qux. + + `, + output: unIndent` + Foo bar  + baz qux. + + `, + errors: expectedErrors([2, 4, 0, "Punctuator"]) + }, { code: unIndent` ({