@@ -27,6 +27,7 @@ import (
27
27
"golang.org/x/tools/gopls/internal/protocol"
28
28
"golang.org/x/tools/gopls/internal/protocol/command"
29
29
"golang.org/x/tools/gopls/internal/settings"
30
+ "golang.org/x/tools/gopls/internal/util/safetoken"
30
31
"golang.org/x/tools/gopls/internal/util/typesutil"
31
32
"golang.org/x/tools/internal/event"
32
33
"golang.org/x/tools/internal/imports"
@@ -236,6 +237,7 @@ var codeActionProducers = [...]codeActionProducer{
236
237
{kind : settings .RefactorExtractFunction , fn : refactorExtractFunction },
237
238
{kind : settings .RefactorExtractMethod , fn : refactorExtractMethod },
238
239
{kind : settings .RefactorExtractToNewFile , fn : refactorExtractToNewFile },
240
+ {kind : settings .RefactorExtractAllOccursOfExpr , fn : refactorExtractAllOccursOfExpr },
239
241
{kind : settings .RefactorExtractVariable , fn : refactorExtractVariable },
240
242
{kind : settings .RefactorInlineCall , fn : refactorInlineCall , needPkg : true },
241
243
{kind : settings .RefactorRewriteChangeQuote , fn : refactorRewriteChangeQuote },
@@ -458,6 +460,26 @@ func refactorExtractVariable(ctx context.Context, req *codeActionsRequest) error
458
460
return nil
459
461
}
460
462
463
+ // refactorExtractAllOccursOfExpr produces "Extract all occcurrances of expression" code action.
464
+ // See [extractAllOccursOfExpr] for command implementation.
465
+ func refactorExtractAllOccursOfExpr (ctx context.Context , req * codeActionsRequest ) error {
466
+ // Don't suggest if only one expr is found,
467
+ // otherwise will duplicate with [refactorExtractVariable]
468
+ if exprs , ok , _ := canExtractExprs (req .start , req .end , req .pgf .File ); ok && len (exprs ) > 1 {
469
+ startOffset , err := safetoken .Offset (req .pgf .Tok , exprs [0 ].Pos ())
470
+ if err != nil {
471
+ return nil
472
+ }
473
+ endOffset , err := safetoken .Offset (req .pgf .Tok , exprs [0 ].End ())
474
+ if err != nil {
475
+ return nil
476
+ }
477
+ expr := req .pgf .Src [startOffset :endOffset ]
478
+ req .addApplyFixAction (fmt .Sprintf ("Extract %d occcurrances of %s" , len (exprs ), expr ), fixExtractAllOccursOfExpr , req .loc )
479
+ }
480
+ return nil
481
+ }
482
+
461
483
// refactorExtractToNewFile produces "Extract declarations to new file" code actions.
462
484
// See [server.commandHandler.ExtractToNewFile] for command implementation.
463
485
func refactorExtractToNewFile (ctx context.Context , req * codeActionsRequest ) error {
0 commit comments