Skip to content

Add request handlers for document formatting #516

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

Merged
merged 27 commits into from
Jun 14, 2017
Merged
Show file tree
Hide file tree
Changes from 24 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
4c6b4f4
Add stub to handle formatting request
May 30, 2017
ca1f97e
Add handler to format document with default settings
Jun 7, 2017
78ad540
Add formatting related types
Jun 7, 2017
2a83b0f
Remove unused handler from LanguageServer
Jun 7, 2017
44ca6b3
Fix DocumentFormattingParams request type
Jun 7, 2017
0b8e8a2
Add a method to enumerate PSScriptAnalyzer cmdlets
Jun 7, 2017
f09d70c
Execute formatter only if module is present
Jun 7, 2017
3da17ee
Handle null value returned by formatter
Jun 7, 2017
7c3ebf8
Add all formatting types and requests
Jun 7, 2017
2f50051
Convert Range type to class from struct
Jun 7, 2017
d8bf331
Update AnalysisService.Format method
Jun 7, 2017
39d69d4
Add range formatting capability to the server
Jun 7, 2017
d00e2ca
Fix format wrapper method
Jun 7, 2017
c4e8866
Disable server side range formatting
Jun 9, 2017
d799a88
Add CodeFormattingSettings type
Jun 10, 2017
466248e
Make properties of FormattingOptions type public
Jun 10, 2017
fb63ff7
Provide settings for formatting
Jun 10, 2017
9eb1b11
Create an abstract base class for settings
Jun 10, 2017
4c1a861
Create a class to represent editor settings
Jun 10, 2017
404b0ae
Disable server side document formatting capability
Jun 13, 2017
ebb6f03
Capitalize options property in FormattingOptions
Jun 13, 2017
0ebfb5e
Send a range array to Format method
Jun 13, 2017
efd884f
Fix merge conflict in LanguageServer.cs
Jun 13, 2017
2851e80
Remove AbstractSettings base class
Jun 13, 2017
6ac7b0d
Update inline xml documentation
Jun 13, 2017
7fc858b
Remove unused request type and its handler
Jun 13, 2017
d74d369
Fix test failures
Jun 14, 2017
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
95 changes: 95 additions & 0 deletions src/PowerShellEditorServices.Protocol/LanguageServer/Formatting.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//

using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol;

namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer
{
public class DocumentFormattingRequest
{
public static readonly RequestType<DocumentFormattingParams, TextEdit[], object, TextDocumentRegistrationOptions> Type = RequestType<DocumentFormattingParams, TextEdit[], object, TextDocumentRegistrationOptions>.Create("textDocument/formatting");
}

public class DocumentRangeFormattingRequest
{
public static readonly RequestType<DocumentRangeFormattingParams, TextEdit[], object, TextDocumentRegistrationOptions> Type = RequestType<DocumentRangeFormattingParams, TextEdit[], object, TextDocumentRegistrationOptions>.Create("textDocument/rangeFormatting");

}

public class DocumentOnTypeFormattingRequest
{
public static readonly RequestType<DocumentOnTypeFormattingRequest, TextEdit[], object, TextDocumentRegistrationOptions> Type = RequestType<DocumentOnTypeFormattingRequest, TextEdit[], object, TextDocumentRegistrationOptions>.Create("textDocument/onTypeFormatting");

}

public class DocumentRangeFormattingParams
{
/// <summary>
/// The document to format.
/// </summary>
public TextDocumentIdentifier TextDocument { get; set; }

/// <summary>
/// The range to format.
/// </summary>
/// <returns></returns>
public Range Range { get; set; }

/// <summary>
/// The format options.
/// </summary>
public FormattingOptions Options { get; set; }
}

public class DocumentOnTypeFormattingParams
{
/// <summary>
/// The document to format.
/// </summary>
public TextDocumentIdentifier TextDocument { get; set; }

/// <summary>
/// The position at which this request was sent.
/// </summary>
public Position Position { get; set; }

/// <summary>
/// The character that has been typed.
/// </summary>
public string ch { get; set; }

/// <summary>
/// The format options.
/// </summary>
public FormattingOptions options { get; set; }
}

public class DocumentFormattingParams
{
/// <summary>
/// The document to format.
/// </summary>
public TextDocumentIdentifier TextDocument { get; set; }

/// <summary>
/// The format options.
/// </summary>
public FormattingOptions options { get; set; }
}

public class FormattingOptions
{
/// <summary>
/// Size of a tab in spaces.
/// </summary>
public int TabSize { get; set; }

/// <summary>
/// Prefer spaces over tabs.
/// </summary>
public bool InsertSpaces { get; set; }
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public class Hover
{
public MarkedString[] Contents { get; set; }

public Range? Range { get; set; }
public Range Range { get; set; }
}

public class HoverRequest
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ public class TextDocumentChangeEvent
/// Gets or sets the Range where the document was changed. Will
/// be null if the server's TextDocumentSyncKind is Full.
/// </summary>
public Range? Range { get; set; }
public Range Range { get; set; }

/// <summary>
/// Gets or sets the length of the Range being replaced in the
Expand Down Expand Up @@ -267,7 +267,7 @@ public class Position
}

[DebuggerDisplay("Start = {Start.Line}:{Start.Character}, End = {End.Line}:{End.Character}")]
public struct Range
public class Range
{
/// <summary>
/// Gets or sets the starting position of the range.
Expand Down
94 changes: 90 additions & 4 deletions src/PowerShellEditorServices.Protocol/Server/LanguageServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,10 @@ public void Start()
this.messageHandlers.SetRequestHandler(HoverRequest.Type, this.HandleHoverRequest);
this.messageHandlers.SetRequestHandler(WorkspaceSymbolRequest.Type, this.HandleWorkspaceSymbolRequest);
this.messageHandlers.SetRequestHandler(CodeActionRequest.Type, this.HandleCodeActionRequest);
this.messageHandlers.SetRequestHandler(DocumentFormattingRequest.Type, this.HandleDocumentFormattingRequest);
this.messageHandlers.SetRequestHandler(
DocumentRangeFormattingRequest.Type,
this.HandleDocumentRangeFormattingRequest);

this.messageHandlers.SetRequestHandler(ShowOnlineHelpRequest.Type, this.HandleShowOnlineHelpRequest);
this.messageHandlers.SetRequestHandler(ExpandAliasRequest.Type, this.HandleExpandAliasRequest);
Expand Down Expand Up @@ -200,7 +204,8 @@ await requestContext.SendResult(
SignatureHelpProvider = new SignatureHelpOptions
{
TriggerCharacters = new string[] { " " } // TODO: Other characters here?
}
},
DocumentFormattingProvider = false
Copy link
Contributor

Choose a reason for hiding this comment

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

Should this be true? Or are you doing this as a workaround to the FormattingOptions issue?

Copy link
Contributor

Choose a reason for hiding this comment

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

I saw the answer to my question in the other PR :)

Copy link
Author

Choose a reason for hiding this comment

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

Yes, this is part of the workaround - when I started working on this I had set it to true, only to run into the FormattingOptions issue later. So I set to to false, which is redundant as the it would be false by default.

}
});
}
Expand Down Expand Up @@ -541,7 +546,7 @@ protected Task HandleDidChangeTextDocumentNotification(

changedFile.ApplyChange(
GetFileChangeDetails(
textChange.Range.Value,
textChange.Range,
textChange.Text));

changedFiles.Add(changedFile);
Expand Down Expand Up @@ -873,7 +878,7 @@ await editorSession
textDocumentPositionParams.Position.Character + 1);

List<MarkedString> symbolInfo = new List<MarkedString>();
Range? symbolRange = null;
Range symbolRange = null;

if (symbolDetails != null)
{
Expand Down Expand Up @@ -1155,7 +1160,45 @@ await requestContext.SendResult(
codeActionCommands.ToArray());
}

