2018-12-05 15:00:36 -07:00
|
|
|
package lsp
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2019-03-13 17:31:41 -06:00
|
|
|
"fmt"
|
2018-12-05 15:00:36 -07:00
|
|
|
|
|
|
|
"golang.org/x/tools/internal/lsp/protocol"
|
|
|
|
"golang.org/x/tools/internal/lsp/source"
|
2019-02-19 19:11:15 -07:00
|
|
|
"golang.org/x/tools/internal/span"
|
2018-12-05 15:00:36 -07:00
|
|
|
)
|
|
|
|
|
|
|
|
// formatRange formats a document with a given range.
|
2019-02-19 19:11:15 -07:00
|
|
|
func formatRange(ctx context.Context, v source.View, s span.Span) ([]protocol.TextEdit, error) {
|
|
|
|
f, m, err := newColumnMap(ctx, v, s.URI)
|
2019-02-04 15:44:35 -07:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2019-02-19 19:11:15 -07:00
|
|
|
rng := s.Range(m.Converter)
|
|
|
|
if rng.Start == rng.End {
|
2019-03-13 17:31:41 -06:00
|
|
|
// If we have a single point, assume we want the whole file.
|
|
|
|
tok := f.GetToken(ctx)
|
|
|
|
if tok == nil {
|
|
|
|
return nil, fmt.Errorf("no file information for %s", f.URI())
|
|
|
|
}
|
|
|
|
rng.End = tok.Pos(tok.Size())
|
2018-12-18 14:18:03 -07:00
|
|
|
}
|
2019-02-19 19:11:15 -07:00
|
|
|
edits, err := source.Format(ctx, f, rng)
|
2018-12-05 15:00:36 -07:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2019-02-19 19:11:15 -07:00
|
|
|
return toProtocolEdits(m, edits), nil
|
2018-12-05 15:00:36 -07:00
|
|
|
}
|
|
|
|
|
2019-02-19 19:11:15 -07:00
|
|
|
func toProtocolEdits(m *protocol.ColumnMapper, edits []source.TextEdit) []protocol.TextEdit {
|
2018-12-05 15:00:36 -07:00
|
|
|
if edits == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
result := make([]protocol.TextEdit, len(edits))
|
|
|
|
for i, edit := range edits {
|
|
|
|
result[i] = protocol.TextEdit{
|
2019-02-19 19:11:15 -07:00
|
|
|
Range: m.Range(edit.Span),
|
2018-12-05 15:00:36 -07:00
|
|
|
NewText: edit.NewText,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return result
|
|
|
|
}
|
2019-02-19 19:11:15 -07:00
|
|
|
|
|
|
|
func newColumnMap(ctx context.Context, v source.View, uri span.URI) (source.File, *protocol.ColumnMapper, error) {
|
|
|
|
f, err := v.GetFile(ctx, uri)
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
2019-03-13 17:31:41 -06:00
|
|
|
tok := f.GetToken(ctx)
|
|
|
|
if tok == nil {
|
|
|
|
return nil, nil, fmt.Errorf("no file information for %v", f.URI())
|
|
|
|
}
|
|
|
|
m := protocol.NewColumnMapper(f.URI(), f.GetFileSet(ctx), tok, f.GetContent(ctx))
|
2019-02-19 19:11:15 -07:00
|
|
|
return f, m, nil
|
|
|
|
}
|