Skip to content
This repository has been archived by the owner on Jan 16, 2024. It is now read-only.

feat: add fmt capabilities #84

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
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
45 changes: 45 additions & 0 deletions server/handler/documentFormatting.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package handler

import (
"bytes"
"os"

"cuelang.org/go/cue/format"
"github.com/tliron/glsp"
protocol "github.com/tliron/glsp/protocol_3_16"
"go.lsp.dev/uri"
)

func (h *Handler) documentFormatting(_ *glsp.Context, params *protocol.DocumentFormattingParams) ([]protocol.TextEdit, error) {
h.log.Debugf("Format: %s", params.TextDocument.URI)
h.log.Debugf("params: %#v", params)

_uri, err := uri.Parse(params.TextDocument.URI)
source, err := os.ReadFile(_uri.Filename())
if err != nil {
return nil, h.wrapError(err)
}

h.log.Debugf("Find source of %s", _uri.Filename)
_fmt, err := format.Source(source, format.UseSpaces(2), format.TabIndent(false)) // TODO: gather from params.Options?
if err != nil {
return nil, h.wrapError(err)
}

h.log.Debugf("Source formatted: %s", _uri.Filename)
start := protocol.Position{Line: 0, Character: 0}

nl := []byte("\n")
ll := bytes.Count(source, nl)
end := protocol.Position{Line: uint32(ll), Character: 0}

edit := protocol.TextEdit{
Range: protocol.Range{
Start: start,
End: end,
},
NewText: string(_fmt),
}

return []protocol.TextEdit{edit}, nil
}
1 change: 1 addition & 0 deletions server/handler/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ func New(opts ...Options) *Handler {
TextDocumentHover: h.documentHover,
TextDocumentDidChange: h.documentDidChange,
TextDocumentDidClose: h.documentDidClose,
TextDocumentFormatting: h.documentFormatting,
}

return h
Expand Down
3 changes: 3 additions & 0 deletions server/handler/initialize.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,5 +99,8 @@ func (h *Handler) capabilities() protocol.ServerCapabilities {
capabilities.DefinitionProvider = true
capabilities.HoverProvider = true

// Formatting
capabilities.DocumentFormattingProvider = true

return capabilities
}