Skip to content
This repository was archived by the owner on Apr 14, 2022. It is now read-only.

Commit 7c9de6c

Browse files
authored
On type formatting (#126)
Implement line formatting via on-type formatting, triggering on newline and semicolon.
1 parent 64590ff commit 7c9de6c

File tree

8 files changed

+2797
-0
lines changed

8 files changed

+2797
-0
lines changed

src/Analysis/Engine/Impl/Infrastructure/Extensions/StringBuilderExtensions.cs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,5 +24,21 @@ public static StringBuilder TrimEnd(this StringBuilder sb) {
2424
}
2525
return sb;
2626
}
27+
28+
public static StringBuilder EnsureEndsWithSpace(this StringBuilder sb, int count = 1, bool allowLeading = false) {
29+
if (sb.Length == 0 && !allowLeading) {
30+
return sb;
31+
}
32+
33+
for (var i = sb.Length - 1; i >= 0 && char.IsWhiteSpace(sb[i]); i--) {
34+
count--;
35+
}
36+
37+
if (count > 0) {
38+
sb.Append(new string(' ', count));
39+
}
40+
41+
return sb;
42+
}
2743
}
2844
}

src/Analysis/Engine/Test/LanguageServerTests.cs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -992,6 +992,42 @@ public async Task ParseAndAnalysisDiagnostics() {
992992
);
993993
}
994994

995+
[TestMethod, Priority(0)]
996+
public async Task OnTypeFormatting() {
997+
using (var s = await CreateServer()) {
998+
var uri = await AddModule(s, "def foo ( ) :\n x = a + b\n x+= 1");
999+
1000+
// Extended tests for line formatting are in LineFormatterTests.
1001+
// These just verify that the language server formats and returns something correct.
1002+
var edits = await s.SendDocumentOnTypeFormatting(uri, new SourceLocation(2, 1), "\n");
1003+
edits.Should().OnlyContain(new TextEdit {
1004+
newText = "def foo():",
1005+
range = new Range {
1006+
start = new SourceLocation(1, 1),
1007+
end = new SourceLocation(1, 15)
1008+
}
1009+
});
1010+
1011+
edits = await s.SendDocumentOnTypeFormatting(uri, new SourceLocation(3, 1), "\n");
1012+
edits.Should().OnlyContain(new TextEdit {
1013+
newText = "x = a + b",
1014+
range = new Range {
1015+
start = new SourceLocation(2, 5),
1016+
end = new SourceLocation(2, 14)
1017+
}
1018+
});
1019+
1020+
edits = await s.SendDocumentOnTypeFormatting(uri, new SourceLocation(4, 1), "\n");
1021+
edits.Should().OnlyContain(new TextEdit {
1022+
newText = "x += 1",
1023+
range = new Range {
1024+
start = new SourceLocation(3, 5),
1025+
end = new SourceLocation(3, 10)
1026+
}
1027+
});
1028+
}
1029+
}
1030+
9951031
class GetAllExtensionProvider : ILanguageServerExtensionProvider {
9961032
public Task<ILanguageServerExtension> CreateAsync(IPythonLanguageServer server, IReadOnlyDictionary<string, object> properties, CancellationToken cancellationToken) {
9971033
return Task.FromResult<ILanguageServerExtension>(new GetAllExtension((Server)server, properties));

0 commit comments

Comments
 (0)