Skip to content

Commit 8346143

Browse files
authored
Fixed trimming comments on the remaining range (#45807)
* Fixed trimming comments on the remaining range * Added test
1 parent 3c27c3a commit 8346143

File tree

2 files changed

+37
-9
lines changed

2 files changed

+37
-9
lines changed

src/services/formatting/formatting.ts

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -432,13 +432,12 @@ namespace ts.formatting {
432432
if (leadingTrivia) {
433433
indentTriviaItems(leadingTrivia, indentation, /*indentNextTokenOrTrivia*/ false,
434434
item => processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined!));
435+
if (options.trimTrailingWhitespace !== false) {
436+
trimTrailingWhitespacesForRemainingRange(leadingTrivia);
437+
}
435438
}
436439
}
437440

438-
if (options.trimTrailingWhitespace !== false) {
439-
trimTrailingWhitespacesForRemainingRange();
440-
}
441-
442441
return edits;
443442

444443
// local functions
@@ -1142,13 +1141,29 @@ namespace ts.formatting {
11421141
}
11431142

11441143
/**
1145-
* Trimming will be done for lines after the previous range
1144+
* Trimming will be done for lines after the previous range.
1145+
* Exclude comments as they had been previously processed.
11461146
*/
1147-
function trimTrailingWhitespacesForRemainingRange() {
1148-
const startPosition = previousRange ? previousRange.end : originalRange.pos;
1147+
function trimTrailingWhitespacesForRemainingRange(trivias: TextRangeWithKind<SyntaxKind>[]) {
1148+
let startPos = previousRange ? previousRange.end : originalRange.pos;
1149+
for (const trivia of trivias) {
1150+
if (isComment(trivia.kind)) {
1151+
if (startPos < trivia.pos) {
1152+
trimTrailingWitespacesForPositions(startPos, trivia.pos - 1, previousRange);
1153+
}
1154+
1155+
startPos = trivia.end + 1;
1156+
}
1157+
}
1158+
1159+
if (startPos < originalRange.end) {
1160+
trimTrailingWitespacesForPositions(startPos, originalRange.end, previousRange);
1161+
}
1162+
}
11491163

1150-
const startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line;
1151-
const endLine = sourceFile.getLineAndCharacterOfPosition(originalRange.end).line;
1164+
function trimTrailingWitespacesForPositions(startPos: number, endPos: number, previousRange: TextRangeWithKind) {
1165+
const startLine = sourceFile.getLineAndCharacterOfPosition(startPos).line;
1166+
const endLine = sourceFile.getLineAndCharacterOfPosition(endPos).line;
11521167

11531168
trimTrailingWhitespacesForLines(startLine, endLine + 1, previousRange);
11541169
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
/// <reference path="../fourslash.ts"/>
2+
3+
//// ;
4+
//// /*
5+
////
6+
//// */
7+
8+
format.document();
9+
verify.currentFileContentIs(
10+
`;
11+
/*
12+
13+
*/`);

0 commit comments

Comments
 (0)