protected Task HandleEvaluateRequest(
protected async Task HandleDocumentFormattingRequest(
DocumentFormattingParams formattingParams,
RequestContext<TextEdit[]> requestContext)
{
var result = await Format(
formattingParams.TextDocument.Uri,
formattingParams.options,
null);

await requestContext.SendResult(new TextEdit[1]
{
new TextEdit
{
NewText = result.Item1,
Range = result.Item2
},
});
}

protected async Task HandleDocumentRangeFormattingRequest(
DocumentRangeFormattingParams formattingParams,
RequestContext<TextEdit[]> requestContext)
{
var result = await Format(
formattingParams.TextDocument.Uri,
formattingParams.Options,
formattingParams.Range);

await requestContext.SendResult(new TextEdit[1]
{
new TextEdit
{
NewText = result.Item1,
Range = result.Item2
},
});
}

protected Task HandleEvaluateRequest(
DebugAdapterMessages.EvaluateRequestArguments evaluateParams,
RequestContext<DebugAdapterMessages.EvaluateResponseBody> requestContext)
{
Expand Down Expand Up @@ -1193,6 +1236,49 @@ protected Task HandleEvaluateRequest(

#region Event Handlers

private async Task<Tuple<string, Range>> Format(
string documentUri,
FormattingOptions options,
Range range)
{
var scriptFile = editorSession.Workspace.GetFile(documentUri);
var pssaSettings = currentSettings.CodeFormatting.GetPSSASettingsHashTable(
options.TabSize,
options.InsertSpaces);

// TODO raise an error event in case format returns null;
string formattedScript;
Range editRange;
var rangeList = range == null ? null : new int[] {
range.Start.Line + 1,
range.Start.Character + 1,
range.End.Line + 1,
range.End.Character + 1};
var extent = scriptFile.ScriptAst.Extent;

// todo create an extension for converting range to script extent
editRange = new Range
{
Start = new Position
{
Line = extent.StartLineNumber - 1,
Character = extent.StartColumnNumber - 1
},
End = new Position
{
Line = extent.EndLineNumber - 1,
Character = extent.EndColumnNumber - 1
}
};

formattedScript = await editorSession.AnalysisService.Format(
scriptFile.Contents,
pssaSettings,
rangeList);
formattedScript = formattedScript ?? scriptFile.Contents;
return Tuple.Create(formattedScript, editRange);
}

private async void PowerShellContext_RunspaceChanged(object sender, Session.RunspaceChangedEventArgs e)
{
await this.messageSender.SendEvent(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@

using System.IO;
using Microsoft.PowerShell.EditorServices.Utility;
using System;
using System.Reflection;
using System.Collections;

namespace Microsoft.PowerShell.EditorServices.Protocol.Server
{
Expand All @@ -14,6 +17,8 @@ public class LanguageServerSettings

public ScriptAnalysisSettings ScriptAnalysis { get; set; }

public CodeFormattingSettings CodeFormatting { get; set; }

public LanguageServerSettings()
{
this.ScriptAnalysis = new ScriptAnalysisSettings();
Expand All @@ -31,6 +36,7 @@ public void Update(
settings.ScriptAnalysis,
workspaceRootPath,
logger);
this.CodeFormatting = new CodeFormattingSettings(settings.CodeFormatting);
}
}
}
Expand Down Expand Up @@ -86,12 +92,92 @@ public void Update(
}
}

public class LanguageServerSettingsWrapper
public class CodeFormattingSettings
{
// NOTE: This property is capitalized as 'Powershell' because the
// mode name sent from the client is written as 'powershell' and
// JSON.net is using camelCasing.
/// <summary>
/// Default constructor.
/// </summary>
public CodeFormattingSettings()
{

}

/// <summary>
/// Copy constructor.
/// </summary>
/// <param name="codeFormattingSettings">An instance of type CodeFormattingSettings.</param>
public CodeFormattingSettings(CodeFormattingSettings codeFormattingSettings)
{
if (codeFormattingSettings == null)
{
throw new ArgumentNullException(nameof(codeFormattingSettings));
}

public LanguageServerSettings Powershell { get; set; }
foreach (var prop in this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
prop.SetValue(this, prop.GetValue(codeFormattingSettings));
}
}

public bool OpenBraceOnSameLine { get; set; }
public bool NewLineAfterOpenBrace { get; set; }
public bool NewLineAfterCloseBrace { get; set; }
public bool WhitespaceBeforeOpenBrace { get; set; }
public bool WhitespaceBeforeOpenParen { get; set; }
public bool WhitespaceAroundOperator { get; set; }
public bool WhitespaceAfterSeparator { get; set; }
public bool IgnoreOneLineBlock { get; set; }
public bool AlignPropertyValuePairs { get; set; }

public Hashtable GetPSSASettingsHashTable(int tabSize, bool insertSpaces)
{
return new Hashtable
{
{"IncludeRules", new string[] {
"PSPlaceCloseBrace",
"PSPlaceOpenBrace",
"PSUseConsistentWhitespace",
"PSUseConsistentIndentation",
"PSAlignAssignmentStatement"
}},
{"Rules", new Hashtable {
{"PSPlaceOpenBrace", new Hashtable {
{"Enable", true},
{"OnSameLine", OpenBraceOnSameLine},
{"NewLineAfter", NewLineAfterOpenBrace},
{"IgnoreOneLineBlock", IgnoreOneLineBlock}
}},
{"PSPlaceCloseBrace", new Hashtable {
{"Enable", true},
{"NewLineAfter", NewLineAfterCloseBrace},
{"IgnoreOneLineBlock", IgnoreOneLineBlock}
}},
{"PSUseConsistentIndentation", new Hashtable {
{"Enable", true},
{"IndentationSize", tabSize}
}},
{"PSUseConsistentWhitespace", new Hashtable {
{"Enable", true},
{"CheckOpenBrace", WhitespaceBeforeOpenBrace},
{"CheckOpenParen", WhitespaceBeforeOpenParen},
{"CheckOperator", WhitespaceAroundOperator},
{"CheckSeparator", WhitespaceAfterSeparator}
}},
{"PSAlignAssignmentStatement", new Hashtable {
{"Enable", true},
{"CheckHashtable", AlignPropertyValuePairs}
}},
}}
};
}
}

public class LanguageServerSettingsWrapper
{
// NOTE: This property is capitalized as 'Powershell' because the
// mode name sent from the client is written as 'powershell' and
// JSON.net is using camelCasing.

public LanguageServerSettings Powershell { get; set; }
}
}
}
Loading