From 248c47f60a12d12371bc74fac56ea83061f084a5 Mon Sep 17 00:00:00 2001 From: Dan Date: Wed, 2 Mar 2022 06:16:32 -0600 Subject: [PATCH] fix "editor.formatOnSaveMode": "modifications" --- CHANGELOG.md | 4 ++++ src/PrettierEditService.ts | 35 +++++++++++++++++++++++++++++------ 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f62704eb5..311a7a85d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ All notable changes to the "prettier-vscode" extension will be documented in thi +## [9.4.0] + +- Fix `"editor.formatOnSaveMode": "modifications"`/`"modificationsIfAvailable"` + ## [9.3.0] - Remove `.gts` and `.gjs` from Handlebars extensions diff --git a/src/PrettierEditService.ts b/src/PrettierEditService.ts index 0b4d4934c..6c6845f53 100644 --- a/src/PrettierEditService.ts +++ b/src/PrettierEditService.ts @@ -323,9 +323,37 @@ export default class PrettierEditService implements Disposable { this.loggingService.logInfo( `Formatting completed in ${duration / 1000}ms.` ); - return [TextEdit.replace(this.fullDocumentRange(document), result)]; + const edit = this.minimalEdit(document, result); + return [edit]; }; + private minimalEdit(document: TextDocument, string1: string) { + const string0 = document.getText(); + // length of common prefix + let i = 0; + while ( + i < string0.length && + i < string1.length && + string0[i] === string1[i] + ) { + ++i; + } + // length of common suffix + let j = 0; + while ( + i + j < string0.length && + i + j < string1.length && + string0[string0.length - j - 1] === string1[string1.length - j - 1] + ) { + ++j; + } + const newText = string1.substring(i, string1.length - j); + const pos0 = document.positionAt(i); + const pos1 = document.positionAt(string0.length - j); + + return TextEdit.replace(new Range(pos0, pos1), newText); + } + /** * Format the given text with user's configuration. * @param text Text to format @@ -507,9 +535,4 @@ export default class PrettierEditService implements Disposable { return options; } - - private fullDocumentRange(document: TextDocument): Range { - const lastLineId = document.lineCount - 1; - return new Range(0, 0, lastLineId, document.lineAt(lastLineId).text.length); - } }