golang.org/x/tools/gopls@v0.15.3/internal/server/folding_range.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 server
     6  
     7  import (
     8  	"context"
     9  
    10  	"golang.org/x/tools/gopls/internal/file"
    11  	"golang.org/x/tools/gopls/internal/golang"
    12  	"golang.org/x/tools/gopls/internal/protocol"
    13  	"golang.org/x/tools/internal/event"
    14  	"golang.org/x/tools/internal/event/tag"
    15  )
    16  
    17  func (s *server) FoldingRange(ctx context.Context, params *protocol.FoldingRangeParams) ([]protocol.FoldingRange, error) {
    18  	ctx, done := event.Start(ctx, "lsp.Server.foldingRange", tag.URI.Of(params.TextDocument.URI))
    19  	defer done()
    20  
    21  	fh, snapshot, release, err := s.fileOf(ctx, params.TextDocument.URI)
    22  	if err != nil {
    23  		return nil, err
    24  	}
    25  	defer release()
    26  	if snapshot.FileKind(fh) != file.Go {
    27  		return nil, nil // empty result
    28  	}
    29  	ranges, err := golang.FoldingRange(ctx, snapshot, fh, snapshot.Options().LineFoldingOnly)
    30  	if err != nil {
    31  		return nil, err
    32  	}
    33  	return toProtocolFoldingRanges(ranges)
    34  }
    35  
    36  func toProtocolFoldingRanges(ranges []*golang.FoldingRangeInfo) ([]protocol.FoldingRange, error) {
    37  	result := make([]protocol.FoldingRange, 0, len(ranges))
    38  	for _, info := range ranges {
    39  		rng := info.MappedRange.Range()
    40  		result = append(result, protocol.FoldingRange{
    41  			StartLine:      rng.Start.Line,
    42  			StartCharacter: rng.Start.Character,
    43  			EndLine:        rng.End.Line,
    44  			EndCharacter:   rng.End.Character,
    45  			Kind:           string(info.Kind),
    46  		})
    47  	}
    48  	return result, nil
    49  }