belav / csharpier

CSharpier is an opinionated code formatter for c#.
https://csharpier.com
MIT License
1.41k stars 99 forks source link

VSCode Extension: Add diagnostics and code actions and format range #1376

Closed badsyntax closed 5 days ago

badsyntax commented 2 weeks ago

Fixes #1375 Fixes #659

A lot of this code has been taken from one of my open source extensions.

This approach uses the prettier-linter-helpers package to generate diffs of strings (unformatted code against formatted code) which is used to provide diagnostic information and code actions. This allows for formatting parts of code.

Screenshot 2024-11-07 at 21 55 03 Screenshot 2024-11-07 at 22 26 38
badsyntax commented 1 week ago

Hey, apologies for the delay in responding.

You mentioned that it fixes https://github.com/belav/csharpier/issues/659, but from looking through the code I only see a new code action provider being created.

Yes sorry, I have not thought about Format Selection. By providing a QuickFIx CodeAction it's possible to format only parts of the code. While not the same as formating selection it provides a similar feature:

https://github.com/user-attachments/assets/a7145741-7a58-4025-9339-c2ee34cbbb7f

Saying that, I will investigate to see how complicated it'l be to support Format Selection.

Will this code make partial formats happen if "editor.formatOnSaveMode": "modificationsIfAvailable"

At this time it doesn't support modificationsIfAvailable but I'll see if I can support that.

badsyntax commented 1 week ago

OK! With the latest change we can format selection.

We generate the diff, then we compare the differences to check if they're in the range of the selection, and if so, apply the diff change as a TextEdit.

https://github.com/user-attachments/assets/614475dc-cba5-40ba-b52a-bc797f9fa38e

badsyntax commented 1 week ago

Also, now that we can format within a range, "editor.formatOnSaveMode": "modificationsIfAvailable" & "editor.formatOnSaveMode": "modifications" is now working:

https://github.com/user-attachments/assets/3a98d8ee-afc4-4a7d-980a-77c5ebbb9237