Keep comments that are near an `if`’s condition closer to that condition
See original GitHub issueThe original Prettier 1.13.6 Playground link
Prettier 1.13.6 Playground link
--parser babylon
--trailing-comma false
Prettier 2.1.2 Playground link
--parser babel
Input:
if (foo) { // foo may not exist
doThing(foo);
}
if (foo)
// foo may not exist
{
doThing(foo);
}
if (foo) /* foo may not exist */ {
doThing(foo);
}
Output:
if (foo) {
// foo may not exist
doThing(foo);
}
if (foo) {
// foo may not exist
doThing(foo);
}
if (foo) {
/* foo may not exist */ doThing(foo);
}
In the current output, the comments are moved into the block after the if
.
As for the desired output, I’m not sure in each of the three cases where the comments should go. Either they shouldn’t be moved:
if (foo) { // foo may not exist
doThing(foo);
}
if (foo)
// foo may not exist
{
doThing(foo);
}
if (foo) /* foo may not exist */ {
doThing(foo);
}
Or they should be moved before the if
, rather than into the block after the if
:
// foo may not exist
if (foo) {
doThing(foo);
}
// foo may not exist
if (foo) {
doThing(foo);
}
/* foo may not exist */ if (foo) {
doThing(foo);
}
I think the second case has a higher likelihood of deserving to be moved than the first and third cases.
Related issue
Pull request #672 “Stabilize comments inside of if/then/else before {” made a change related to the last of the three cases, but it simply made the current output stable, rather than changing what that output was.
Similar cases with acceptable output
For completeness, these similar cases are formatted in a way I am okay with, though it’s possible others would want the comment placement to always be preserved:
The original Prettier 1.13.6 Playground link
Prettier 1.13.6 Playground link
--parser babylon
--trailing-comma false
Prettier 2.1.2 Playground link
--parser babel
Input:
if (foo) // foo may not exist
{
doThing(foo);
}
if /* foo may not exist */ (foo) {
doThing(foo);
}
/* foo may not exist */ if (foo) {
doThing(foo);
}
Output:
if (foo) {
// foo may not exist
doThing(foo);
}
if (/* foo may not exist */ foo) {
doThing(foo);
}
/* foo may not exist */ if (foo) {
doThing(foo);
}
Scope of this issue
All of these examples also apply to constructs other than if
, such as while
and for
, that can have comments next to their conditions.
Issue Analytics
- State:
- Created 7 years ago
- Reactions:25
- Comments:15 (7 by maintainers)
Not sure if this has been discussed elsewhere, but when adding comments above
else if
andelse
statements, they are indented to the same level as the previous block rather than to where the closing bracket is:…becomes
I feel like
// Comment 2
and// Comment 3
should be at the same indentation level as// Comment 1
Is August, 2022, still looking for a solution…