1
0
mirror of https://github.com/golang/go synced 2024-11-18 08:54:45 -07:00

internal/lsp: support textDocument/formatting for .mod extension

This change implements support for textDocument/formatting when it comes to go.mod files. It also adds formatting on save ability.

To enable formatting on save for go.mod files, you need to include the following settings inside of your VSCode settings.json:

...
"[go.mod]": {
	"editor.codeActionsOnSave": {
		"source.organizeImports": true,
	},
	"editor.formatOnSave": true,
},
...

Updates golang/go#36501

Change-Id: I60ac14d0e99b2b086fe9a8581770771aafc2173c
Reviewed-on: https://go-review.googlesource.com/c/tools/+/221223
Run-TryBot: Rohan Challa <rohan@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Rebecca Stambler <rstambler@golang.org>
This commit is contained in:
Rohan Challa 2020-02-26 17:56:56 -05:00
parent de023d59a5
commit 136c3617b6
3 changed files with 40 additions and 5 deletions

View File

@ -12,6 +12,12 @@ Use the [VSCode-Go] plugin, with the following configuration:
// Optional: Disable snippets, as they conflict with completion ranking.
"editor.snippetSuggestions": "none",
},
"[go.mod]": {
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true,
},
},
"gopls": {
// Add parameter placeholders when completing a function.
"usePlaceholders": true,

View File

@ -7,18 +7,21 @@ package lsp
import (
"context"
"golang.org/x/tools/internal/lsp/mod"
"golang.org/x/tools/internal/lsp/protocol"
"golang.org/x/tools/internal/lsp/source"
)
func (s *Server) formatting(ctx context.Context, params *protocol.DocumentFormattingParams) ([]protocol.TextEdit, error) {
snapshot, fh, ok, err := s.beginFileRequest(params.TextDocument.URI, source.Go)
snapshot, fh, ok, err := s.beginFileRequest(params.TextDocument.URI, source.UnknownKind)
if !ok {
return nil, err
}
edits, err := source.Format(ctx, snapshot, fh)
if err != nil {
return nil, err
switch fh.Identity().Kind {
case source.Mod:
return mod.Format(ctx, snapshot, fh)
case source.Go:
return source.Format(ctx, snapshot, fh)
}
return edits, nil
return nil, nil
}

View File

@ -0,0 +1,26 @@
package mod
import (
"context"
"golang.org/x/tools/internal/lsp/protocol"
"golang.org/x/tools/internal/lsp/source"
"golang.org/x/tools/internal/telemetry/trace"
)
func Format(ctx context.Context, snapshot source.Snapshot, fh source.FileHandle) ([]protocol.TextEdit, error) {
ctx, done := trace.StartSpan(ctx, "mod.Format")
defer done()
file, m, err := snapshot.ModHandle(ctx, fh).Parse(ctx)
if err != nil {
return nil, err
}
formatted, err := file.Format()
if err != nil {
return nil, err
}
// Calculate the edits to be made due to the change.
diff := snapshot.View().Options().ComputeEdits(fh.Identity().URI, string(m.Content), string(formatted))
return source.ToProtocolEdits(m, diff)
}