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) {
|
2019-03-15 11:19:43 -06:00
|
|
|
f, m, err := newColumnMap(ctx, v, s.URI())
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
rng, err := s.Range(m.Converter)
|
2019-02-04 15:44:35 -07:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2019-02-19 19:11:15 -07:00
|
|
|
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-03-15 11:19:43 -06:00
|
|
|
return toProtocolEdits(m, edits)
|
2018-12-05 15:00:36 -07:00
|
|
|
}
|
|
|
|
|
2019-03-15 11:19:43 -06:00
|
|
|
func toProtocolEdits(m *protocol.ColumnMapper, edits []source.TextEdit) ([]protocol.TextEdit, error) {
|
2018-12-05 15:00:36 -07:00
|
|
|
if edits == nil {
|
2019-03-15 11:19:43 -06:00
|
|
|
return nil, nil
|
2018-12-05 15:00:36 -07:00
|
|
|
}
|
|
|
|
result := make([]protocol.TextEdit, len(edits))
|
|
|
|
for i, edit := range edits {
|
2019-03-15 11:19:43 -06:00
|
|
|
rng, err := m.Range(edit.Span)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2018-12-05 15:00:36 -07:00
|
|
|
result[i] = protocol.TextEdit{
|
2019-03-15 11:19:43 -06:00
|
|
|
Range: rng,
|
2018-12-05 15:00:36 -07:00
|
|
|
NewText: edit.NewText,
|
|
|
|
}
|
|
|
|
}
|
2019-03-15 11:19:43 -06:00
|
|
|
return result, nil
|
2018-12-05 15:00:36 -07:00
|
|
|
}
|
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
|
|
|
|
}
|