lsp

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: MIT Imports: 20 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package lsp is a client of the Language Server Protocol 3.17: it starts a language server, keeps it in step with the documents an Editor edits, and asks it for diagnostics, completions, hovers and definitions.

Start runs a server from a command the caller gives (the package knows no server; the servers package is a catalog of them) and greets it; Connect does the same over any stream, a server already running or one in a test. Attach then binds an Editor to a document of the server: it opens the document, sends every edit, shows the server's diagnostics, and sets the editor's hooks to ask the server for completions, hovers, signatures, definitions, implementations, references, renames and code actions; the Document it returns formats the document and lists its symbols.

Messages are JSON-RPC 2.0 framed by Content-Length headers, over the server's standard input and output. Positions are offered in UTF-8, the unit an Editor counts in; a server that only speaks UTF-16, the default of the protocol, gets UTF-16, and Attach converts every position.

Index

Constants

This section is empty.

Variables

View Source
var ErrClosed = errors.New("lsp: connection closed")

ErrClosed is what a request returns once the connection to the server is gone, closed by Close or by the server.

View Source
var ErrNoFormatting = errors.New("lsp: the server does not format documents")

ErrNoFormatting is what Format returns when the server does not format.

View Source
var ErrNoSymbols = errors.New("lsp: the server does not list document symbols")

ErrNoSymbols is what Symbols returns when the server lists no symbols.

Functions

func FilePath

func FilePath(uri string) (path string, ok bool)

FilePath is the path a file URI names, ok false for a URI of another scheme.

func FileURI

func FileURI(path string) string

FileURI is the file URI of path, made absolute.

Types

type Client

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

Client is a connection to one language server. Its methods may be called from any goroutine.

func Connect

func Connect(ctx context.Context, rw io.ReadWriteCloser, cfg Config) (*Client, error)

Connect speaks LSP over rw, a server's stream, and runs the initialize handshake: it offers UTF-8 positions, which the Editor counts in, and falls back to what the server picks. Close closes rw.

func Start

func Start(ctx context.Context, cfg Config) (*Client, error)

Start runs cfg.Command in cfg.RootDir and connects to it over its standard input and output, as Connect does. ctx bounds the start and the initialize handshake, not the server's life: Close ends that.

func (*Client) Close

func (c *Client) Close() error

Close asks the server to shut down and exit, as LSP's shutdown and exit, and closes the connection. A server started by Start that has not exited within a couple of seconds is killed.

func (*Client) CodeActions

func (c *Client) CodeActions(ctx context.Context, uri string, r Range, diags []Diagnostic) ([]CodeAction, error)

CodeActions asks for the actions on r, where diags are.

func (*Client) Completion

func (c *Client) Completion(ctx context.Context, uri string, pos Position, trigger string) (CompletionList, error)

Completion asks for the completions at pos. trigger is the character typed that asked for them, empty when the user asked.

func (*Client) CompletionTriggers

func (c *Client) CompletionTriggers() []string

CompletionTriggers are the characters after which the server offers completions unasked.

func (*Client) Definition

func (c *Client) Definition(ctx context.Context, uri string, pos Position) ([]Location, error)

Definition asks where the symbol at pos is defined.

func (*Client) DidChange

func (c *Client) DidChange(uri string, version int, changes []ContentChange) error

DidChange tells the server the document is now at version, after changes, applied in order.

func (*Client) DidClose

func (c *Client) DidClose(uri string) error

DidClose tells the server the document is closed.

func (*Client) DidOpen

func (c *Client) DidOpen(uri, languageID string, version int, text string) error

DidOpen tells the server a document is open, with its text.

func (*Client) DidSave

func (c *Client) DidSave(uri string, text *string) error

DidSave tells the server the document was saved; text, when the server asked for it (Sync), is what was saved.

func (*Client) Done

func (c *Client) Done() <-chan struct{}

Done is closed once the connection to the server is gone.

func (*Client) Encoding

func (c *Client) Encoding() PositionEncoding

Encoding is the position encoding the server picked: every Position the client sends or reads counts in it.

func (*Client) ExecuteCommand

func (c *Client) ExecuteCommand(ctx context.Context, cmd Command) error

ExecuteCommand asks the server to run cmd. What it edits comes back as workspace/applyEdit, which the documents attached to the client apply.

func (*Client) Format

func (c *Client) Format(ctx context.Context, uri string, opts FormattingOptions) ([]TextEdit, error)

Format asks for the edits that format the whole document.

func (*Client) HasCodeActions

func (c *Client) HasCodeActions() bool

