prevent unnecessary indent when formatting doc comment code snippets #5636
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.
Fixes #5623
When formatting code snippets in doc comments, we start by wrapping the content of the code block in an
fn main(){}
and add indentation. We do this because we're about to create an internal rustfmtSession
that will try to parse the input snippet as a crate. In order for that operation to succeed the snippet can only contain top level items like function definitions.To illustrate the transformation, assume we're starting with the following doc comment:
After the transformation rustfmt will actually try to format this:
It turns out that during the transformation described above, we sometimes add indentation to empty lines. This normally isn't an issue because rustfmt removes the redundant indentation while reformatting, but in the event a user adds an inner
#![rustfmt::skip]
attribute to their doc comment snippet the inner attribute will be applied to thefn main(){}
and we'll leave the erroneous indentation in place.So this is what rustfmt will try to reformat:
To prevent this issue entirely we won't add indentation to any line that is empty or only contains whitespace.
r? @calebcartwright