lsp

package
v0.0.27 Latest Latest
Warning

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

Go to latest
Published: Apr 23, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// FormatTimeout is the maximum time to wait for formatting results.
	FormatTimeout = 5 * time.Second

	// DiagnosticsDelay is the time to wait for the server to push diagnostics
	// after a file change notification.
	DiagnosticsDelay = 2 * time.Second
)
View Source
const (
	SeverityError       = 1
	SeverityWarning     = 2
	SeverityInformation = 3
	SeverityHint        = 4
)

DiagnosticSeverity constants.

View Source
const (
	SymbolKindFile        = 1
	SymbolKindModule      = 2
	SymbolKindNamespace   = 3
	SymbolKindPackage     = 4
	SymbolKindClass       = 5
	SymbolKindMethod      = 6
	SymbolKindProperty    = 7
	SymbolKindField       = 8
	SymbolKindConstructor = 9
	SymbolKindEnum        = 10
	SymbolKindInterface   = 11
	SymbolKindFunction    = 12
	SymbolKindVariable    = 13
	SymbolKindConstant    = 14
	SymbolKindStruct      = 23
)

SymbolKind constants (subset of commonly used kinds).

View Source
const DefaultRequestTimeout = 30 * time.Second

DefaultRequestTimeout is the maximum time to wait for a response.

Variables

This section is empty.

Functions

func ApplyTextEdits

func ApplyTextEdits(content string, edits []TextEdit) string

ApplyTextEdits applies LSP TextEdit operations to a document string. Edits are applied in reverse order (bottom-up) to preserve line/character offsets.

func BuildLSPAfterToolCallback

func BuildLSPAfterToolCallback(mgr *Manager) llmagent.AfterToolCallback

BuildLSPAfterToolCallback creates an AfterToolCallback that: - Formats files after write tool calls via the LSP server - Collects diagnostics after write/edit tool calls and appends them to the result

If no LSP server is available for a file type, the callback is a no-op. All errors are logged but never fail the tool call.

func DefaultLanguages

func DefaultLanguages() map[string]*LanguageConfig

DefaultLanguages returns built-in language server configurations.

func DetectLanguage

func DetectLanguage(filePath string, languages map[string]*LanguageConfig) string

DetectLanguage returns the language name for a file path based on extension. Returns empty string if no language matches.

func FindRoot

func FindRoot(filePath string, markers []string) string

FindRoot walks up from filePath looking for any of the marker files/dirs. Returns the directory containing the first marker found, or the directory of filePath itself if no marker is found.

Types

type Client

type Client struct {

	// NotificationHandler is called for server-initiated notifications.
	// It is called from the reader goroutine; it must not block.
	NotificationHandler func(method string, params json.RawMessage)
	// contains filtered or unexported fields
}

Client is a JSON-RPC 2.0 client that communicates with an LSP server over stdio using Content-Length framing.

func NewClient

func NewClient(command string, args ...string) (*Client, error)

NewClient starts an LSP server subprocess and returns a client connected to it via stdio. The caller must call Close() when done.

func (*Client) Close

func (c *Client) Close() error

Close sends shutdown and exit to the server, then kills the process.

func (*Client) Notify

func (c *Client) Notify(method string, params any) error

Notify sends a JSON-RPC notification (no response expected).

func (*Client) Request

func (c *Client) Request(ctx context.Context, method string, params any) (json.RawMessage, error)

Request sends a JSON-RPC request and waits for the response. The context controls the timeout; if no deadline is set, DefaultRequestTimeout is used.

type ClientCapabilities

type ClientCapabilities struct {
	TextDocument *TextDocumentClientCapabilities `json:"textDocument,omitempty"`
}

ClientCapabilities declares client features.

type CodeAction added in v0.0.15

type CodeAction struct {
	Title       string         `json:"title"`
	Kind        string         `json:"kind,omitempty"`
	Edit        *WorkspaceEdit `json:"edit,omitempty"`
	Command     *Command       `json:"command,omitempty"`
	IsPreferred bool           `json:"isPreferred,omitempty"`
}

CodeAction represents a code action that can be executed.

