From 3c801f3b2228b54b158426483013ae00a5c7e20c Mon Sep 17 00:00:00 2001 From: vinocher-bc Date: Tue, 18 Jun 2024 16:06:11 -0700 Subject: [PATCH 1/2] Format previous line on --- src/SwiftFormatEditProvider.ts | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/src/SwiftFormatEditProvider.ts b/src/SwiftFormatEditProvider.ts index 678b88a..d47af74 100644 --- a/src/SwiftFormatEditProvider.ts +++ b/src/SwiftFormatEditProvider.ts @@ -132,10 +132,24 @@ export class SwiftFormatEditProvider ch: string, formatting: vscode.FormattingOptions, ) { - // Don't format if user has inserted an empty line - if (document.lineAt(position.line).text.trim() === "") { - return []; + // If a new line was entered, format the previous line + if (ch === "\n" && position.line > 0) { + const previousLine = position.line - 1; + + // If the previous line is empty, formatting is not required + if (document.lineAt(previousLine).text.trim() === "") { + return []; + } + + // Create a range for the previous line and format it + const previousLineText = document.lineAt(previousLine).text; + const range = new vscode.Range(new vscode.Position(previousLine, 0), new vscode.Position(previousLine, previousLineText.length)); + return format({ + document, + parameters: ["--fragment", "true"], + range, + formatting + }); } - return format({ document, formatting }); } } From acc0276b7db0e1882be02f66e78a697a3cb0e500 Mon Sep 17 00:00:00 2001 From: vinocher-bc Date: Mon, 24 Jun 2024 15:01:15 -0700 Subject: [PATCH 2/2] Explicitly handle edge case --- src/SwiftFormatEditProvider.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/SwiftFormatEditProvider.ts b/src/SwiftFormatEditProvider.ts index d47af74..4a272c4 100644 --- a/src/SwiftFormatEditProvider.ts +++ b/src/SwiftFormatEditProvider.ts @@ -133,7 +133,10 @@ export class SwiftFormatEditProvider formatting: vscode.FormattingOptions, ) { // If a new line was entered, format the previous line - if (ch === "\n" && position.line > 0) { + if (ch === "\n") { + if (position.line <= 0) { + return []; + } const previousLine = position.line - 1; // If the previous line is empty, formatting is not required