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
68
69
70
71
72
73
74
75
76
77
|
package provider
import (
"strings"
"github.com/grindlemire/go-tui/internal/formatter"
"github.com/grindlemire/go-tui/internal/lsp/log"
)
type FormattingOptions struct {
TabSize int `json:"tabSize"`
InsertSpaces bool `json:"insertSpaces"`
TrimTrailingWhitespace bool `json:"trimTrailingWhitespace,omitempty"`
InsertFinalNewline bool `json:"insertFinalNewline,omitempty"`
TrimFinalNewlines bool `json:"trimFinalNewlines,omitempty"`
}
type TextEdit struct {
Range Range `json:"range"`
NewText string `json:"newText"`
}
type formattingProvider struct{}
func NewFormattingProvider() FormattingProvider {
return &formattingProvider{}
}
func (f *formattingProvider) Format(doc *Document, opts FormattingOptions) ([]TextEdit, error) {
log.Server("Formatting provider for %s", doc.URI)
fmtr := formatter.New()
if opts.InsertSpaces {
fmtr.IndentString = strings.Repeat(" ", opts.TabSize)
} else {
fmtr.IndentString = "\t"
}
formatted, err := fmtr.Format(doc.URI, doc.Content)
if err != nil {
log.Server("Formatting error: %v", err)
return []TextEdit{}, nil
}
if formatted == doc.Content {
return []TextEdit{}, nil
}
lines := strings.Split(doc.Content, "\n")
lastLine := len(lines) - 1
lastChar := 0
if lastLine >= 0 && len(lines[lastLine]) > 0 {
lastChar = len(lines[lastLine])
}
edits := []TextEdit{
{
Range: Range{
Start: Position{Line: 0, Character: 0},
End: Position{Line: lastLine, Character: lastChar},
},
NewText: formatted,
},
}
return edits, nil
}
|