Skip to content

Commit ca1f97e

Browse files
author
Kapil Borle
committed
Add handler to format document with default settings
1 parent 4c6b4f4 commit ca1f97e

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

src/PowerShellEditorServices.Protocol/Server/LanguageServer.cs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1158,6 +1158,34 @@ protected async Task HandleDocumentFormattingRequest(
11581158
{
11591159
// TODO Get settings
11601160
// TODO Update settings to store code formatting settings
1161+
var scriptFile = editorSession.Workspace.GetFile(formattingParams.TextDocument.Uri);
1162+
var formattedScript = await editorSession.AnalysisService.Format(scriptFile.Contents);
1163+
var extent = scriptFile.ScriptAst.Extent;
1164+
1165+
// todo create an extension for this
1166+
var editRange = new Range
1167+
{
1168+
Start = new Position
1169+
{
1170+
Line = extent.StartLineNumber - 1,
1171+
Character = extent.StartColumnNumber - 1
1172+
},
1173+
End = new Position
1174+
{
1175+
Line = extent.EndLineNumber - 1,
1176+
Character = extent.EndColumnNumber - 1
1177+
}
1178+
};
1179+
1180+
await requestContext.SendResult(new TextEdit[1]
1181+
{
1182+
new TextEdit
1183+
{
1184+
Range = editRange,
1185+
NewText = formattedScript
1186+
},
1187+
1188+
});
11611189
}
11621190

11631191
protected Task HandleEvaluateRequest(

src/PowerShellEditorServices/Analysis/AnalysisService.cs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,6 +245,17 @@ public IEnumerable<string> GetPSScriptAnalyzerRules()
245245
return ruleNames;
246246
}
247247

248+
public async Task<string> Format(string scriptDefinition)
249+
{
250+
var result = InvokePowerShellAsync(
251+
"Invoke-Formatter",
252+
new Dictionary<string, object> {
253+
{"ScriptDefinition", scriptDefinition}
254+
});
255+
256+
return (await result)?.Select(r => r.ImmediateBaseObject as string).FirstOrDefault();
257+
}
258+
248259
/// <summary>
249260
/// Disposes the runspace being used by the analysis service.
250261
/// </summary>

0 commit comments

Comments
 (0)