settings

package
v0.0.0-...-395a15b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 21, 2024 License: BSD-3-Clause Imports: 69 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// source
	GoAssembly    protocol.CodeActionKind = "source.assembly"
	GoDoc         protocol.CodeActionKind = "source.doc"
	GoFreeSymbols protocol.CodeActionKind = "source.freesymbols"
	GoTest        protocol.CodeActionKind = "source.test"

	// gopls
	GoplsDocFeatures protocol.CodeActionKind = "gopls.doc.features"

	// refactor.rewrite
	RefactorRewriteChangeQuote       protocol.CodeActionKind = "refactor.rewrite.changeQuote"
	RefactorRewriteFillStruct        protocol.CodeActionKind = "refactor.rewrite.fillStruct"
	RefactorRewriteFillSwitch        protocol.CodeActionKind = "refactor.rewrite.fillSwitch"
	RefactorRewriteInvertIf          protocol.CodeActionKind = "refactor.rewrite.invertIf"
	RefactorRewriteJoinLines         protocol.CodeActionKind = "refactor.rewrite.joinLines"
	RefactorRewriteRemoveUnusedParam protocol.CodeActionKind = "refactor.rewrite.removeUnusedParam"
	RefactorRewriteSplitLines        protocol.CodeActionKind = "refactor.rewrite.splitLines"

	// refactor.inline
	RefactorInlineCall protocol.CodeActionKind = "refactor.inline.call"

	// refactor.extract
	RefactorExtractFunction  protocol.CodeActionKind = "refactor.extract.function"
	RefactorExtractMethod    protocol.CodeActionKind = "refactor.extract.method"
	RefactorExtractVariable  protocol.CodeActionKind = "refactor.extract.variable"
	RefactorExtractToNewFile protocol.CodeActionKind = "refactor.extract.toNewFile"
)
  • VS Code

CodeAction kinds specific to gopls

See ../protocol/tsprotocol.go for LSP standard kinds, including

quickfix
refactor
refactor.extract
refactor.inline
refactor.move
refactor.rewrite
source
source.organizeImports
source.fixAll
notebook

Kinds are hierarchical: "refactor" subsumes "refactor.inline", which subsumes "refactor.inline.call". This rule implies that the empty string, confusingly named protocol.Empty, subsumes all kinds. The "Only" field in a CodeAction request may specify a category such as "refactor"; any matching code action will be returned.

All CodeActions returned by gopls use a specific leaf kind such as "refactor.inline.call", except for quick fixes, which all use "quickfix". TODO(adonovan): perhaps quick fixes should also be hierarchical (e.g. quickfix.govulncheck.{reset,upgrade})?

VS Code

The effects of CodeActionKind on the behavior of VS Code are baffling and undocumented. Here's what we have observed.

Clicking on the "Refactor..." menu item shows a submenu of actions with kind="refactor.*", and clicking on "Source action..." shows actions with kind="source.*". A lightbulb appears in both cases.

A third menu, "Quick fix...", not found on the usual context menu but accessible through the command palette or "⌘.", does not set the Only field in its request, so the set of kinds is determined by how the server interprets the default. The LSP 3.18 guidance is that this should be treated equivalent to Only=["quickfix"], and that is what gopls now does. (If the server responds with more kinds, they will be displayed in menu subsections.)

All of these CodeAction requests have triggerkind=Invoked.

Cursor motion also performs a CodeAction request, but with triggerkind=Automatic. Even if this returns a mix of action kinds, only the "refactor" and "quickfix" actions seem to matter. A lightbulb appears if that subset of actions is non-empty, and the menu displays them. (This was noisy--see #65167--so gopls now only reports diagnostic-associated code actions if kind is Invoked or missing.)

None of these CodeAction requests specifies a "kind" restriction; the filtering is done on the response, by the client.

In all these menus, VS Code organizes the actions' menu items into groups based on their kind, with hardwired captions such as "Refactor...", "Extract", "Inline", "More actions", and "Quick fix".

The special category "source.fixAll" is intended for actions that are unambiguously safe to apply so that clients may automatically apply all actions matching this category on save. (That said, this is not VS Code's default behavior; see editor.codeActionsOnSave.)

Variables

View Source
var DefaultAnalyzers = make(map[string]*Analyzer) // initialized below

DefaultAnalyzers holds the set of Analyzers available to all gopls sessions, independent of build version, keyed by analyzer name.

It is the source from which gopls/doc/analyzers.md is generated.

View Source
var StaticcheckAnalyzers = make(map[string]*Analyzer) // written by analysis_<ver>.go

StaticcheckAnalzyers describes available Staticcheck analyzers, keyed by analyzer name.

Functions

This section is empty.

Types

type Analyzer

type Analyzer struct {
	// contains filtered or unexported fields
}

Analyzer augments a analysis.Analyzer with additional LSP configuration.

Analyzers are immutable, since they are shared across multiple LSP sessions.

func (*Analyzer) ActionKinds

func (a *Analyzer) ActionKinds() []protocol.CodeActionKind

ActionKinds is the set of kinds of code action this analyzer produces.

If left unset, it defaults to QuickFix. TODO(rfindley): revisit.

func (*Analyzer) Analyzer

func (a *Analyzer) Analyzer() *analysis.Analyzer

Analyzer returns the analysis.Analyzer that this Analyzer wraps.

func (*Analyzer) EnabledByDefault

func (a *Analyzer) EnabledByDefault() bool

EnabledByDefault reports whether the analyzer is enabled by default for all sessions. This value can be configured per-analysis in user settings.

func (*Analyzer) Severity

func (a *Analyzer) Severity() protocol.DiagnosticSeverity

Severity is the severity set for diagnostics reported by this analyzer. If left unset it defaults to Warning.

Note: diagnostics with severity protocol.SeverityHint do not show up in the VS Code "problems" tab.

func (*Analyzer) String

func (a *Analyzer) String() string

String returns the name of this analyzer.

func (*Analyzer) Tags

func (a *Analyzer) Tags() []protocol.DiagnosticTag

Tags is extra tags (unnecessary, deprecated, etc) for diagnostics reported by this analyzer.

type Annotation

type Annotation string
const (
	// Nil controls nil checks.
	Nil Annotation = "nil"

	// Escape controls diagnostics about escape choices.
	Escape Annotation = "escape"

	// Inline controls diagnostics about inlining choices.
	Inline Annotation = "inline"

	// Bounds controls bounds checking diagnostics.
	Bounds Annotation = "bounds"
)

type BuildOptions

type BuildOptions struct {
	// BuildFlags is the set of flags passed on to the build system when invoked.
	// It is applied to queries like `go list`, which is used when discovering files.
	// The most common use is to set `-tags`.
	BuildFlags []string

	// Env adds environment variables to external commands run by `gopls`, most notably `go list`.
	Env map[string]string

	// DirectoryFilters can be used to exclude unwanted directories from the
	// workspace. By default, all directories are included. Filters are an
	// operator, `+` to include and `-` to exclude, followed by a path prefix
	// relative to the workspace folder. They are evaluated in order, and
	// the last filter that applies to a path controls whether it is included.
	// The path prefix can be empty, so an initial `-` excludes everything.
	//
	// DirectoryFilters also supports the `**` operator to match 0 or more directories.
	//
	// Examples:
	//
	// Exclude node_modules at current depth: `-node_modules`
	//
	// Exclude node_modules at any depth: `-**/node_modules`
	//
	// Include only project_a: `-` (exclude everything), `+project_a`
	//
	// Include only project_a, but not node_modules inside it: `-`, `+project_a`, `-project_a/node_modules`
	DirectoryFilters []string

	// TemplateExtensions gives the extensions of file names that are treated
	// as template files. (The extension
	// is the part of the file name after the final dot.)
	TemplateExtensions []string

	// obsolete, no effect
	MemoryMode string `status:"experimental"`

	// ExpandWorkspaceToModule determines which packages are considered
	// "workspace packages" when the workspace is using modules.
	//
	// Workspace packages affect the scope of workspace-wide operations. Notably,
	// gopls diagnoses all packages considered to be part of the workspace after
	// every keystroke, so by setting "ExpandWorkspaceToModule" to false, and
	// opening a nested workspace directory, you can reduce the amount of work
	// gopls has to do to keep your workspace up to date.
	ExpandWorkspaceToModule bool `status:"experimental"`

	// AllowImplicitNetworkAccess disables GOPROXY=off, allowing implicit module
	// downloads rather than requiring user action. This option will eventually
	// be removed.
	AllowImplicitNetworkAccess bool `status:"experimental"`

	// StandaloneTags specifies a set of build constraints that identify
	// individual Go source files that make up the entire main package of an
	// executable.
	//
	// A common example of standalone main files is the convention of using the
	// directive `//go:build ignore` to denote files that are not intended to be
	// included in any package, for example because they are invoked directly by
	// the developer using `go run`.
	//
	// Gopls considers a file to be a standalone main file if and only if it has
	// package name "main" and has a build directive of the exact form
	// "//go:build tag" or "// +build tag", where tag is among the list of tags
	// configured by this setting. Notably, if the build constraint is more
	// complicated than a simple tag (such as the composite constraint
	// `//go:build tag && go1.18`), the file is not considered to be a standalone
	// main file.
	//
	// This setting is only supported when gopls is built with Go 1.16 or later.
	StandaloneTags []string
}

Note: BuildOptions must be comparable with reflect.DeepEqual.

type ClientOptions

type ClientOptions struct {
	ClientInfo                                 protocol.ClientInfo
	InsertTextFormat                           protocol.InsertTextFormat
	InsertReplaceSupported                     bool
	ConfigurationSupported                     bool
	DynamicConfigurationSupported              bool
	DynamicRegistrationSemanticTokensSupported bool
	DynamicWatchedFilesSupported               bool
	RelativePatternsSupported                  bool
	PreferredContentFormat                     protocol.MarkupKind
	LineFoldingOnly                            bool
	HierarchicalDocumentSymbolSupport          bool
	SemanticTypes                              []string
	SemanticMods                               []string
	RelatedInformationSupported                bool
	CompletionTags                             bool
	CompletionDeprecated                       bool
	SupportedResourceOperations                []protocol.ResourceOperationKind
	CodeActionResolveOptions                   []string
}

ClientOptions holds LSP-specific configuration that is provided by the client.

ClientOptions must be comparable with reflect.DeepEqual.

type CodeLensSource

type CodeLensSource string

A CodeLensSource identifies an (algorithmic) source of code lenses.

const (
	// Toggle display of Go compiler optimization decisions
	//
	// This codelens source causes the `package` declaration of
	// each file to be annotated with a command to toggle the
	// state of the per-session variable that controls whether
	// optimization decisions from the Go compiler (formerly known
	// as "gc") should be displayed as diagnostics.
	//
	// Optimization decisions include:
	// - whether a variable escapes, and how escape is inferred;
	// - whether a nil-pointer check is implied or eliminated;
	// - whether a function can be inlined.
	//
	// TODO(adonovan): this source is off by default because the
	// annotation is annoying and because VS Code has a separate
	// "Toggle gc details" command. Replace it with a Code Action
	// ("Source action...").
	CodeLensGCDetails CodeLensSource = "gc_details"

	// Run `go generate`
	//
	// This codelens source annotates any `//go:generate` comments
	// with commands to run `go generate` in this directory, on
	// all directories recursively beneath this one.
	//
	// See [Generating code](https://go.dev/blog/generate) for
	// more details.
	CodeLensGenerate CodeLensSource = "generate"

	// Re-generate cgo declarations
	//
	// This codelens source annotates an `import "C"` declaration
	// with a command to re-run the [cgo
	// command](https://pkg.go.dev/cmd/cgo) to regenerate the
	// corresponding Go declarations.
	//
	// Use this after editing the C code in comments attached to
	// the import, or in C header files included by it.
	CodeLensRegenerateCgo CodeLensSource = "regenerate_cgo"

	// Run govulncheck
	//
	// This codelens source annotates the `module` directive in a
	// go.mod file with a command to run Govulncheck.
	//
	// [Govulncheck](https://go.dev/blog/vuln) is a static
	// analysis tool that computes the set of functions reachable
	// within your application, including dependencies;
	// queries a database of known security vulnerabilities; and
	// reports any potential problems it finds.
	CodeLensRunGovulncheck CodeLensSource = "run_govulncheck"

	// Run tests and benchmarks
	//
	// This codelens source annotates each `Test` and `Benchmark`
	// function in a `*_test.go` file with a command to run it.
	//
	// This source is off by default because VS Code has
	// a client-side custom UI for testing, and because progress
	// notifications are not a great UX for streamed test output.
	// See:
	// - golang/go#67400 for a discussion of this feature.
	// - https://github.com/joaotavora/eglot/discussions/1402
	//   for an alternative approach.
	CodeLensTest CodeLensSource = "test"

	// Tidy go.mod file
	//
	// This codelens source annotates the `module` directive in a
	// go.mod file with a command to run [`go mod
	// tidy`](https://go.dev/ref/mod#go-mod-tidy), which ensures
	// that the go.mod file matches the source code in the module.
	CodeLensTidy CodeLensSource = "tidy"

	// Update dependencies
	//
	// This codelens source annotates the `module` directive in a
	// go.mod file with commands to:
	//
	// - check for available upgrades,
	// - upgrade direct dependencies, and
	// - upgrade all dependencies transitively.
	CodeLensUpgradeDependency CodeLensSource = "upgrade_dependency"

	// Update vendor directory
	//
	// This codelens source annotates the `module` directive in a
	// go.mod file with a command to run [`go mod
	// vendor`](https://go.dev/ref/mod#go-mod-vendor), which
	// creates or updates the directory named `vendor` in the
	// module root so that it contains an up-to-date copy of all
	// necessary package dependencies.
	CodeLensVendor CodeLensSource = "vendor"
)

CodeLens sources

These identifiers appear in the "codelenses" configuration setting, and in the user documentation thereof, which is generated by gopls/doc/generate/generate.go parsing this file.

Doc comments should use GitHub Markdown. The first line becomes the title.

(For historical reasons, each code lens source identifier typically matches the name of one of the command.Commands returned by it, but that isn't essential.)

type CompletionOptions

type CompletionOptions struct {
	// Placeholders enables placeholders for function parameters or struct
	// fields in completion responses.
	UsePlaceholders bool

	// CompletionBudget is the soft latency goal for completion requests. Most
	// requests finish in a couple milliseconds, but in some cases deep
	// completions can take much longer. As we use up our budget we
	// dynamically reduce the search scope to ensure we return timely
	// results. Zero means unlimited.
	CompletionBudget time.Duration `status:"debug"`

	// Matcher sets the algorithm that is used when calculating completion
	// candidates.
	Matcher Matcher `status:"advanced"`

	// ExperimentalPostfixCompletions enables artificial method snippets
	// such as "someSlice.sort!".
	ExperimentalPostfixCompletions bool `status:"experimental"`

	// CompleteFunctionCalls enables function call completion.
	//
	// When completing a statement, or when a function return type matches the
	// expected of the expression being completed, completion may suggest call
	// expressions (i.e. may include parentheses).
	CompleteFunctionCalls bool
}

Note: CompletionOptions must be comparable with reflect.DeepEqual.

type DiagnosticOptions

type DiagnosticOptions struct {
	// Analyses specify analyses that the user would like to enable or disable.
	// A map of the names of analysis passes that should be enabled/disabled.
	// A full list of analyzers that gopls uses can be found in
	// [analyzers.md](https://github.com/golang/tools/blob/master/gopls/doc/analyzers.md).
	//
	// Example Usage:
	//
	// “`json5
	// ...
	// "analyses": {
	//   "unreachable": false, // Disable the unreachable analyzer.
	//   "unusedvariable": true  // Enable the unusedvariable analyzer.
	// }
	// ...
	// “`
	Analyses map[string]bool

	// Staticcheck enables additional analyses from staticcheck.io.
	// These analyses are documented on
	// [Staticcheck's website](https://staticcheck.io/docs/checks/).
	Staticcheck bool `status:"experimental"`

	// Annotations specifies the various kinds of optimization diagnostics
	// that should be reported by the gc_details command.
	Annotations map[Annotation]bool `status:"experimental"`

	// Vulncheck enables vulnerability scanning.
	Vulncheck VulncheckMode `status:"experimental"`

	// DiagnosticsDelay controls the amount of time that gopls waits
	// after the most recent file modification before computing deep diagnostics.
	// Simple diagnostics (parsing and type-checking) are always run immediately
	// on recently modified packages.
	//
	// This option must be set to a valid duration string, for example `"250ms"`.
	DiagnosticsDelay time.Duration `status:"advanced"`

	// DiagnosticsTrigger controls when to run diagnostics.
	DiagnosticsTrigger DiagnosticsTrigger `status:"experimental"`

	// AnalysisProgressReporting controls whether gopls sends progress
	// notifications when construction of its index of analysis facts is taking a
	// long time. Cancelling these notifications will cancel the indexing task,
	// though it will restart after the next change in the workspace.
	//
	// When a package is opened for the first time and heavyweight analyses such as
	// staticcheck are enabled, it can take a while to construct the index of
	// analysis facts for all its dependencies. The index is cached in the
	// filesystem, so subsequent analysis should be faster.
	AnalysisProgressReporting bool
}

Note: DiagnosticOptions must be comparable with reflect.DeepEqual.

type DiagnosticsTrigger

type DiagnosticsTrigger string
const (
	// Trigger diagnostics on file edit and save. (default)
	DiagnosticsOnEdit DiagnosticsTrigger = "Edit"
	// Trigger diagnostics only on file save. Events like initial workspace load
	// or configuration change will still trigger diagnostics.
	DiagnosticsOnSave DiagnosticsTrigger = "Save"
)

type DocumentationOptions

type DocumentationOptions struct {
	// HoverKind controls the information that appears in the hover text.
	// SingleLine and Structured are intended for use only by authors of editor plugins.
	HoverKind HoverKind

	// LinkTarget is the base URL for links to Go package
	// documentation returned by LSP operations such as Hover and
	// DocumentLinks and in the CodeDescription field of each
	// Diagnostic.
	//
	// It might be one of:
	//
	// * `"godoc.org"`
	// * `"pkg.go.dev"`
	//
	// If company chooses to use its own `godoc.org`, its address can be used as well.
	//
	// Modules matching the GOPRIVATE environment variable will not have
	// documentation links in hover.
	LinkTarget string

	// LinksInHover controls the presence of documentation links in hover markdown.
	LinksInHover LinksInHoverEnum
}

Note: DocumentationOptions must be comparable with reflect.DeepEqual.

type FormattingOptions

type FormattingOptions struct {
	// Local is the equivalent of the `goimports -local` flag, which puts
	// imports beginning with this string after third-party packages. It should
	// be the prefix of the import path whose imports should be grouped
	// separately.
	//
	// It is used when tidying imports (during an LSP Organize
	// Imports request) or when inserting new ones (for example,
	// during completion); an LSP Formatting request merely sorts the
	// existing imports.
	Local string

	// Gofumpt indicates if we should run gofumpt formatting.
	Gofumpt bool
}

Note: FormattingOptions must be comparable with reflect.DeepEqual.

type HoverKind

type HoverKind string
const (
	SingleLine            HoverKind = "SingleLine"
	NoDocumentation       HoverKind = "NoDocumentation"
	SynopsisDocumentation HoverKind = "SynopsisDocumentation"
	FullDocumentation     HoverKind = "FullDocumentation"

	// Structured is an experimental setting that returns a structured hover format.
	// This format separates the signature from the documentation, so that the client
	// can do more manipulation of these fields.
	//
	// This should only be used by clients that support this behavior.
	Structured HoverKind = "Structured"
)

type ImportShortcut

type ImportShortcut string
const (
	BothShortcuts      ImportShortcut = "Both"
	LinkShortcut       ImportShortcut = "Link"
	DefinitionShortcut ImportShortcut = "Definition"
)

func (ImportShortcut) ShowDefinition

func (s ImportShortcut) ShowDefinition() bool
func (s ImportShortcut) ShowLinks() bool

type InlayHint

type InlayHint string

An InlayHint identifies a category of hint that may be independently requested through the "hints" setting.

const (
	// ParameterNames controls inlay hints for parameter names:
	// “`go
	// 	parseInt(/* str: */ "123", /* radix: */ 8)
	// “`
	ParameterNames InlayHint = "parameterNames"

	// AssignVariableTypes controls inlay hints for variable types in assign statements:
	// “`go
	// 	i/* int*/, j/* int*/ := 0, len(r)-1
	// “`
	AssignVariableTypes InlayHint = "assignVariableTypes"

	// ConstantValues controls inlay hints for constant values:
	// “`go
	// 	const (
	// 		KindNone   Kind = iota/* = 0*/
	// 		KindPrint/*  = 1*/
	// 		KindPrintf/* = 2*/
	// 		KindErrorf/* = 3*/
	// 	)
	// “`
	ConstantValues InlayHint = "constantValues"

	// RangeVariableTypes controls inlay hints for variable types in range statements:
	// “`go
	// 	for k/* int*/, v/* string*/ := range []string{} {
	// 		fmt.Println(k, v)
	// 	}
	// “`
	RangeVariableTypes InlayHint = "rangeVariableTypes"

	// CompositeLiteralTypes controls inlay hints for composite literal types:
	// “`go
	// 	for _, c := range []struct {
	// 		in, want string
	// 	}{
	// 		/*struct{ in string; want string }*/{"Hello, world", "dlrow ,olleH"},
	// 	}
	// “`
	CompositeLiteralTypes InlayHint = "compositeLiteralTypes"

	// CompositeLiteralFieldNames inlay hints for composite literal field names:
	// “`go
	// 	{/*in: */"Hello, world", /*want: */"dlrow ,olleH"}
	// “`
	CompositeLiteralFieldNames InlayHint = "compositeLiteralFields"

	// FunctionTypeParameters inlay hints for implicit type parameters on generic functions:
	// “`go
	// 	myFoo/*[int, string]*/(1, "hello")
	// “`
	FunctionTypeParameters InlayHint = "functionTypeParameters"
)

This is the source from which gopls/doc/inlayHints.md is generated.

type InlayHintOptions

type InlayHintOptions struct {
	// Hints specify inlay hints that users want to see. A full list of hints
	// that gopls uses can be found in
	// [inlayHints.md](https://github.com/golang/tools/blob/master/gopls/doc/inlayHints.md).
	Hints map[InlayHint]bool `status:"experimental"`
}

type InternalOptions

type InternalOptions struct {
	// VerboseWorkDoneProgress controls whether the LSP server should send
	// progress reports for all work done outside the scope of an RPC.
	// Used by the regression tests.
	VerboseWorkDoneProgress bool

	// CompletionDocumentation enables documentation with completion results.
	CompletionDocumentation bool

	// CompleteUnimported enables completion for packages that you do not
	// currently import.
	CompleteUnimported bool

	// DeepCompletion enables the ability to return completions from deep
	// inside relevant entities, rather than just the locally accessible ones.
	//
	// Consider this example:
	//
	// “`go
	// package main
	//
	// import "fmt"
	//
	// type wrapString struct {
	//     str string
	// }
	//
	// func main() {
	//     x := wrapString{"hello world"}
	//     fmt.Printf(<>)
	// }
	// “`
	//
	// At the location of the `<>` in this program, deep completion would suggest
	// the result `x.str`.
	DeepCompletion bool

	// ShowBugReports causes a message to be shown when the first bug is reported
	// on the server.
	// This option applies only during initialization.
	ShowBugReports bool

	// SubdirWatchPatterns configures the file watching glob patterns registered
	// by gopls.
	//
	// Some clients (namely VS Code) do not send workspace/didChangeWatchedFile
	// notifications for files contained in a directory when that directory is
	// deleted:
	// https://github.com/microsoft/vscode/issues/109754
	//
	// In this case, gopls would miss important notifications about deleted
	// packages. To work around this, gopls registers a watch pattern for each
	// directory containing Go files.
	//
	// Unfortunately, other clients experience performance problems with this
	// many watch patterns, so there is no single behavior that works well for
	// all clients.
	//
	// The "subdirWatchPatterns" setting allows configuring this behavior. Its
	// default value of "auto" attempts to guess the correct behavior based on
	// the client name. We'd love to avoid this specialization, but as described
	// above there is no single value that works for all clients.
	//
	// If any LSP client does not behave well with the default value (for
	// example, if like VS Code it drops file notifications), please file an
	// issue.
	SubdirWatchPatterns SubdirWatchPatterns

	// ReportAnalysisProgressAfter sets the duration for gopls to wait before starting
	// progress reporting for ongoing go/analysis passes.
	//
	// It is intended to be used for testing only.
	ReportAnalysisProgressAfter time.Duration

	// TelemetryPrompt controls whether gopls prompts about enabling Go telemetry.
	//
	// Once the prompt is answered, gopls doesn't ask again, but TelemetryPrompt
	// can prevent the question from ever being asked in the first place.
	TelemetryPrompt bool

	// LinkifyShowMessage controls whether the client wants gopls
	// to linkify links in showMessage. e.g. [go.dev](https://go.dev).
	LinkifyShowMessage bool

	// IncludeReplaceInWorkspace controls whether locally replaced modules in a
	// go.mod file are treated like workspace modules.
	// Or in other words, if a go.mod file with local replaces behaves like a
	// go.work file.
	IncludeReplaceInWorkspace bool

	// ZeroConfig enables the zero-config algorithm for workspace layout,
	// dynamically creating build configurations for different modules,
	// directories, and GOOS/GOARCH combinations to cover open files.
	ZeroConfig bool

	// PullDiagnostics enables support for pull diagnostics.
	//
	// TODO(rfindley): make pull diagnostics robust, and remove this option,
	// allowing pull diagnostics by default.
	PullDiagnostics bool
}

InternalOptions contains settings that are not intended for use by the average user. These may be settings used by tests or outdated settings that will soon be deprecated. Some of these settings may not even be configurable by the user.

TODO(rfindley): even though these settings are not intended for modification, some of them should be surfaced in our documentation.

type LinksInHoverEnum

type LinksInHoverEnum int

LinksInHoverEnum has legal values:

- `false`, for no links; - `true`, for links to the `linkTarget` domain; or - `"gopls"`, for links to gopls' core documentation viewer.

Note: this type has special logic in loadEnums in generate.go. Be sure to reflect enum and doc changes there!

const (
	LinksInHover_None LinksInHoverEnum = iota
	LinksInHover_LinkTarget
	LinksInHover_Gopls
)

func (LinksInHoverEnum) MarshalJSON

func (l LinksInHoverEnum) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface, so that the default values are formatted correctly in documentation. (See [Options.setOne] for the flexible custom unmarshalling behavior).

type Matcher

type Matcher string
const (
	Fuzzy           Matcher = "Fuzzy"
	CaseInsensitive Matcher = "CaseInsensitive"
	CaseSensitive   Matcher = "CaseSensitive"
)
type NavigationOptions struct {
	// ImportShortcut specifies whether import statements should link to
	// documentation or go to definitions.
	ImportShortcut ImportShortcut

	// SymbolMatcher sets the algorithm that is used when finding workspace symbols.
	SymbolMatcher SymbolMatcher `status:"advanced"`

	// SymbolStyle controls how symbols are qualified in symbol responses.
	//
	// Example Usage:
	//
	// “`json5
	// "gopls": {
	// ...
	//   "symbolStyle": "Dynamic",
	// ...
	// }
	// “`
	SymbolStyle SymbolStyle `status:"advanced"`

	// SymbolScope controls which packages are searched for workspace/symbol
	// requests. When the scope is "workspace", gopls searches only workspace
	// packages. When the scope is "all", gopls searches all loaded packages,
	// including dependencies and the standard library.
	SymbolScope SymbolScope
}

type Options

Options holds various configuration that affects Gopls execution, organized by the nature or origin of the settings.

Options must be comparable with reflect.DeepEqual, and serializable with frob.Codec.

This type defines both the logic of LSP-supplied option parsing (see [SetOptions]), and the public documentation of options in ../../doc/settings.md (generated by gopls/doc/generate).

Each exported field of each embedded type such as "ClientOptions" contributes a user-visible option setting. The option name is the field name rendered in camelCase. Unlike most Go doc comments, these fields should be documented using GitHub markdown.

func DefaultOptions

func DefaultOptions(overrides ...func(*Options)) *Options

DefaultOptions is the options that are used for Gopls execution independent of any externally provided configuration (LSP initialization, command invocation, etc.).

It is the source from which gopls/doc/settings.md is generated.

func (*Options) Clone

func (o *Options) Clone() *Options

func (*Options) ForClientCapabilities

func (o *Options) ForClientCapabilities(clientInfo *protocol.ClientInfo, caps protocol.ClientCapabilities)

func (*Options) Set

func (o *Options) Set(value any) (errors []error)

Set updates *options based on the provided JSON value: null, bool, string, number, array, or object. On failure, it returns one or more non-nil errors.

type ServerOptions

type ServerOptions struct {
	SupportedCodeActions map[file.Kind]map[protocol.CodeActionKind]bool
	SupportedCommands    []string
}

ServerOptions holds LSP-specific configuration that is provided by the server.

ServerOptions must be comparable with reflect.DeepEqual.

type SoftError

type SoftError struct {
	// contains filtered or unexported fields
}

A SoftError is an error that does not affect the functionality of gopls.

func (*SoftError) Error

func (e *SoftError) Error() string

type SubdirWatchPatterns

type SubdirWatchPatterns string
const (
	SubdirWatchPatternsOn   SubdirWatchPatterns = "on"
	SubdirWatchPatternsOff  SubdirWatchPatterns = "off"
	SubdirWatchPatternsAuto SubdirWatchPatterns = "auto"
)

type SymbolMatcher

type SymbolMatcher string

A SymbolMatcher controls the matching of symbols for workspace/symbol requests.

const (
	SymbolFuzzy           SymbolMatcher = "Fuzzy"
	SymbolFastFuzzy       SymbolMatcher = "FastFuzzy"
	SymbolCaseInsensitive SymbolMatcher = "CaseInsensitive"
	SymbolCaseSensitive   SymbolMatcher = "CaseSensitive"
)

type SymbolScope

type SymbolScope string

A SymbolScope controls the search scope for workspace/symbol requests.

const (
	// WorkspaceSymbolScope matches symbols in workspace packages only.
	WorkspaceSymbolScope SymbolScope = "workspace"
	// AllSymbolScope matches symbols in any loaded package, including
	// dependencies.
	AllSymbolScope SymbolScope = "all"
)

type SymbolStyle

type SymbolStyle string

A SymbolStyle controls the formatting of symbols in workspace/symbol results.

const (
	// PackageQualifiedSymbols is package qualified symbols i.e.
	// "pkg.Foo.Field".
	PackageQualifiedSymbols SymbolStyle = "Package"
	// FullyQualifiedSymbols is fully qualified symbols, i.e.
	// "path/to/pkg.Foo.Field".
	FullyQualifiedSymbols SymbolStyle = "Full"
	// DynamicSymbols uses whichever qualifier results in the highest scoring
	// match for the given symbol query. Here a "qualifier" is any "/" or "."
	// delimited suffix of the fully qualified symbol. i.e. "to/pkg.Foo.Field" or
	// just "Foo.Field".
	DynamicSymbols SymbolStyle = "Dynamic"
)

type UIOptions

type UIOptions struct {
	DocumentationOptions
	CompletionOptions
	NavigationOptions
	DiagnosticOptions
	InlayHintOptions

	// Codelenses overrides the enabled/disabled state of each of gopls'
	// sources of [Code Lenses](codelenses.md).
	//
	// Example Usage:
	//
	// “`json5
	// "gopls": {
	// ...
	//   "codelenses": {
	//     "generate": false,  // Don't show the `go generate` lens.
	//     "gc_details": true  // Show a code lens toggling the display of gc's choices.
	//   }
	// ...
	// }
	// “`
	Codelenses map[CodeLensSource]bool

	// SemanticTokens controls whether the LSP server will send
	// semantic tokens to the client.
	SemanticTokens bool `status:"experimental"`

	// NoSemanticString turns off the sending of the semantic token 'string'
	NoSemanticString bool `status:"experimental"`

	// NoSemanticNumber  turns off the sending of the semantic token 'number'
	NoSemanticNumber bool `status:"experimental"`
}

Note: UIOptions must be comparable with reflect.DeepEqual.

type UserOptions

type UserOptions struct {
	BuildOptions
	UIOptions
	FormattingOptions

	// VerboseOutput enables additional debug logging.
	VerboseOutput bool `status:"debug"`
}

UserOptions holds custom Gopls configuration (not part of the LSP) that is modified by the client.

UserOptions must be comparable with reflect.DeepEqual.

func (*UserOptions) EnvSlice

func (u *UserOptions) EnvSlice() []string

EnvSlice returns Env as a slice of k=v strings.

func (*UserOptions) SetEnvSlice

func (u *UserOptions) SetEnvSlice(env []string)

SetEnvSlice sets Env from a slice of k=v strings.

type VulncheckMode

type VulncheckMode string
const (
	// Disable vulnerability analysis.
	ModeVulncheckOff VulncheckMode = "Off"
	// In Imports mode, `gopls` will report vulnerabilities that affect packages
	// directly and indirectly used by the analyzed main module.
	ModeVulncheckImports VulncheckMode = "Imports"
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL