Skip to content

Commit

Permalink
fix "editor.formatOnSaveMode": "modifications"
Browse files Browse the repository at this point in the history
  • Loading branch information
rotu committed Mar 2, 2022
1 parent 6badc74 commit 248c47f
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 6 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ All notable changes to the "prettier-vscode" extension will be documented in thi

<!-- Check [Keep a Changelog](http://keepachangelog.com/) for recommendations on how to structure this file. -->

## [9.4.0]

- Fix `"editor.formatOnSaveMode": "modifications"`/`"modificationsIfAvailable"`

## [9.3.0]

- Remove `.gts` and `.gjs` from Handlebars extensions
Expand Down
35 changes: 29 additions & 6 deletions src/PrettierEditService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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);
}
}

0 comments on commit 248c47f

Please sign in to comment.