github.com/april1989/origin-go-tools@v0.0.32/internal/lsp/cmd/highlight.go (about) 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. 4 5 package cmd 6 7 import ( 8 "context" 9 "flag" 10 "fmt" 11 "sort" 12 13 "github.com/april1989/origin-go-tools/internal/lsp/protocol" 14 "github.com/april1989/origin-go-tools/internal/span" 15 "github.com/april1989/origin-go-tools/internal/tool" 16 ) 17 18 // highlight implements the highlight verb for gopls. 19 type highlight struct { 20 app *Application 21 } 22 23 func (r *highlight) Name() string { return "highlight" } 24 func (r *highlight) Usage() string { return "<position>" } 25 func (r *highlight) ShortHelp() string { return "display selected identifier's highlights" } 26 func (r *highlight) DetailedHelp(f *flag.FlagSet) { 27 fmt.Fprint(f.Output(), ` 28 Example: 29 30 $ # 1-indexed location (:line:column or :#offset) of the target identifier 31 $ gopls highlight helper/helper.go:8:6 32 $ gopls highlight helper/helper.go:#53 33 34 gopls highlight flags are: 35 `) 36 f.PrintDefaults() 37 } 38 39 func (r *highlight) Run(ctx context.Context, args ...string) error { 40 if len(args) != 1 { 41 return tool.CommandLineErrorf("highlight expects 1 argument (position)") 42 } 43 44 conn, err := r.app.connect(ctx) 45 if err != nil { 46 return err 47 } 48 defer conn.terminate(ctx) 49 50 from := span.Parse(args[0]) 51 file := conn.AddFile(ctx, from.URI()) 52 if file.err != nil { 53 return file.err 54 } 55 56 loc, err := file.mapper.Location(from) 57 if err != nil { 58 return err 59 } 60 61 p := protocol.DocumentHighlightParams{ 62 TextDocumentPositionParams: protocol.TextDocumentPositionParams{ 63 TextDocument: protocol.TextDocumentIdentifier{URI: loc.URI}, 64 Position: loc.Range.Start, 65 }, 66 } 67 highlights, err := conn.DocumentHighlight(ctx, &p) 68 if err != nil { 69 return err 70 } 71 72 var results []span.Span 73 for _, h := range highlights { 74 l := protocol.Location{Range: h.Range} 75 s, err := file.mapper.Span(l) 76 if err != nil { 77 return err 78 } 79 results = append(results, s) 80 } 81 // Sort results to make tests deterministic since DocumentHighlight uses a map. 82 sort.SliceStable(results, func(i, j int) bool { 83 return span.Compare(results[i], results[j]) == -1 84 }) 85 86 for _, s := range results { 87 fmt.Println(s) 88 } 89 return nil 90 }