github.com/jhump/golang-x-tools@v0.0.0-20220218190644-4958d6d39439/internal/lsp/work/format.go (about)

     1  // Copyright 2022 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 work
     6  
     7  import (
     8  	"context"
     9  
    10  	"golang.org/x/mod/modfile"
    11  	"github.com/jhump/golang-x-tools/internal/event"
    12  	"github.com/jhump/golang-x-tools/internal/lsp/protocol"
    13  	"github.com/jhump/golang-x-tools/internal/lsp/source"
    14  )
    15  
    16  func Format(ctx context.Context, snapshot source.Snapshot, fh source.FileHandle) ([]protocol.TextEdit, error) {
    17  	ctx, done := event.Start(ctx, "work.Format")
    18  	defer done()
    19  
    20  	pw, err := snapshot.ParseWork(ctx, fh)
    21  	if err != nil {
    22  		return nil, err
    23  	}
    24  	formatted := modfile.Format(pw.File.Syntax)
    25  	// Calculate the edits to be made due to the change.
    26  	diff, err := snapshot.View().Options().ComputeEdits(fh.URI(), string(pw.Mapper.Content), string(formatted))
    27  	if err != nil {
    28  		return nil, err
    29  	}
    30  	return source.ToProtocolEdits(pw.Mapper, diff)
    31  }