type CodeActionContext added in v0.0.15

type CodeActionContext struct {
	Diagnostics []Diagnostic `json:"diagnostics"`
}

CodeActionContext contains information about the code action request.

type CodeActionParams added in v0.0.15

type CodeActionParams struct {
	TextDocument TextDocumentIdentifier `json:"textDocument"`
	Range        Range                  `json:"range"`
	Context      CodeActionContext      `json:"context"`
}

CodeActionParams for textDocument/codeAction.

type Command added in v0.0.15

type Command struct {
	Command   string `json:"command"`
	Arguments []any  `json:"arguments,omitempty"`
}

Command represents a command to execute.

type Diagnostic

type Diagnostic struct {
	Range    Range           `json:"range"`
	Severity int             `json:"severity,omitempty"`
	Source   string          `json:"source,omitempty"`
	Message  string          `json:"message"`
	Code     json.RawMessage `json:"code,omitempty"`
}

Diagnostic represents an LSP diagnostic.

func (*Diagnostic) SeverityString

func (d *Diagnostic) SeverityString() string

SeverityString returns a human-readable severity name.

type DidChangeTextDocumentParams

type DidChangeTextDocumentParams struct {
	TextDocument   VersionedTextDocumentIdentifier  `json:"textDocument"`
	ContentChanges []TextDocumentContentChangeEvent `json:"contentChanges"`
}

DidChangeTextDocumentParams for textDocument/didChange.

type DidCloseTextDocumentParams

type DidCloseTextDocumentParams struct {
	TextDocument TextDocumentIdentifier `json:"textDocument"`
}

DidCloseTextDocumentParams for textDocument/didClose.

type DidOpenTextDocumentParams

type DidOpenTextDocumentParams struct {
	TextDocument TextDocumentItem `json:"textDocument"`
}

DidOpenTextDocumentParams for textDocument/didOpen.

type DocumentFormattingParams

type DocumentFormattingParams struct {
	TextDocument TextDocumentIdentifier `json:"textDocument"`
	Options      FormattingOptions      `json:"options"`
}

DocumentFormattingParams for textDocument/formatting.

type DocumentSymbol

type DocumentSymbol struct {
	Name           string           `json:"name"`
	Kind           int              `json:"kind"`
	Range          Range            `json:"range"`
	SelectionRange Range            `json:"selectionRange"`
	Children       []DocumentSymbol `json:"children,omitempty"`
}

DocumentSymbol represents a symbol in a document.

type DocumentSymbolParams

type DocumentSymbolParams struct {
	TextDocument TextDocumentIdentifier `json:"textDocument"`
}

DocumentSymbolParams for textDocument/documentSymbol.

type FormattingOptions

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

FormattingOptions for formatting requests.

type HoverResult

type HoverResult struct {
	Contents MarkupContent `json:"contents"`
	Range    *Range        `json:"range,omitempty"`
}

HoverResult is the result of a textDocument/hover request.

type InitializeParams

type InitializeParams struct {
	ProcessID    int                `json:"processId"`
	RootURI      string             `json:"rootUri"`
	Capabilities ClientCapabilities `json:"capabilities"`
}

InitializeParams for the initialize request.

type InitializeResult

type InitializeResult struct {
	Capabilities ServerCapabilities `json:"capabilities"`
}

InitializeResult from the server.

type LanguageConfig

type LanguageConfig struct {
	Command        string         `json:"command"`
	Args           []string       `json:"args,omitempty"`
	FileExtensions []string       `json:"fileExtensions"`
	RootMarkers    []string       `json:"rootMarkers"`
	InitOptions    map[string]any `json:"initOptions,omitempty"`
	LanguageID     string         `json:"languageId"` // LSP language identifier
}

LanguageConfig describes how to start and identify an LSP server for a language.

type Location

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

Location is a range inside a particular document.

type Manager

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

Manager manages LSP server lifecycle — starting servers on demand, caching running servers, and shutting them down.

func NewManager

func NewManager(cfg *ManagerConfig) *Manager

NewManager creates a Manager with the given config merged over defaults. It checks which language servers are installed and logs warnings for missing ones.