HasCodeActions reports whether the server answers textDocument/codeAction.

func (*Client) HasCompletion

func (c *Client) HasCompletion() bool

HasCompletion reports whether the server answers textDocument/completion.

func (*Client) HasDefinition

func (c *Client) HasDefinition() bool

HasDefinition reports whether the server answers textDocument/definition.

func (*Client) HasFormatting

func (c *Client) HasFormatting() bool

HasFormatting reports whether the server answers textDocument/formatting.

func (*Client) HasHover

func (c *Client) HasHover() bool

HasHover reports whether the server answers textDocument/hover.

func (*Client) HasImplementation

func (c *Client) HasImplementation() bool

HasImplementation reports whether the server answers textDocument/implementation.

func (*Client) HasReferences

func (c *Client) HasReferences() bool

HasReferences reports whether the server answers textDocument/references.

func (*Client) HasRename

func (c *Client) HasRename() bool

HasRename reports whether the server answers textDocument/rename.

func (*Client) HasSignatureHelp

func (c *Client) HasSignatureHelp() bool

HasSignatureHelp reports whether the server answers textDocument/signatureHelp.

func (*Client) HasSymbols

func (c *Client) HasSymbols() bool

HasSymbols reports whether the server answers textDocument/documentSymbol.

func (*Client) HasTypeDefinition

func (c *Client) HasTypeDefinition() bool

HasTypeDefinition reports whether the server answers textDocument/typeDefinition.

func (*Client) Hover

func (c *Client) Hover(ctx context.Context, uri string, pos Position) (*Hover, error)

Hover asks what to show for pos; nil when the server has nothing.

func (*Client) Implementation

func (c *Client) Implementation(ctx context.Context, uri string, pos Position) ([]Location, error)

Implementation asks where the symbol at pos, an interface or a method of one say, is implemented.

func (*Client) References

func (c *Client) References(ctx context.Context, uri string, pos Position, withDeclaration bool) ([]Location, error)

References asks for the references to the symbol at pos, its declaration among them when withDeclaration is set.

func (*Client) Rename

func (c *Client) Rename(ctx context.Context, uri string, pos Position, name string) (WorkspaceEdit, error)

Rename asks for the edits renaming the symbol at pos to name.

func (*Client) ResolveCodeAction

func (c *Client) ResolveCodeAction(ctx context.Context, a CodeAction) (CodeAction, error)

ResolveCodeAction asks the server to fill in a, its edit most of all; a server that does not resolve gives a back.

func (*Client) ResolveCompletion

func (c *Client) ResolveCompletion(ctx context.Context, item CompletionItem) (CompletionItem, error)

ResolveCompletion asks the server to fill in item, its documentation most of all; a server that does not resolve gives item back.

func (*Client) SignatureHelp

func (c *Client) SignatureHelp(ctx context.Context, uri string, pos Position, trigger string) (*SignatureHelp, error)

SignatureHelp asks for the signature of the call around pos; trigger is the character typed that asked, empty when the client asks again. nil when pos is in no call.

func (*Client) SignatureTriggers

func (c *Client) SignatureTriggers() []string

SignatureTriggers are the characters after which the server tells a call's signature, those that retrigger it included, and HasSignatureHelp whether it tells any.

func (*Client) Sync

func (c *Client) Sync() (kind SyncKind, saveText bool)

Sync is how the server wants changes sent, and whether didSave carries the text.

func (*Client) TypeDefinition

func (c *Client) TypeDefinition(ctx context.Context, uri string, pos Position) ([]Location, error)

TypeDefinition asks where the type of the symbol at pos is defined.

func (*Client) WatchDiagnostics

func (c *Client) WatchDiagnostics(uri string, f func(PublishDiagnostics)) (stop func())

WatchDiagnostics hands every textDocument/publishDiagnostics for uri to f, on the goroutine that reads from the server, until stop is called; f returns fast. A later watch of the same uri replaces this one.

type Code

type Code string

Code is a diagnostic's code, which LSP lets be a number or a string, read as its text.

func (*Code) UnmarshalJSON

func (c *Code) UnmarshalJSON(b []byte) error

UnmarshalJSON takes a number or a string.

type CodeAction

type CodeAction struct {
	Title       string          `json:"title"`
	Kind        string          `json:"kind,omitempty"`
	Diagnostics []Diagnostic    `json:"diagnostics,omitempty"`
	Edit        *WorkspaceEdit  `json:"edit,omitempty"`
	Command     *Command        `json:"command,omitempty"`
	Data        json.RawMessage `json:"data,omitempty"`
	IsCommand   bool            `json:"-"`
}

