Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -162,27 +162,6 @@ public async Task<ImmutableArray<TextChange>> ExecuteAsync(FormattingContext con
// We need to take into account the lines affected by formatting as well as cleanup.
var lineDelta = LineDelta(formattedText, cleanupChanges, out var firstLine, out var lastLine);

// Okay hear me out, I know this looks lazy, but it totally makes sense.
// This method is called with edits that the C# formatter wants to make, and from those edits we work out which
// other edits to apply etc. Fine, all good so far. BUT its totally possible that the user typed a closing brace
// in the same position as the C# formatter thought it should be, on the line _after_ the code that the C# formatter
// reformatted.
//
// For example, given:
// if (true){
// }
//
// If the C# formatter is happy with the placement of that close brace then this method will get two edits:
// * On line 1 to indent the if by 4 spaces
// * On line 1 to add a newline and 4 spaces in front of the opening brace
//
// We'll happy format lines 1 and 2, and ignore the closing brace altogether. So, by looking one line further
// we won't have that problem.
if (linePositionSpanAfterFormatting.End.Line + lineDelta < cleanedText.Lines.Count - 1)
{
lineDelta++;
}

// Now we know how many lines were affected by the cleanup and formatting, but we don't know where those lines are. For example, given:
//
// @if (true)
Expand All @@ -199,6 +178,25 @@ public async Task<ImmutableArray<TextChange>> ExecuteAsync(FormattingContext con
var startLine = Math.Min(firstLine, linePositionSpanAfterFormatting.Start.Line);
var endLineInclusive = Math.Max(lastLine, linePositionSpanAfterFormatting.End.Line + lineDelta);

if (context.TriggerCharacter != '\0')

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What does the triggerCharacter being "null" signify? That there isn't a cursor?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, this formatting pipeline is used for code actions and snippets too; anything where we have edits to the generated C# we need to format, so those don't have trigger characters or cursor positions.

{
// Track through the combined formatting and cleanup changes so the position is translated directly into the cleaned text.
var hostDocumentIndex = TrackPositionForward(context.HostDocumentIndex, cleanedText.GetChangeRanges(originalText));

// The line containing the typed character can follow the last C# edit. Include it when adjacent, but not an arbitrary
// following line, which may contain unrelated code that looks nested while the user is still typing.
var typedCharacterLine = cleanedText.GetLinePosition(hostDocumentIndex).Line;
if (typedCharacterLine == endLineInclusive + 1)
{
endLineInclusive++;
}
}
else if (linePositionSpanAfterFormatting.End.Line + lineDelta < cleanedText.Lines.Count - 1)
{
// Without a cursor, include one extra line to ensure inserted constructs have their final line indented.
endLineInclusive = Math.Max(endLineInclusive, linePositionSpanAfterFormatting.End.Line + lineDelta + 1);
}

Debug.Assert(cleanedText.Lines.Count > endLineInclusive, "Invalid range. This is unexpected.");

var indentationChanges = await AdjustIndentationAsync(changedContext, startLine, endLineInclusive, roslynWorkspaceHelper.HostWorkspaceServices, _logger, cancellationToken).ConfigureAwait(false);
Expand All @@ -214,6 +212,39 @@ public async Task<ImmutableArray<TextChange>> ExecuteAsync(FormattingContext con
return SourceTextDiffer.GetMinimalTextChanges(originalText, cleanedText, DiffKind.Char);
}

/// <summary>
/// Tracks a position from the original text into the text produced by applying <paramref name="changes"/>.
/// </summary>
private static int TrackPositionForward(int position, IReadOnlyList<TextChangeRange> changes)
{
var delta = 0;
TextChangeRange? containingChange = null;

foreach (var change in changes)
{
// The changes use original-text coordinates, so accumulate the net length of changes before the position.
// The strict start check keeps an insertion at the position on the right side of the tracked position.
if (change.Span.End <= position && change.Span.Start < position)
{
delta += change.NewLength - change.Span.Length;
}
else if (change.Span.Start < position && position < change.Span.End)
{
// Remember a replacement containing the position; its start still needs the preceding changes' delta.
containingChange = change;
}
}

if (containingChange is { } containing)
{
// Preserve the position's relative offset within the replacement, clamping it if the new text is shorter.
var offset = Math.Min(position - containing.Span.Start, containing.NewLength);
return containing.Span.Start + delta + offset;
}

return position + delta;
}

// Returns the minimal TextSpan that encompasses all the differences between the old and the new text.
private static SourceText ApplyChangesAndTrackChange(SourceText oldText, ImmutableArray<TextChange> changes, out TextSpan spanBeforeChange, out TextSpan spanAfterChange)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,40 @@ public void Foo
triggerCharacter: '}');
}

[FormattingTestFact]
[WorkItem("https://github.com/dotnet/razor/issues/7962")]
public async Task CloseCurly_DoesNotIndentPropertyAfterCursorAsync()
{
await RunOnTypeFormattingTestAsync(
input: """
@code {
private void Current()
{
if(true)
{
}$$
[Parameter] public int Value { get; set; }
private void Later()
{
}
}
""",
expected: """
@code {
private void Current()
{
if (true)
{
}
[Parameter] public int Value { get; set; }
private void Later()
{
}
}
""",
triggerCharacter: '}');
}

[FormattingTestFact]
public async Task CloseCurly_Property_SingleLineAsync()
{
Expand Down