Skip to content

Commit

Permalink
Only scan in top level import trivia
Browse files Browse the repository at this point in the history
  • Loading branch information
MQuy committed Apr 5, 2022
1 parent 24e4cd9 commit f594067
Showing 1 changed file with 8 additions and 6 deletions.
14 changes: 8 additions & 6 deletions src/services/organizeImports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ namespace ts.OrganizeImports {
const groupImports: ImportDeclaration[][] = [];
let groupIndex = 0;
for (const topLevelImportDecl of importDecls) {
if (isNewGroup(sourceFile, topLevelImportDecl, scanner)) {
if (isNewGroup(topLevelImportDecl, scanner)) {
groupIndex++;
}

Expand All @@ -108,18 +108,20 @@ namespace ts.OrganizeImports {

// a new group is created if an import includes at least two new line
// new line from multi-line comment doesn't count
function isNewGroup(sourceFile: SourceFile, topLevelImportDecl: ImportDeclaration, scanner: Scanner) {
const startPos = topLevelImportDecl.getFullStart();
const endPos = topLevelImportDecl.getStart();
function isNewGroup(topLevelImportDecl: ImportDeclaration, scanner: Scanner) {
const leadingText = topLevelImportDecl.getFullText().substring(0, topLevelImportDecl.getLeadingTriviaWidth());
scanner.setText(leadingText);

scanner.setText(sourceFile.text, startPos);
let numberOfNewLines = 0;
while (scanner.getTokenPos() < endPos) {
while (true) {
const tokenKind = scanner.scan();

if (tokenKind === SyntaxKind.NewLineTrivia) {
numberOfNewLines++;
}
else if (tokenKind === SyntaxKind.EndOfFileToken) {
break;
}
}

return numberOfNewLines >= 2;
Expand Down

0 comments on commit f594067

Please sign in to comment.