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

Preserve Line Breaks Instead of Automatically Merging Code into a Single Line #1512

Open
JasonGrass opened this issue Feb 25, 2025 · 2 comments

Comments

@JasonGrass
Copy link

Input:

For example, given the following code:

var result = list
    .Where(x => x > 5)
    .Where(x => x % 2 == 0)
    .Select(x => x * x)
    .ToList();

Output:

I have not configured printWidth (the default value is 100). When I save the code and trigger code formatting, it changes to:

var result = list.Where(x => x > 5).Where(x => x % 2 == 0).Select(x => x * x).ToList();

Expected behavior:

Only when I modify printWidth to a smaller value, such as 50, does it produce the desired effect.

var result = list
    .Where(x => x > 5)
    .Where(x => x % 2 == 0)
    .Select(x => x * x)
    .ToList();

Is there any way to prevent this behavior?

My Suggestion:

printWidth should only limit the maximum length of a line.
If the line exceeds this maximum length, it should automatically break.
However, if the line does not exceed the maximum length, it should not forcefully merge already broken code into a single line.

I use the CSharpier plugin in Visual Studio for code formatting.
CSharpier - Visual Studio Marketplace
version: 2.0.1

@belav
Copy link
Owner

belav commented Feb 25, 2025

CSharpier does not take into account any existing line breaks when deciding how to format code.

Prettier for the most part functions the exact same way although it does have a couple (possibly controversial) cases where it will format differently based on if the current statement is already broken or not. They have reasons for it being included even though they'd preferred to have avoided it - https://prettier.io/docs/rationale#multi-line-objects

For this specific instance CSharpier may break invocation chains that meet a certain criteria even if they are not longer than the max width, see #792. I don't see CSharpier changing to take into account existing line breaks when dealing with invocations however.

@JasonGrass
Copy link
Author

A brief addition

As a temporary solution, you can use csharpier-ignore to temporarily ignore the automatic formatting for the next line.

// csharpier-ignore
var result = list
    .Where(x => x > 5)
    .Where(x => x % 2 == 0)
    .Select(x => x * x)
    .ToList();

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

No branches or pull requests

2 participants