func (*Manager) Available

func (m *Manager) Available(lang string) bool

Available returns whether a language server binary was found.

func (*Manager) CachedDiagnostics

func (m *Manager) CachedDiagnostics(fileURI string) []Diagnostic

CachedDiagnostics returns the latest diagnostics for a file URI.

func (*Manager) Languages

func (m *Manager) Languages() map[string]*LanguageConfig

Languages returns the configured language map (for inspection/testing).

func (*Manager) ServerFor

func (m *Manager) ServerFor(filePath string) (*Server, error)

ServerFor returns a Server for the given file, starting one if needed. Returns (nil, nil) if no language server is configured or installed for the file type.

func (*Manager) Shutdown

func (m *Manager) Shutdown()

Shutdown gracefully shuts down all running servers.

type ManagerConfig

type ManagerConfig struct {
	Languages map[string]*LanguageConfig `json:"languages,omitempty"`
	Disabled  []string                   `json:"disabled,omitempty"`
}

ManagerConfig holds optional overrides for language server configurations.

type MarkupContent

type MarkupContent struct {
	Kind  string `json:"kind"` // "plaintext" or "markdown"
	Value string `json:"value"`
}

MarkupContent represents human-readable content.

type Notification

type Notification struct {
	JSONRPC string          `json:"jsonrpc"`
	Method  string          `json:"method"`
	Params  json.RawMessage `json:"params,omitempty"`
}

Notification is a JSON-RPC 2.0 notification (no ID, no response expected).

type Position

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

Position in a text document (0-based line and character).

type PublishDiagnosticsClientCapabilities

type PublishDiagnosticsClientCapabilities struct {
	RelatedInformation bool `json:"relatedInformation,omitempty"`
}

PublishDiagnosticsClientCapabilities for diagnostics.

type PublishDiagnosticsParams

type PublishDiagnosticsParams struct {
	URI         string       `json:"uri"`
	Diagnostics []Diagnostic `json:"diagnostics"`
}

PublishDiagnosticsParams from the server.

type Range

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

Range in a text document.

type ReferenceContext

type ReferenceContext struct {
	IncludeDeclaration bool `json:"includeDeclaration"`
}

ReferenceContext controls reference search behavior.

type ReferenceParams

type ReferenceParams struct {
	TextDocument TextDocumentIdentifier `json:"textDocument"`
	Position     Position               `json:"position"`
	Context      ReferenceContext       `json:"context"`
}

ReferenceParams for textDocument/references.

type Request

type Request struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      int             `json:"id"`
	Method  string          `json:"method"`
	Params  json.RawMessage `json:"params,omitempty"`
}

Request is a JSON-RPC 2.0 request message.

type Response

type Response struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      *int            `json:"id"`
	Result  json.RawMessage `json:"result,omitempty"`
	Error   *ResponseError  `json:"error,omitempty"`
}

Response is a JSON-RPC 2.0 response message.

type ResponseError

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

ResponseError represents a JSON-RPC error object.

func (*ResponseError) Error

func (e *ResponseError) Error() string

type Server

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

Server wraps a Client with higher-level LSP operations.

func (*Server) Close

func (s *Server) Close() error

Close sends didClose for all open files.

func (*Server) CodeActions added in v0.0.15

func (s *Server) CodeActions(ctx context.Context, file string, startLine, startChar, endLine, endChar int) ([]CodeAction, error)

CodeActions sends textDocument/codeAction and returns available code actions.

func (*Server) Definition

func (s *Server) Definition(ctx context.Context, file string, line, col int) ([]Location, error)

Definition sends textDocument/definition and returns locations.

func (*Server) Diagnostics

func (s *Server) Diagnostics(ctx context.Context, file string) ([]Diagnostic, error)

Diagnostics requests diagnostics for a file. Note: most servers push diagnostics via notifications; this triggers didOpen/didChange to prompt a refresh and returns empty. Callers should use the Manager's diagnostic cache instead.

func (*Server) Format

func (s *Server) Format(ctx context.Context, file string) ([]TextEdit, error)

Format sends textDocument/formatting and returns text edits.

func (*Server) Hover

