Skip to content

Commit e151d49

Browse files
committed
Merge pull request microsoft#7307 from zhengbli/fixFormatOnEnter
Avoid removing indentation on a new line as trailing white spaces
2 parents f06423b + 1224013 commit e151d49

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

src/services/formatting/formatting.ts

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -72,12 +72,20 @@ namespace ts.formatting {
7272
if (line === 0) {
7373
return [];
7474
}
75-
// get the span for the previous\current line
75+
// After the enter key, the cursor is now at a new line. The new line may or may not contain non-whitespace characters.
76+
// If the new line has only whitespaces, we won't want to format this line, because that would remove the indentation as
77+
// trailing whitespaces. So the end of the formatting span should be the later one between:
78+
// 1. the end of the previous line
79+
// 2. the last non-whitespace character in the current line
80+
let endOfFormatSpan = getEndLinePosition(line, sourceFile);
81+
while (isWhiteSpace(sourceFile.text.charCodeAt(endOfFormatSpan)) && !isLineBreak(sourceFile.text.charCodeAt(endOfFormatSpan))) {
82+
endOfFormatSpan--;
83+
}
7684
let span = {
7785
// get start position for the previous line
7886
pos: getStartPositionOfLine(line - 1, sourceFile),
79-
// get end position for the current line (end value is exclusive so add 1 to the result)
80-
end: getEndLinePosition(line, sourceFile) + 1
87+
// end value is exclusive so add 1 to the result
88+
end: endOfFormatSpan + 1
8189
}
8290
return formatSpan(span, sourceFile, options, rulesProvider, FormattingRequestKind.FormatOnEnter);
8391
}

0 commit comments

Comments
 (0)