lsp

package
v0.3.9 Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2026 License: GPL-3.0 Imports: 20 Imported by: 0

Documentation

Overview

Package lsp LSP 客户端实现

管理语言服务器进程,提供文件符号提取和文档注释获取功能。 支持每工作目录每语言启动一个 LSP 服务器,10 分钟无调用自动回收。

Index

Constants

This section is empty.

Variables

View Source
var ErrLSPDisabled = errors.New("LSP disabled after consecutive failures")

ErrLSPDisabled 当 LSP 连续启动失败被禁用时返回

View Source
var SymbolKindNames = map[SymbolKind]string{
	SymbolFile:          "file",
	SymbolModule:        "module",
	SymbolNamespace:     "namespace",
	SymbolPackage:       "package",
	SymbolClass:         "class",
	SymbolMethod:        "method",
	SymbolProperty:      "property",
	SymbolField:         "field",
	SymbolConstructor:   "constructor",
	SymbolEnum:          "enum",
	SymbolInterface:     "interface",
	SymbolFunction:      "function",
	SymbolVariable:      "variable",
	SymbolConstant:      "constant",
	SymbolStruct:        "struct",
	SymbolEnumMember:    "enum member",
	SymbolEvent:         "event",
	SymbolOperator:      "operator",
	SymbolTypeParameter: "type parameter",
}

SymbolKindNames SymbolKind 到中文名称的映射

Functions

func GetFileNameExt added in v0.3.4

func GetFileNameExt(baseName string) (string, bool)

GetFileNameExt 返回已知无扩展名文件的映射伪扩展名

func Initialize

func Initialize() error

Initialize 初始化 LSP 管理器 从配置读取设置,若未启用则直接返回

func ResetLSPFailures added in v0.3.4

func ResetLSPFailures()

ResetLSPFailures 重置所有 LSP 的失败计数,供新索引周期开始前调用

func Shutdown

func Shutdown() error

Shutdown 关闭所有 LSP 客户端

func SupportedExtensions

func SupportedExtensions() []string

SupportedExtensions 返回所有支持的扩展名列表(用户配置 + 内置默认值 + 已知无LSP的扩展名)

Types

type Client

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

Client 管理单个 LSP 服务器进程

func NewClient

func NewClient(workdir, language string, cfg LanguageServerConfig) *Client

NewClient 创建 LSP 客户端

func (*Client) Close

func (c *Client) Close() error

Close 强制关闭 LSP 服务器

func (*Client) IsIdle

func (c *Client) IsIdle(timeout time.Duration) bool

IsIdle 检查客户端是否空闲超时

func (*Client) Language

func (c *Client) Language() string

Language 返回语言名称

func (*Client) LastUsed

func (c *Client) LastUsed() time.Time

LastUsed 返回上次使用时间

func (*Client) SendNotification

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

SendNotification 发送通知(线程安全)

func (*Client) SendRequest

func (c *Client) SendRequest(ctx context.Context, method string, params any) ([]byte, error)

SendRequest 发送请求(线程安全)

func (*Client) Shutdown

func (c *Client) Shutdown(ctx context.Context) error

Shutdown 优雅关闭 LSP 服务器

func (*Client) Start

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

Start 启动 LSP 服务器进程并完成 initialize 握手

func (*Client) State

func (c *Client) State() ClientState

State 返回当前状态

func (*Client) Workdir

func (c *Client) Workdir() string

Workdir 返回工作目录

type ClientCapabilities

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

ClientCapabilities LSP 客户端能力

type ClientState

type ClientState int

ClientState LSP 客户端状态

const (
	StateCreated      ClientState = iota // 已创建,未启动
	StateReady                           // 已初始化,可处理请求
	StateShuttingDown                    // 正在关闭
	StateClosed                          // 已关闭
)

LSP 客户端状态

func (ClientState) String

func (s ClientState) String() string

type Diagnostic added in v0.3.4

type Diagnostic struct {
	Range    Range              `json:"range"`
	Severity DiagnosticSeverity `json:"severity,omitempty"`
	Source   string             `json:"source,omitempty"`
	Code     any                `json:"code,omitempty"` // string | int, LSP 诊断错误码
	Message  string             `json:"message"`
}

Diagnostic LSP 诊断信息

type DiagnosticBrief added in v0.3.4

type DiagnosticBrief struct {
	Line     int    `json:"line"`
	Column   int    `json:"column,omitempty"`
	Message  string `json:"message"`
	Severity string `json:"severity"`
	Source   string `json:"source,omitempty"`
	Code     string `json:"code,omitempty"`
}

