1 // Copyright 2019 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
14 "golang.org/x/tools/internal/lsp/protocol"
15 "golang.org/x/tools/internal/span"
16 "golang.org/x/tools/internal/tool"
19 // symbols implements the symbols verb for gopls
24 func (r *symbols) Name() string { return "symbols" }
25 func (r *symbols) Usage() string { return "<file>" }
26 func (r *symbols) ShortHelp() string { return "display selected file's symbols" }
27 func (r *symbols) DetailedHelp(f *flag.FlagSet) {
28 fmt.Fprint(f.Output(), `
30 $ gopls symbols helper/helper.go
34 func (r *symbols) Run(ctx context.Context, args ...string) error {
36 return tool.CommandLineErrorf("symbols expects 1 argument (position)")
39 conn, err := r.app.connect(ctx)
43 defer conn.terminate(ctx)
45 from := span.Parse(args[0])
46 p := protocol.DocumentSymbolParams{
47 TextDocument: protocol.TextDocumentIdentifier{
48 URI: protocol.URIFromSpanURI(from.URI()),
51 symbols, err := conn.DocumentSymbol(ctx, &p)
55 for _, s := range symbols {
56 if m, ok := s.(map[string]interface{}); ok {
57 s, err = mapToSymbol(m)
62 switch t := s.(type) {
63 case protocol.DocumentSymbol:
64 printDocumentSymbol(t)
65 case protocol.SymbolInformation:
66 printSymbolInformation(t)
72 func mapToSymbol(m map[string]interface{}) (interface{}, error) {
73 b, err := json.Marshal(m)
78 if _, ok := m["selectionRange"]; ok {
79 var s protocol.DocumentSymbol
80 if err := json.Unmarshal(b, &s); err != nil {
86 var s protocol.SymbolInformation
87 if err := json.Unmarshal(b, &s); err != nil {
93 func printDocumentSymbol(s protocol.DocumentSymbol) {
94 fmt.Printf("%s %s %s\n", s.Name, s.Kind, positionToString(s.SelectionRange))
95 // Sort children for consistency
96 sort.Slice(s.Children, func(i, j int) bool {
97 return s.Children[i].Name < s.Children[j].Name
99 for _, c := range s.Children {
100 fmt.Printf("\t%s %s %s\n", c.Name, c.Kind, positionToString(c.SelectionRange))
104 func printSymbolInformation(s protocol.SymbolInformation) {
105 fmt.Printf("%s %s %s\n", s.Name, s.Kind, positionToString(s.Location.Range))
108 func positionToString(r protocol.Range) string {
109 return fmt.Sprintf("%v:%v-%v:%v",