CodeAction is an action a server offers on a range: an edit, a command to run after it, or both; or, with Edit and Command both nil and IsCommand set, a bare command, whose Title and Command are in Command.

func (*CodeAction) UnmarshalJSON

func (a *CodeAction) UnmarshalJSON(b []byte) error

UnmarshalJSON takes a CodeAction or a bare Command.

type Command

type Command struct {
	Title     string            `json:"title"`
	Command   string            `json:"command"`
	Arguments []json.RawMessage `json:"arguments,omitempty"`
}

Command is a command a server runs with workspace/executeCommand.

type CompletionItem

type CompletionItem struct {
	Label            string             `json:"label"`
	Kind             CompletionItemKind `json:"kind,omitempty"`
	Detail           string             `json:"detail,omitempty"`
	Documentation    Markup             `json:"documentation,omitzero"`
	SortText         string             `json:"sortText,omitempty"`
	FilterText       string             `json:"filterText,omitempty"`
	InsertText       string             `json:"insertText,omitempty"`
	InsertTextFormat InsertTextFormat   `json:"insertTextFormat,omitempty"`
	TextEdit         *TextEdit          `json:"textEdit,omitempty"`
	// Data is the server's own, sent back with completionItem/resolve.
	Data json.RawMessage `json:"data,omitempty"`
}

CompletionItem is one completion a server offers.

type CompletionItemKind

type CompletionItemKind int

CompletionItemKind is what a completion item names, as LSP numbers it.

const (
	KindText CompletionItemKind = iota + 1
	KindMethod
	KindFunction
	KindConstructor
	KindField
	KindVariable
	KindClass
	KindInterface
	KindModule
	KindProperty
	KindUnit
	KindValue
	KindEnum
	KindKeyword
	KindSnippet
	KindColor
	KindFile
	KindReference
	KindFolder
	KindEnumMember
	KindConstant
	KindStruct
	KindEvent
	KindOperator
	KindTypeParameter
)

The completion item kinds of LSP 3.17.

type CompletionList

type CompletionList struct {
	IsIncomplete bool             `json:"isIncomplete"`
	Items        []CompletionItem `json:"items"`
}

CompletionList is what textDocument/completion answers: items, and whether typing more should ask again rather than filter them.

func (*CompletionList) UnmarshalJSON

func (l *CompletionList) UnmarshalJSON(b []byte) error

UnmarshalJSON takes a CompletionList, a bare array of items, or null.

type Config

type Config struct {
	// Command is the server's program and its arguments, for Start.
	Command []string
	// Env is added to the client's own environment for the server.
	Env []string
	// RootDir is the workspace the server works on, and the server's
	// working directory.
	RootDir string
	// InitializationOptions goes to the server with initialize, as is;
	// nil sends none.
	InitializationOptions json.RawMessage
	// Settings answers the server's workspace/configuration requests, the
	// section each asks for picked out of it, and goes with
	// workspace/didChangeConfiguration once initialized; nil sends none.
	Settings json.RawMessage
	// Stderr takes what the server writes to its standard error; nil drops
	// it.
	Stderr io.Writer
}

Config is how to start and greet a server. The client knows no server: the caller names it, by hand or from the servers catalog.

type ContentChange

type ContentChange struct {
	Range *Range `json:"range,omitempty"`
	Text  string `json:"text"`
}

ContentChange is one change of textDocument/didChange: Text replaces Range, or the whole document when Range is nil.

type Diagnostic

type Diagnostic struct {
	Range Range `json:"range"`
	// Severity is 0 when the server leaves it to the client, which takes
	// it as an error.
	Severity Severity `json:"severity,omitempty"`
	// Code is the server's name for the problem, a number or a string as
	// the server sent it; empty when it sent none.
	Code    Code   `json:"code,omitempty"`
	Source  string `json:"source,omitempty"`
	Message string `json:"message"`
}

Diagnostic is a problem a server reports in a document.

type Document

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

Document is an Editor bound to a document of a server by Attach.

func Attach

func Attach(c *Client, e *godemirror.Editor, uri string, opts Options) (*Document, error)

Attach opens the editor's document on the server, as uri, and binds the two: every edit goes to the server (incrementally when it accepts that, whole otherwise), the server's diagnostics show in the editor, and the editor's hooks (Complete, ResolveCompletion, CompletionTriggers, Hover, Definition, TypeDefinition, Implementation, References, SignatureHelp, Rename, CodeActions, ApplyCodeAction) ask the server, for what it offers. The editor's OnUpdate, if set, is still called after the server hears of each update. Attach runs on the goroutine that lays the editor out; Close undoes it.

func (*Document) Close

func (d *Document) Close() error

Close closes the document on the server, and gives the editor back its OnUpdate and no hooks, with its diagnostics cleared. It runs on the goroutine that lays the editor out.

func (*Document) Format

func (d *Document) Format(ctx context.Context) error

Format asks the server to format the whole document, indented as the editor's IndentUnit, and makes its edits as one transaction, which one Undo takes back. It blocks until the server answers, on the goroutine that lays the editor out, so ctx should carry a deadline. Formatting on save is the caller's: Format, then write the document, then Save.

func (*Document) Save

func (d *Document) Save() error

Save tells the server the document was saved, as it now is.

func (*Document) Symbols

func (d *Document) Symbols(ctx context.Context) ([]Symbol, error)

Symbols asks the server for the document's symbols, as a tree when the server nests them, and reads them in the editor's units. It blocks until the server answers, on the goroutine that lays the editor out, so ctx should carry a deadline.

type FormattingOptions

type FormattingOptions struct {
	TabSize      int  `json:"tabSize"`
	InsertSpaces bool `json:"insertSpaces"`
}

FormattingOptions are how a server is asked to lay code out.

type Hover

type Hover struct {
	Contents Markup `json:"contents"`
	Range    *Range `json:"range,omitempty"`
}

Hover is what textDocument/hover answers. Range, when set, is the span the hover is about.

type InsertTextFormat

type InsertTextFormat int

InsertTextFormat says whether an item's text is plain or a snippet.

const (
	PlainText InsertTextFormat = 1
	Snippet   InsertTextFormat = 2
)

The insert text formats.

type Location

type Location struct {
	URI   string `json:"uri"`
	Range Range  `json:"range"`
}

Location is a range in a document, named by its URI.

type Markup

type Markup struct {
	Kind  string `json:"kind"`
	Value string `json:"value"`
}

Markup is text a server sends for people to read: Value is markdown when Kind is "markdown", plain text otherwise.

func (*Markup) UnmarshalJSON

func (m *Markup) UnmarshalJSON(b []byte) error

UnmarshalJSON takes a MarkupContent, a MarkedString (a string or a language and value), or an array of MarkedStrings, joined as markdown.

type Options

type Options struct {
	// LanguageID is the document's language as LSP names it ("go",
	// "typescript", "python"); Attach fails without it.
	LanguageID string
	// Invalidate asks the window for a frame (app.Window.Invalidate):
	// diagnostics come from the server between frames, and the editor shows
	// them on the next one. It is called from the goroutine that reads from
	// the server.
	Invalidate func()
	// OnError, when set, hears of every request the server failed or a
	// change the client could not send, from the goroutine that met it: the
	// UI's for a change, a request's own for a request. Without it they are
	// dropped: the editor shows nothing for a request that failed.
	OnError func(error)
}

Options are how Attach binds an Editor.

type ParameterInformation

type ParameterInformation struct {
	Label         string
	Start, End    int
	Offsets       bool
	Documentation Markup `json:"documentation,omitzero"`
}

ParameterInformation is a parameter of a signature. Its label is a substring of the signature's, or Start and End, offsets in it in the position encoding's units, when the server sends offsets.

func (*ParameterInformation) UnmarshalJSON

func (p *ParameterInformation) UnmarshalJSON(b []byte) error

UnmarshalJSON takes a label that is a string or a pair of offsets.

type Position

type Position struct {
	Line      int `json:"line"`
	Character int `json:"character"`
}

Position is a place in a document as LSP counts it: Line from 0, and Character from 0 in the units of the client's PositionEncoding.

type PositionEncoding

type PositionEncoding string

PositionEncoding is the unit a Position's Character counts in, as client and server agree on it at initialize.

const (
	UTF8  PositionEncoding = "utf-8"
	UTF16 PositionEncoding = "utf-16"
	UTF32 PositionEncoding = "utf-32"
)

The position encodings of LSP 3.17. UTF-16 is the protocol's default, the one a server that names none speaks.

func (PositionEncoding) ByteColumn

func (enc PositionEncoding) ByteColumn(line string, character int) int

ByteColumn is the byte offset in line (one line's text, without its line break) of character, counted in enc. A character past the end of line, as LSP allows, is its end; one inside a UTF-8 sequence or a surrogate pair goes to the start of that character.

func (PositionEncoding) Character

func (enc PositionEncoding) Character(line string, byteCol int) int

Character is the column of byteCol, a byte offset in line, counted in enc.

type PublishDiagnostics

type PublishDiagnostics struct {
	URI         string       `json:"uri"`
	Version     *int         `json:"version,omitempty"`
	Diagnostics []Diagnostic `json:"diagnostics"`
}

PublishDiagnostics is the params of textDocument/publishDiagnostics: the whole set of diagnostics of URI, replacing the last. Version is the document version they were computed for, or nil when the server does not say.

type Range

type Range struct {
	Start Position `json:"start"`
	End   Position `json:"end"`
}

Range is the span from Start to End, End excluded.

type ResponseError

type ResponseError struct {
	Code    int             `json:"code"`
	Message string          `json:"message"`
	Data    json.RawMessage `json:"data,omitempty"`
}

ResponseError is an error a server answered a request with.

func (*ResponseError) Error

func (e *ResponseError) Error() string

type Severity

type Severity int

Severity is how bad a Diagnostic is, 1 (error) to 4 (hint), as LSP numbers it.

const (
	SeverityError Severity = iota + 1
	SeverityWarning
	SeverityInformation
	SeverityHint
)

The severities of a diagnostic.

type SignatureHelp

type SignatureHelp struct {
	Signatures      []SignatureInformation `json:"signatures"`
	ActiveSignature int                    `json:"activeSignature"`
	ActiveParameter *int                   `json:"activeParameter"`
}

SignatureHelp is what textDocument/signatureHelp answers: the signatures of the call, the active one, and its active parameter.

type SignatureInformation

type SignatureInformation struct {
	Label           string                 `json:"label"`
	Documentation   Markup                 `json:"documentation,omitzero"`
	Parameters      []ParameterInformation `json:"parameters"`
	ActiveParameter *int                   `json:"activeParameter"`
}

SignatureInformation is one signature: its label, its documentation, its parameters, and, overriding the help's, its active parameter.

type Symbol

type Symbol struct {
	Name, Detail     string
	Kind             SymbolKind
	Range, Selection godemirror.Location
	Children         []Symbol
}

Symbol is a symbol of a document, for an outline: Range is all of it, its body included, and Selection its name, both in the editor's units (lines from 0, columns in UTF-8 bytes); Children are the symbols inside it.

type SymbolKind

type SymbolKind int

SymbolKind is what a symbol is, as LSP numbers it.

const (
	SymbolFile SymbolKind = iota + 1
	SymbolModule
	SymbolNamespace
	SymbolPackage
	SymbolClass
	SymbolMethod
	SymbolProperty
	SymbolField
	SymbolConstructor
	SymbolEnum
	SymbolInterface
	SymbolFunction
	SymbolVariable
	SymbolConstant
	SymbolString
	SymbolNumber
	SymbolBoolean
	SymbolArray
	SymbolObject
	SymbolKey
	SymbolNull
	SymbolEnumMember
	SymbolStruct
	SymbolEvent
	SymbolOperator
	SymbolTypeParameter
)

The symbol kinds of LSP 3.17.

type SyncKind

type SyncKind int

SyncKind is how a server wants a document's changes sent, as LSP's TextDocumentSyncKind.

const (
	SyncNone        SyncKind = 0
	SyncFull        SyncKind = 1
	SyncIncremental SyncKind = 2
)

The sync kinds: none, the whole text each time, or the changed ranges.

type TextEdit

type TextEdit struct {
	Range   Range  `json:"range"`
	NewText string `json:"newText"`
}

TextEdit replaces Range with NewText. Read from an InsertReplaceEdit, it is the edit's insert range.

func (*TextEdit) UnmarshalJSON

func (t *TextEdit) UnmarshalJSON(b []byte) error

UnmarshalJSON takes a TextEdit or an InsertReplaceEdit.

type WorkspaceEdit

type WorkspaceEdit struct {
	Changes         map[string][]TextEdit `json:"changes"`
	DocumentChanges []json.RawMessage     `json:"documentChanges"`
}

WorkspaceEdit is edits to documents, as a rename or a code action makes them: by URI in Changes, or in order in DocumentChanges, whose file operations (create, rename, delete) the client does not make.

Directories

Path Synopsis
Package servers is a catalog of language servers: for each one, the command that starts it, the vim filetypes it serves, the files that mark a project root, its default initialization options and settings, and how to install it.
Package servers is a catalog of language servers: for each one, the command that starts it, the vim filetypes it serves, the files that mark a project root, its default initialization options and settings, and how to install it.

Jump to

Keyboard shortcuts

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