DiagnosticBrief 诊断信息(供 AI 消费) 包含行号、列号、消息、严重级别、来源(LSP 服务器名)和错误码

func CheckNoLSPFileSyntax added in v0.3.4

func CheckNoLSPFileSyntax(ext, content string) []DiagnosticBrief

CheckNoLSPFileSyntax 对不支持 LSP 的文件做原生语法检查 ext: 文件扩展名(如 .json, .yaml, .toml) content: 文件内容 返回诊断列表,空切片表示无问题

type DiagnosticSeverity added in v0.3.4

type DiagnosticSeverity int

DiagnosticSeverity 诊断严重程度

const (
	DiagnosticSeverityError       DiagnosticSeverity = 1
	DiagnosticSeverityWarning     DiagnosticSeverity = 2
	DiagnosticSeverityInformation DiagnosticSeverity = 3
	DiagnosticSeverityHint        DiagnosticSeverity = 4
)

type DidChangeTextDocumentParams added in v0.3.4

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

DidChangeTextDocumentParams textDocument/didChange 通知参数

type DidCloseTextDocumentParams

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

DidCloseTextDocumentParams didClose 通知参数

type DidOpenTextDocumentParams

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

DidOpenTextDocumentParams didOpen 通知参数

type DocumentFormattingParams added in v0.3.4

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

DocumentFormattingParams textDocument/formatting 请求参数

type DocumentSymbol

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

DocumentSymbol LSP 文档符号

type DocumentSymbolCapability

type DocumentSymbolCapability struct {
	HierarchicalDocumentSymbolSupport bool `json:"hierarchicalDocumentSymbolSupport,omitempty"`
}

DocumentSymbolCapability documentSymbol 能力

type DocumentSymbolParams

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

DocumentSymbolParams documentSymbol 请求参数

type FormatResult added in v0.3.4

type FormatResult struct {
	Formatted   bool              `json:"formatted"`
	Diagnostics []DiagnosticBrief `json:"diagnostics,omitempty"`
	Error       string            `json:"error,omitempty"`
}

FormatResult 格式化+诊断结果

func FormatAndDiagnose added in v0.3.4

func FormatAndDiagnose(workdir, filePath string) *FormatResult

FormatAndDiagnose 格式化文件并获取诊断信息 workdir: LSP 工作目录(通常为 session.Root) filePath: 文件绝对路径 对支持 LSP 的语言:调用 LSP 格式化 + publishDiagnostics 对不支持 LSP 的文件(JSON/YAML/TOML/INI/Markdown 等):做原生语法检查 即使 LSP 被禁用,原生语法检查仍然会运行

type FormattingOptions added in v0.3.4

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

FormattingOptions 格式化选项

type Hover

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

Hover LSP hover 结果

type HoverCapability

type HoverCapability struct {
	ContentFormat []string `json:"contentFormat,omitempty"`
}

HoverCapability hover 能力

type HoverParams

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

HoverParams hover 请求参数

type InitializeParams

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

InitializeParams LSP initialize 请求参数

type InitializeResult

type InitializeResult struct {
	Capabilities ServerCapabilities `json:"capabilities"`
	ServerInfo   *ServerInfo        `json:"serverInfo,omitempty"`
}

InitializeResult LSP initialize 响应结果

type LanguageServerConfig

type LanguageServerConfig struct {
	Command string
	Args    []string
}

LanguageServerConfig 语言服务器配置(命令+参数)

type Manager

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

Manager 管理多工作目录多语言的 LSP 客户端

func (*Manager) FormatAndDiagnose added in v0.3.4

func (m *Manager) FormatAndDiagnose(workdir, filePath string) *FormatResult

FormatAndDiagnose 格式化文件并获取诊断 对支持 LSP 的语言:调用 LSP 格式化 + publishDiagnostics 对不支持 LSP 的文件(JSON/YAML/TOML/INI/Markdown 等):做原生语法检查

func (*Manager) GetSymbols

func (m *Manager) GetSymbols(workdir, filePath string) ([]SymbolResult, error)

GetSymbols 获取指定文件的所有顶层符号及其结构体成员和注释

type MarkupContent

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

MarkupContent LSP 标记内容

type NotificationHandler added in v0.3.4

type NotificationHandler func(method string, params json.RawMessage)

NotificationHandler 处理服务器推送通知的回调

type Position

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

Position LSP 位置

type PublishDiagnosticsParams added in v0.3.4

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

PublishDiagnosticsParams textDocument/publishDiagnostics 通知参数

type Range

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

Range LSP 范围

type ServerCapabilities

