Skip to content

Commit a3dcb34

Browse files
committed
Ignore empty or whitespace-only lines when calculating
1 parent 042ba55 commit a3dcb34

File tree

3 files changed

+21
-3
lines changed

3 files changed

+21
-3
lines changed

src/lib/documentHelpers.ts

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,18 @@ export function linesForIndexes(document: TextDocument, lineIndexes: number[]):
77
}
88

99
export function minimumIndentationForLineIndexes(document: TextDocument, lineIndexes: number[]): number {
10-
const indentationLevels = lineIndexes.map((lineIndex) => {
11-
return document.lineAt(lineIndex).firstNonWhitespaceCharacterIndex;
12-
});
10+
const indentationLevels = lineIndexes.reduce<number[]>((indentationLevels, lineIndex) => {
11+
const line = document.lineAt(lineIndex);
12+
13+
// Skip empty lines so they don't skew the calculation results
14+
if (line.isEmptyOrWhitespace) {
15+
return indentationLevels;
16+
}
17+
18+
indentationLevels.push(line.firstNonWhitespaceCharacterIndex);
19+
20+
return indentationLevels;
21+
}, []);
1322

1423
const minimumIndentationLevelInSelection = Math.min(...indentationLevels);
1524
return minimumIndentationLevelInSelection;

src/test/fixtures/javascript-example.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,9 @@ class MyThing {
88
doSomethingElse() {
99
throw new Error('Nope!');
1010
}
11+
12+
emptyFunction() {
13+
14+
15+
}
1116
}

src/test/suite/lib/documentHelpers.test.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,10 @@ describe('Document Helpers', function () {
3636
it('calculates the correct minimum indentation level for multiple lines', () => {
3737
assert.equal(minimumIndentationForLineIndexes(document, [1, 2, 3]), 2);
3838
});
39+
40+
it('calculates the correct minimum indentation level when lines contain an empty line', () => {
41+
assert.equal(minimumIndentationForLineIndexes(document, [11, 12, 13, 14]), 4);
42+
});
3943
});
4044

4145
context('contentOfLinesWithAdjustedIndentation', async () => {

0 commit comments

Comments
 (0)