Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DartFormatter class caches line endings from the first format which might produce incorrect results for subsequent formats #1337

Open
DanTup opened this issue Dec 6, 2023 · 1 comment
Labels

Comments

@DanTup
Copy link
Contributor

DanTup commented Dec 6, 2023

I'm not sure if this is strictly a bug, but it feels incorrect. I was investigating an issue at Dart-Code/Dart-Code#4865 where sometimes lots of blank lines were being added when formatting documents.

It seems like there may be two issues:

  1. The formatter changing a file using \n to \r\n
  2. VS Code showing \r\n as if it's two newlines if the file is set to LF mode but contains CRLF.

The reason the first was occurring is that in the analysis server we are currently reusing the DartFormatter instance. This class caches the line ending on first format if it's not explicitly provided. This means if you format a document that uses CRLF and then one that uses LF, it will output CRLF for the second file:

final formatter = DartFormatter();
print(jsonEncode(formatter.format('int a;\r\n'))); // Outputs "int a;\r\n"
print(jsonEncode(formatter.format('int b;\n'))); // Outputs "int b;\r\n" but expected "int b;\n"

I'm going to remove the reuse of this instance from the server (we were discussing this because of language versions anyway), but I thought it was worth raising this because it's not clear if this is expected behaviour.

@munificent
Copy link
Member

Thanks for filing this. The intent has always been that DartFormatter objects are lightweight and short-lived, but it does seem confusing and not useful that it persists the inferred line endings across multiple calls.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants