Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR implements a hack that would call Prettier's format command after our own formatter completes execution. It also includes a minor refactor and updating deps, but the only relevant commit is 8096181.
Long story
Initially, I tried installing
prettier
and using its JavaScript API (so that the extension wouldn't even be needed), but I faced issues bundling it with ESBuild. I replaced ESBuild with Rollup and after some config hacks it bundled successfully, but then I faced the most important issue: editing the document in the middleware (even before requesting from the LSP server) causes VS Code to cancel the formatting request, requiring the user to trigger it again.The best thing to do here is to format the document (in-memory, not on-disk) and then diff the output with the original input and transform that "diff" to LSP's
TextEdit
s, and then merge them with the array returned from our formatter, but that would have been unnecessarily complicated.The only way around this was to format with Prettier after the server's edits were already applied by VS Code, which means using the ugly
setTimeout
. Also, I went back on the "not requiring the Prettier extension" part because that felt like forcing Prettier on all users, so instead I decided to check if theprettier.enable
setting istrue
, and then simply invoke command from the Prettier extension itself.Shortcomings
Since the document is edited (by Prettier) after the requested formatting is complete, it will be left in a dirty state. This is a minor annoyance that is only relevant if the user had the "format on save" option turned on and formatted by saving. I tried working around it by adding
vscode.commands.executeCommand("workbench.action.files.saveWithoutFormatting");
after Prettier completes, but that will always force saving even if the user didn't request formatting through saving, which is somewhat intrusive.