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

Commit

Permalink
feat: add fmt capabilities
Browse files Browse the repository at this point in the history
  • Loading branch information
b4nst committed Jul 31, 2022
1 parent e98c200 commit c495dc2
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 0 deletions.
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
}

0 comments on commit c495dc2

Please sign in to comment.