forked from Azure/bicep
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBicepDocumentFormattingHandler.cs
66 lines (55 loc) · 2.73 KB
/
BicepDocumentFormattingHandler.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Threading;
using System.Threading.Tasks;
using Bicep.Core.PrettyPrint;
using Bicep.LanguageServer.CompilationManager;
using Bicep.LanguageServer.Utils;
using OmniSharp.Extensions.LanguageServer.Protocol.Document;
using OmniSharp.Extensions.LanguageServer.Protocol.Models;
using Bicep.Core.PrettyPrint.Options;
using Microsoft.Extensions.Logging;
using Bicep.Core.Syntax;
using Bicep.LanguageServer.Extensions;
using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities;
namespace Bicep.LanguageServer.Handlers
{
public class BicepDocumentFormattingHandler : DocumentFormattingHandlerBase
{
private readonly ILogger<BicepDocumentSymbolHandler> logger;
private readonly ICompilationManager compilationManager;
public BicepDocumentFormattingHandler(ILogger<BicepDocumentSymbolHandler> logger, ICompilationManager compilationManager)
{
this.logger = logger;
this.compilationManager = compilationManager;
}
public override Task<TextEditContainer?> Handle(DocumentFormattingParams request, CancellationToken cancellationToken)
{
CompilationContext? context = this.compilationManager.GetCompilation(request.TextDocument.Uri);
if (context == null)
{
// we have not yet compiled this document, which shouldn't really happen
this.logger.LogError("Document formatting request arrived before file {Uri} could be compiled.", request.TextDocument.Uri);
return Task.FromResult<TextEditContainer?>(null);
}
long indentSize = request.Options.TabSize;
IndentKindOption indentKindOption = request.Options.InsertSpaces ? IndentKindOption.Space : IndentKindOption.Tab;
ProgramSyntax programSyntax = context.ProgramSyntax;
PrettyPrintOptions options = new PrettyPrintOptions(NewlineOption.Auto, indentKindOption, indentSize, request.Options.InsertFinalNewline);
string? output = PrettyPrinter.PrintProgram(programSyntax, options);
if (output == null)
{
return Task.FromResult<TextEditContainer?>(null);
}
return Task.FromResult<TextEditContainer?>(new TextEditContainer(new TextEdit
{
Range = programSyntax.Span.ToRange(context.LineStarts),
NewText = output
}));
}
protected override DocumentFormattingRegistrationOptions CreateRegistrationOptions(DocumentFormattingCapability capability, ClientCapabilities clientCapabilities) => new()
{
DocumentSelector = DocumentSelectorFactory.Create()
};
}
}