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

Update formatOnType handler to support formatting on NewLine #76876

Merged
merged 3 commits into from
Jan 23, 2025
Merged
Show file tree
Hide file tree
Changes from 2 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 @@ -44,13 +44,13 @@ public FormatDocumentOnTypeHandler(IGlobalOptionService globalOptions)
if (document is null)
return null;

var position = await document.GetPositionFromLinePositionAsync(ProtocolConversions.PositionToLinePosition(request.Position), cancellationToken).ConfigureAwait(false);

if (string.IsNullOrEmpty(request.Character) || SyntaxFacts.IsNewLine(request.Character[0]))
if (string.IsNullOrEmpty(request.Character))
{
return [];
}

var position = await document.GetPositionFromLinePositionAsync(ProtocolConversions.PositionToLinePosition(request.Position), cancellationToken).ConfigureAwait(false);

var formattingService = document.Project.Services.GetRequiredService<ISyntaxFormattingService>();
var documentSyntax = await ParsedDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);

Expand All @@ -72,6 +72,36 @@ public FormatDocumentOnTypeHandler(IGlobalOptionService globalOptions)
return [];
}

if (SyntaxFacts.IsNewLine(request.Character[0]))
{
// When formatting after a newline is pressed, the cursor line will be all whitespace
// and we do not want to remove the indentation from it.
//
// Take the following example of pressing enter after an opening brace.
//
// ```
// public void M() {||}
// ```
//
// The editor moves the cursor to the next line and uses it's languageconfig to add
// the appropriate level of indentation.
//
// ```
// public void M() {
// ||
// }
// ```
//
// At this point `formatOnType` is called. The formatting service will generate two
// text changes. The first moves the opening brace to the following line with proper
// indentation. The second removes the whitespace from the cursor line.
//
// Letting the second change go through would be a bad experience for the user as they
// will now be responsible for adding back the proper indentation.

textChanges = textChanges.WhereAsArray(static (change, position) => !change.Span.Contains(position), position);
Copy link
Member

Choose a reason for hiding this comment

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

great comment. very helpful. would it make sense to also add a condition that that final span of the change is empty? basically, it would b only filtering out the formatting change that deletes the code the caret it at.

Copy link
Member Author

Choose a reason for hiding this comment

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

Looks like I was imprecise and will update the comment.

The second change runs from the start of the cursor line to the closing brace. It removes the whitespace from the cursor line and rewrites the indentation on the line with the closing brace. The 14 characters \r\n is replaced with \r\n .

}

return [.. textChanges.Select(change => ProtocolConversions.TextChangeToTextEdit(change, documentSyntax.Text))];
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
Expand All @@ -24,74 +23,107 @@ public FormatDocumentOnTypeTests(ITestOutputHelper testOutputHelper) : base(test
public async Task TestFormatDocumentOnTypeAsync(bool mutatingLspWorkspace)
{
var markup =
@"class A
{
void M()
{
if (true)
{{|type:|}
}
}";
"""
class A
{
void M()
{
if (true)
{{|type:|}
}
}
""";
var expected =
@"class A
{
void M()
{
if (true)
{
}
}";
"""
class A
{
void M()
{
if (true)
{
}
}
""";
await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace);
var characterTyped = ";";
var locationTyped = testLspServer.GetLocations("type").Single();
var documentText = await testLspServer.GetDocumentTextAsync(locationTyped.Uri);

var results = await RunFormatDocumentOnTypeAsync(testLspServer, characterTyped, locationTyped);
var actualText = ApplyTextEdits(results, documentText);
Assert.Equal(expected, actualText);
await AssertFormatDocumentOnTypeAsync(testLspServer, characterTyped, locationTyped, expected);
}

[Theory, CombinatorialData]
public async Task TestFormatDocumentOnType_UseTabsAsync(bool mutatingLspWorkspace)
{
var markup =
@"class A
{
void M()
{
if (true)
{{|type:|}
}
}";
"""
class A
{
void M()
{
if (true)
{{|type:|}
}
}
""";
var expected =
@"class A
{
void M()
{
if (true)
{
}
}";
"""
class A
{
void M()
{
if (true)
{
}
}
""";
await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace);
var characterTyped = ";";
var locationTyped = testLspServer.GetLocations("type").Single();
var documentText = await testLspServer.GetDocumentTextAsync(locationTyped.Uri);
await AssertFormatDocumentOnTypeAsync(testLspServer, characterTyped, locationTyped, expected, insertSpaces: false, tabSize: 4);
}

var results = await RunFormatDocumentOnTypeAsync(testLspServer, characterTyped, locationTyped, insertSpaces: false, tabSize: 4);
var actualText = ApplyTextEdits(results, documentText);
Assert.Equal(expected, actualText);
[Theory, CombinatorialData]
public async Task TestFormatDocumentOnType_NewLine(bool mutatingLspWorkspace)
{
var markup =
"""
class A
{
void M() {
{|type:|}
}
}
""";
var expected =
"""
class A
{
void M()
{

}
}
""";
await using var testLspServer = await CreateTestLspServerAsync(markup, mutatingLspWorkspace);
var characterTyped = "\n";
var locationTyped = testLspServer.GetLocations("type").Single();
await AssertFormatDocumentOnTypeAsync(testLspServer, characterTyped, locationTyped, expected);
}

private static async Task<LSP.TextEdit[]> RunFormatDocumentOnTypeAsync(
private static async Task AssertFormatDocumentOnTypeAsync(
TestLspServer testLspServer,
string characterTyped,
LSP.Location locationTyped,
[StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string expectedText,
bool insertSpaces = true,
int tabSize = 4)
{
return await testLspServer.ExecuteRequestAsync<LSP.DocumentOnTypeFormattingParams, LSP.TextEdit[]>(LSP.Methods.TextDocumentOnTypeFormattingName,
CreateDocumentOnTypeFormattingParams(
characterTyped, locationTyped, insertSpaces, tabSize), CancellationToken.None);
var documentText = await testLspServer.GetDocumentTextAsync(locationTyped.Uri);
var results = await testLspServer.ExecuteRequestAsync<LSP.DocumentOnTypeFormattingParams, LSP.TextEdit[]>(
LSP.Methods.TextDocumentOnTypeFormattingName,
CreateDocumentOnTypeFormattingParams(characterTyped, locationTyped, insertSpaces, tabSize),
CancellationToken.None);
var actualText = ApplyTextEdits(results, documentText);
Assert.Equal(expectedText, actualText);
}

private static LSP.DocumentOnTypeFormattingParams CreateDocumentOnTypeFormattingParams(
Expand Down
Loading