-
Notifications
You must be signed in to change notification settings - Fork 6
/
format.go
67 lines (58 loc) · 1.87 KB
/
format.go
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
67
package langserver
import (
"context"
"encoding/json"
"fmt"
"strings"
"github.com/kitagry/regols/langserver/internal/lsp"
"github.com/open-policy-agent/opa/format"
"github.com/sourcegraph/jsonrpc2"
)
func (h *handler) handleTextDocumentFormatting(_ context.Context, _ *jsonrpc2.Conn, req *jsonrpc2.Request) (result any, err error) {
if req.Params == nil {
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams}
}
var params lsp.DocumentFormattingParams
if err := json.Unmarshal(*req.Params, ¶ms); err != nil {
return nil, err
}
rawText, ok := h.project.GetFile(documentURIToURI(params.TextDocument.URI))
if !ok {
return nil, fmt.Errorf("failed to find document %s", params.TextDocument.URI)
}
formatted, err := format.Source(documentURIToURI(params.TextDocument.URI), []byte(rawText))
if !ok {
return nil, fmt.Errorf("failed to format: %w", err)
}
if len(formatted) == 0 {
return nil, nil
}
return ComputeEdits(params.TextDocument.URI, rawText, string(formatted)), nil
}
// ComputeEdits computes diff edits from 2 string inputs
func ComputeEdits(uri lsp.DocumentURI, before, after string) []lsp.TextEdit {
ops := operations(splitLines(before), splitLines(after))
edits := make([]lsp.TextEdit, 0, len(ops))
for _, op := range ops {
switch op.Kind {
case Delete:
// Delete: unformatted[i1:i2] is deleted.
edits = append(edits, lsp.TextEdit{Range: lsp.Range{
Start: lsp.Position{Line: op.I1, Character: 0},
End: lsp.Position{Line: op.I2, Character: 0},
}})
case Insert:
// Insert: formatted[j1:j2] is inserted at unformatted[i1:i1].
if content := strings.Join(op.Content, ""); content != "" {
edits = append(edits, lsp.TextEdit{
Range: lsp.Range{
Start: lsp.Position{Line: op.I1, Character: 0},
End: lsp.Position{Line: op.I2, Character: 0},
},
NewText: content,
})
}
}
}
return edits
}