func (s *Server) Hover(ctx context.Context, file string, line, col int) (*HoverResult, error)

Hover sends textDocument/hover and returns the result.

func (*Server) NotifyChange

func (s *Server) NotifyChange(file string, content string) error

NotifyChange sends a didChange notification for an already-open file.

func (*Server) References

func (s *Server) References(ctx context.Context, file string, line, col int) ([]Location, error)

References sends textDocument/references and returns locations.

func (*Server) Symbols

func (s *Server) Symbols(ctx context.Context, file string) ([]DocumentSymbol, error)

Symbols sends textDocument/documentSymbol and returns symbols.

func (*Server) WorkspaceSymbols added in v0.0.15

func (s *Server) WorkspaceSymbols(ctx context.Context, query string) ([]WorkspaceSymbol, error)

WorkspaceSymbols sends workspace/symbol and returns symbols matching a query.

type ServerCapabilities

type ServerCapabilities struct {
	TextDocumentSync           json.RawMessage `json:"textDocumentSync,omitempty"`
	CompletionProvider         json.RawMessage `json:"completionProvider,omitempty"`
	HoverProvider              json.RawMessage `json:"hoverProvider,omitempty"`
	DefinitionProvider         json.RawMessage `json:"definitionProvider,omitempty"`
	ReferencesProvider         json.RawMessage `json:"referencesProvider,omitempty"`
	DocumentSymbolProvider     json.RawMessage `json:"documentSymbolProvider,omitempty"`
	DocumentFormattingProvider json.RawMessage `json:"documentFormattingProvider,omitempty"`
}

ServerCapabilities advertises server features.

type TextDocumentClientCapabilities

type TextDocumentClientCapabilities struct {
	Synchronization    *TextDocumentSyncClientCapabilities   `json:"synchronization,omitempty"`
	PublishDiagnostics *PublishDiagnosticsClientCapabilities `json:"publishDiagnostics,omitempty"`
}

TextDocumentClientCapabilities for text document features.

type TextDocumentContentChangeEvent

type TextDocumentContentChangeEvent struct {
	Text string `json:"text"`
}

TextDocumentContentChangeEvent is a full document sync change.

type TextDocumentIdentifier

type TextDocumentIdentifier struct {
	URI string `json:"uri"`
}

TextDocumentIdentifier identifies a text document.

type TextDocumentItem

type TextDocumentItem struct {
	URI        string `json:"uri"`
	LanguageID string `json:"languageId"`
	Version    int    `json:"version"`
	Text       string `json:"text"`
}

TextDocumentItem is used in didOpen notifications.

type TextDocumentPositionParams

type TextDocumentPositionParams struct {
	TextDocument TextDocumentIdentifier `json:"textDocument"`
	Position     Position               `json:"position"`
}

TextDocumentPositionParams identifies a position in a text document.

type TextDocumentSyncClientCapabilities

type TextDocumentSyncClientCapabilities struct {
	DidSave bool `json:"didSave,omitempty"`
}

TextDocumentSyncClientCapabilities for synchronization.

type TextEdit

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

TextEdit represents a change to a text document.

type VersionedTextDocumentIdentifier

type VersionedTextDocumentIdentifier struct {
	URI     string `json:"uri"`
	Version int    `json:"version"`
}

VersionedTextDocumentIdentifier identifies a specific version of a text document.

type WorkspaceEdit added in v0.0.15

type WorkspaceEdit struct {
	Changes map[string][]TextEdit `json:"changes,omitempty"`
}

WorkspaceEdit represents changes to be applied to a workspace.

type WorkspaceSymbol added in v0.0.15

type WorkspaceSymbol struct {
	Name          string   `json:"name"`
	Kind          int      `json:"kind"`
	Location      Location `json:"location"`
	ContainerName string   `json:"containerName,omitempty"`
}

WorkspaceSymbol represents a symbol found via workspace/symbol.

type WorkspaceSymbolParams added in v0.0.15

type WorkspaceSymbolParams struct {
	Query string `json:"query"`
}

WorkspaceSymbolParams for workspace/symbol.

Jump to

Keyboard shortcuts

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