golang.org/x/tools/gopls@v0.15.3/internal/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  
    12  	"golang.org/x/tools/gopls/internal/protocol"
    13  	"golang.org/x/tools/internal/tool"
    14  )
    15  
    16  // highlight implements the highlight verb for gopls.
    17  type highlight struct {
    18  	app *Application
    19  }
    20  
    21  func (r *highlight) Name() string      { return "highlight" }
    22  func (r *highlight) Parent() string    { return r.app.Name() }
    23  func (r *highlight) Usage() string     { return "<position>" }
    24  func (r *highlight) ShortHelp() string { return "display selected identifier's highlights" }
    25  func (r *highlight) DetailedHelp(f *flag.FlagSet) {
    26  	fmt.Fprint(f.Output(), `
    27  Example:
    28  
    29  	$ # 1-indexed location (:line:column or :#offset) of the target identifier
    30  	$ gopls highlight helper/helper.go:8:6
    31  	$ gopls highlight helper/helper.go:#53
    32  `)
    33  	printFlagDefaults(f)
    34  }
    35  
    36  func (r *highlight) Run(ctx context.Context, args ...string) error {
    37  	if len(args) != 1 {
    38  		return tool.CommandLineErrorf("highlight expects 1 argument (position)")
    39  	}
    40  
    41  	conn, err := r.app.connect(ctx, nil)
    42  	if err != nil {
    43  		return err
    44  	}
    45  	defer conn.terminate(ctx)
    46  
    47  	from := parseSpan(args[0])
    48  	file, err := conn.openFile(ctx, from.URI())
    49  	if err != nil {
    50  		return err
    51  	}
    52  
    53  	loc, err := file.spanLocation(from)
    54  	if err != nil {
    55  		return err
    56  	}
    57  
    58  	p := protocol.DocumentHighlightParams{
    59  		TextDocumentPositionParams: protocol.LocationTextDocumentPositionParams(loc),
    60  	}
    61  	highlights, err := conn.DocumentHighlight(ctx, &p)
    62  	if err != nil {
    63  		return err
    64  	}
    65  
    66  	var results []span
    67  	for _, h := range highlights {
    68  		s, err := file.rangeSpan(h.Range)
    69  		if err != nil {
    70  			return err
    71  		}
    72  		results = append(results, s)
    73  	}
    74  	// Sort results to make tests deterministic since DocumentHighlight uses a map.
    75  	sortSpans(results)
    76  
    77  	for _, s := range results {
    78  		fmt.Println(s)
    79  	}
    80  	return nil
    81  }