diff --git a/packages/common/src/tests/utils/stringUtilsTests.ts b/packages/common/src/tests/utils/stringUtilsTests.ts index 41614f5c5..de7f44ec5 100644 --- a/packages/common/src/tests/utils/stringUtilsTests.ts +++ b/packages/common/src/tests/utils/stringUtilsTests.ts @@ -331,6 +331,14 @@ describe("StringUtils", () => { str += "\n other"; doTest(str, "this is a `\n test`\nother", { isInStringAtPos: index => index >= pos && index < end }); }); + + it("should handle lines that only have indentation", () => { + doTest(" test\n \n test", "test\n\ntest", { indentSizeInSpaces: 2 }); + }); + + it("should ignore empty lines", () => { + doTest(" test\n\n test", "test\n\ntest", { indentSizeInSpaces: 2 }); + }); }); describe(nameof(StringUtils, "indent"), () => { diff --git a/packages/common/src/utils/StringUtils.ts b/packages/common/src/utils/StringUtils.ts index 966474fe4..cdff778a9 100644 --- a/packages/common/src/utils/StringUtils.ts +++ b/packages/common/src/utils/StringUtils.ts @@ -183,11 +183,15 @@ export class StringUtils { // indentation for spaces rounds up to the nearest tab size multiple const indentWidth = Math.ceil(spacesCount / indentSizeInSpaces) * indentSizeInSpaces + tabsCount * indentSizeInSpaces; - if (minIndentWidth == null || indentWidth < minIndentWidth) + if (str.charCodeAt(i) !== CharCodes.NEWLINE && (minIndentWidth == null || indentWidth < minIndentWidth)) minIndentWidth = indentWidth; endPositions.push(i); isAtStartOfLine = false; + + // this check is needed for lines that are empty or consist purely of spaces/tabs + if (str.charCodeAt(i) === CharCodes.NEWLINE) + i--; } }