type ServerCapabilities struct {
	TextDocumentSync       any `json:"textDocumentSync,omitempty"`
	HoverProvider          any `json:"hoverProvider,omitempty"`
	DocumentSymbolProvider any `json:"documentSymbolProvider,omitempty"`
}

ServerCapabilities LSP 服务器能力

type ServerInfo

type ServerInfo struct {
	Name    string `json:"name"`
	Version string `json:"version,omitempty"`
}

ServerInfo LSP 服务器信息

type SymbolKind

type SymbolKind int

SymbolKind LSP 符号类型

const (
	SymbolFile          SymbolKind = 1
	SymbolModule        SymbolKind = 2
	SymbolNamespace     SymbolKind = 3
	SymbolPackage       SymbolKind = 4
	SymbolClass         SymbolKind = 5
	SymbolMethod        SymbolKind = 6
	SymbolProperty      SymbolKind = 7
	SymbolField         SymbolKind = 8
	SymbolConstructor   SymbolKind = 9
	SymbolEnum          SymbolKind = 10
	SymbolInterface     SymbolKind = 11
	SymbolFunction      SymbolKind = 12
	SymbolVariable      SymbolKind = 13
	SymbolConstant      SymbolKind = 14
	SymbolString        SymbolKind = 15
	SymbolNumber        SymbolKind = 16
	SymbolBoolean       SymbolKind = 17
	SymbolArray         SymbolKind = 18
	SymbolObject        SymbolKind = 19
	SymbolKey           SymbolKind = 20
	SymbolNull          SymbolKind = 21
	SymbolEnumMember    SymbolKind = 22
	SymbolStruct        SymbolKind = 23
	SymbolEvent         SymbolKind = 24
	SymbolOperator      SymbolKind = 25
	SymbolTypeParameter SymbolKind = 26
)

符号类型

type SymbolResult

type SymbolResult struct {
	Name       string     `json:"name"`
	Kind       SymbolKind `json:"kind"`
	KindName   string     `json:"kindName"`
	Detail     string     `json:"detail,omitempty"`
	DocComment string     `json:"docComment,omitempty"`
	Signature  string     `json:"signature"`
	Code       string     `json:"code"`
	Line       uint32     `json:"line"`
}

SymbolResult 符号提取结果

func GetSymbols

func GetSymbols(workdir, filePath string) ([]SymbolResult, error)

GetSymbols 获取文件符号(对外 API) workdir: 工作目录 filePath: 文件绝对路径

type TextDocumentClientCapabilities

type TextDocumentClientCapabilities struct {
	Hover          *HoverCapability          `json:"hover,omitempty"`
	DocumentSymbol *DocumentSymbolCapability `json:"documentSymbol,omitempty"`
}

TextDocumentClientCapabilities LSP 文本文档客户端能力

type TextDocumentContentChangeEvent added in v0.3.4

type TextDocumentContentChangeEvent struct {
	Range       *Range `json:"range,omitempty"`
	RangeLength int    `json:"rangeLength,omitempty"`
	Text        string `json:"text"`
}

TextDocumentContentChangeEvent 文档内容变更事件

type TextDocumentIdentifier

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

TextDocumentIdentifier LSP 文本文档标识符

type TextDocumentItem

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

TextDocumentItem LSP 文本文档项

type TextEdit added in v0.3.4

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

TextEdit LSP 文本编辑

type Transport

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

Transport JSON-RPC 2.0 传输层,基于 Content-Length 帧协议(LSP 标准)

func NewTransport

func NewTransport(stdin io.WriteCloser, stdout io.ReadCloser) *Transport

NewTransport 创建传输层,启动后台读取 goroutine

func (*Transport) Close

func (t *Transport) Close() error

Close 关闭传输层

func (*Transport) HasPending added in v0.3.5

func (t *Transport) HasPending() bool

HasPending 返回是否存在尚未收到响应的在途请求(供空闲回收判断)

func (*Transport) SendNotification

func (t *Transport) SendNotification(method string, params any) error

SendNotification 发送通知(不需要响应)

func (*Transport) SendRequest

func (t *Transport) SendRequest(ctx context.Context, method string, params any) (json.RawMessage, error)

SendRequest 发送请求并等待响应 ctx 用于控制超时,建议使用带超时的 context

func (*Transport) SetNotificationHandler added in v0.3.4

func (t *Transport) SetNotificationHandler(handler NotificationHandler)

SetNotificationHandler 设置服务器推送通知的处理回调

type VersionedTextDocumentIdentifier added in v0.3.4

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

VersionedTextDocumentIdentifier 带版本号的文档标识

Jump to

Keyboard shortcuts

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