From abed27506266f567c9e2809543022844c4fbd811 Mon Sep 17 00:00:00 2001 From: Stan Lo Date: Thu, 23 Nov 2023 18:54:34 +0000 Subject: [PATCH] Fix weird indentation for on-type completion The issue was caused by incorrect indentation calculation when the line was not empty before the cursor. This commit fixes the issue by calculating the indentation based on the line's content. Co-authored-by: Vinicius Stock --- src/client.ts | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/src/client.ts b/src/client.ts index 4db460a0..5d8594c1 100644 --- a/src/client.ts +++ b/src/client.ts @@ -178,24 +178,30 @@ export default class Client implements ClientInterface { const workspaceEdit = new vscode.WorkspaceEdit(); workspaceEdit.set(document.uri, response); - await vscode.workspace.applyEdit(workspaceEdit); const editor = vscode.window.activeTextEditor!; - const existingText = editor.document.getText( - new vscode.Range( - cursorPosition.range.start, - cursorPosition.range.end, - ), - ); + + // This should happen before applying the edits, otherwise the cursor will be moved to the wrong position + const existingText = editor.document.lineAt( + cursorPosition.range.start.line, + ).text; + + await vscode.workspace.applyEdit(workspaceEdit); const indentChar = vscode.window.activeTextEditor?.options .insertSpaces ? " " : "\t"; - const indentation = indentChar.repeat( - cursorPosition.range.end.character - existingText.length, - ); + // If the line is not empty, we don't want to indent the cursor + let indentationLength = 0; + + // If the line is empty or only contains whitespace, we want to indent the cursor to the requested position + if (/^\s*$/.exec(existingText)) { + indentationLength = cursorPosition.range.end.character; + } + + const indentation = indentChar.repeat(indentationLength); await vscode.window.activeTextEditor!.insertSnippet( new vscode.SnippetString(