Files
MyGolandRelease/internal/app/lsp.go
T
zerorigin a80c0f886a MyGoland 首次提交:Go 轻量 IDE
- 编辑器:多标签、语法高亮、gopls 全套(补全/诊断/跳转/重命名/代码动作/内联提示/签名大纲)
- 调试:Delve DAP(断点/条件断点/变量树/表达式求值/goroutine 列表)
- 测试:结果树、覆盖率行着色、失败跳源码、-run 精确运行、行号可跑标记
- Git:状态着色、选择性暂存提交、pull/push、历史并排对比
- 本地历史 + 自动快照 + 崩溃恢复、会话/光标恢复
- 全局搜索替换(预览+确认,GBK 安全)、多终端、gopls 崩溃自愈
- 设计文档与验证记录见 docs/plans/
2026-11-04 16:37:05 +08:00

470 lines
11 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package app
import (
"context"
"sort"
"strings"
"time"
"github.com/egoist/mygo/ui/editor"
"mygoland/internal/lsp"
)
// requestTimeout 是单个语言服务器请求的上限。
const requestTimeout = 10 * time.Second
// startLSP 在工作区打开后异步拉起 gopls。
func (a *App) startLSP(root string) {
a.lspGen++
gen := a.lspGen
a.lspLastStart = time.Now()
a.lspState = "gopls 启动中…"
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Second)
defer cancel()
c, err := lsp.Start(ctx, lsp.Options{
Root: root,
Logf: func(format string, args ...any) {
// 语言服务器日志只写标准错误,避免污染界面。
logf("lsp: "+format, args...)
},
OnDiagnostics: func(uri string, version int, ds []lsp.Diagnostic) {
if a.win == nil {
return
}
a.win.Update(func() { a.applyDiagnostics(uri, version, ds) })
},
OnExit: func() { a.onLSPExit(root, gen) },
})
a.win.Update(func() {
if err != nil {
a.lsp = nil
a.lspState = "gopls 不可用(" + firstLine(err.Error()) + ")"
return
}
a.lsp = c
a.lspState = "gopls 就绪"
for _, d := range a.docs {
a.lspOpen(d)
}
})
}()
}
// onLSPExit gopls 进程退出。手动重启/关闭时 a.lsp 已换人或代数已变,直接忽略;
// 真是意外崩溃就自动重启——但 10 秒内刚起过又死的(比如 go.mod 坏了导致
// 起一次崩一次)不再自动拉,免得无限重启循环,交给菜单手动处理。
func (a *App) onLSPExit(root string, gen int) {
a.win.Update(func() {
if a.root != root || gen != a.lspGen || a.lsp == nil {
return
}
a.lsp = nil
if time.Since(a.lspLastStart) < 10*time.Second {
a.lspState = "gopls 已退出(菜单「重启语言服务器」可手动拉起)"
a.refresh()
return
}
a.lspState = "gopls 意外退出,正在重启…"
a.resetDocsForLSP()
a.startLSP(root)
a.refresh()
})
}
// resetDocsForLSP 清掉文档的已同步标记:重连后所有 Go 文件要重新 didOpen
//(prev 快照由 lspOpen 重新设)。须在主线程调用。
func (a *App) resetDocsForLSP() {
for _, d := range a.docs {
if lsp.IsGoFile(d.path) {
d.opened = false
d.sent = 0
}
}
}
// restartLSP 手动重启语言服务器:改了 go.mod、gopls 卡死、缓存抽风时用。
func (a *App) restartLSP() {
if a.root == "" {
return
}
if c := a.lsp; c != nil {
a.lsp = nil
go c.Close()
}
a.resetDocsForLSP()
a.startLSP(a.root)
a.refresh()
}
// RunModTidy 整理模块依赖,输出走运行面板;tidy 完 gopls 会自己跟上。
func (a *App) RunModTidy() {
a.startTask("go mod tidy", "go", "mod", "tidy")
}
// lspOpen 把文档同步给语言服务器。
func (a *App) lspOpen(d *Doc) {
if a.lsp == nil || d.opened || !lsp.IsGoFile(d.path) {
return
}
d.opened = true
d.sent = d.buf.Version()
d.prev = d.buf.Snapshot()
_ = a.lsp.DidOpen(d.uri, "go", int(d.sent), d.prev.String())
// 打开之后要等 gopls 分析完才会有提示,但请求本身是异步的,先发出去,
// 服务端会等到有结果再回。
a.scheduleInlays(d)
}
// lspSync 把缓冲区的增量改动推给语言服务器,须在主线程调用。
func (a *App) lspSync(d *Doc) {
if a.lsp == nil || !lsp.IsGoFile(d.path) {
return
}
if !d.opened {
a.lspOpen(d)
return
}
ver := d.buf.Version()
if ver == d.sent {
return
}
old := d.prev.String()
cur := d.buf.String()
change, text, ok := lsp.DiffChange(old, cur)
if !ok {
d.sent = ver
d.prev = d.buf.Snapshot()
return
}
d.sent = ver
d.prev = d.buf.Snapshot()
_ = a.lsp.DidChange(d.uri, int(ver), []lsp.ContentChange{{
Range: &change,
Text: text,
}})
// 文本变了,提示里的类型/参数名也可能变。
a.scheduleInlays(d)
}
// applyDiagnostics 把 LSP 诊断转成编辑器诊断,须在主线程调用。
func (a *App) applyDiagnostics(uri string, version int, ds []lsp.Diagnostic) {
var d *Doc
for _, x := range a.docs {
if x.uri == uri {
d = x
break
}
}
if d == nil {
return
}
ver := uint64(version)
var text string
switch {
case ver == 0 || ver == d.buf.Version():
text = d.buf.String()
ver = d.buf.Version()
case d.prev.Version() == ver:
text = d.prev.String()
default:
// 诊断对应的版本已经过期,丢弃以免位置错乱。
return
}
// 原样留一份:请求代码动作时要把服务端给的诊断(含 data)带回去。
d.diags = append([]lsp.Diagnostic(nil), ds...)
out := make([]editor.Diagnostic, 0, len(ds))
probs := make([]Problem, 0, len(ds))
for _, x := range ds {
sev := severityOf(x.Severity)
out = append(out, editor.Diagnostic{
Start: lsp.PositionToOffset(text, x.Range.Start),
End: lsp.PositionToOffset(text, x.Range.End),
Severity: sev,
Message: x.Message,
Source: x.Source,
})
probs = append(probs, Problem{
Path: d.path,
Line: x.Range.Start.Line + 1,
Col: x.Range.Start.Character + 1,
Text: x.Message,
Severity: sev,
})
}
d.problems = probs
d.st.SetDiagnostics(ver, out)
// 诊断到了通常说明这轮分析结束,顺手要一次内联提示。
a.scheduleInlays(d)
}
// severityOf 把 LSP 严重级别映射到编辑器。
func severityOf(s int) editor.Severity {
switch s {
case 2:
return editor.SeverityWarning
case 3:
return editor.SeverityInfo
case 4:
return editor.SeverityHint
}
return editor.SeverityError
}
// complete 向语言服务器要补全,结果回到主线程显示。
func (a *App) complete(d *Doc, r editor.CompletionRequest) {
c := a.lsp
if c == nil {
d.st.ShowCompletions(r.Offset-len(r.Prefix), wordsOf(d.buf, r.Prefix))
return
}
at := r.Offset - len(r.Prefix)
pos := positionAt(d, r.Offset)
version := r.Version
go func() {
ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
defer cancel()
items, err := c.Completion(ctx, d.uri, pos)
if err != nil || len(items) == 0 {
// 语言服务器还没准备好或没有建议时,退回词表补全。
a.win.Update(func() {
if d.buf.Version() != version {
return
}
d.st.ShowCompletions(at, wordsOf(d.buf, r.Prefix))
})
return
}
out := make([]editor.Completion, 0, len(items))
for _, it := range items {
out = append(out, toEditorCompletion(it))
}
a.win.Update(func() {
if d.buf.Version() != version {
return
}
d.st.ShowCompletions(at, out)
})
}()
}
// toEditorCompletion 把 LSP 补全项映射到编辑器补全项。
func toEditorCompletion(it lsp.CompletionItem) editor.Completion {
insert := it.InsertText
if it.TextEdit != nil && it.TextEdit.NewText != "" {
insert = it.TextEdit.NewText
}
if insert == "" {
insert = it.Label
}
return editor.Completion{
Label: it.Label,
Detail: it.Detail,
Kind: completionKind(it.Kind),
Insert: insert,
Documentation: it.DocumentationText(),
FilterText: it.FilterText,
}
}
// completionKind 映射 LSP 补全类型。
func completionKind(k int) editor.CompletionKind {
switch k {
case 1:
return editor.CompletionText
case 2:
return editor.CompletionMethod
case 3, 4:
return editor.CompletionFunction
case 5:
return editor.CompletionField
case 6, 12:
return editor.CompletionVariable
case 7, 8, 22, 25:
return editor.CompletionType
case 9:
return editor.CompletionModule
case 10, 11:
return editor.CompletionField
case 13, 14:
return editor.CompletionKeyword
case 15:
return editor.CompletionSnippet
case 20, 21:
return editor.CompletionConstant
}
return editor.CompletionText
}
// hover 请求悬停信息。
func (a *App) hover(d *Doc, r editor.HoverRequest) {
c := a.lsp
if c == nil {
return
}
pos := positionAt(d, r.Offset)
go func() {
ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
defer cancel()
h, err := c.Hover(ctx, d.uri, pos)
if err != nil || h == nil {
return
}
text := strings.TrimSpace(markdownToText(h.Text()))
if text == "" {
return
}
a.win.Update(func() {
start, end := wordBounds(d, r.Offset)
if h.Range != nil {
cur := d.buf.String()
start = lsp.PositionToOffset(cur, h.Range.Start)
end = lsp.PositionToOffset(cur, h.Range.End)
}
d.st.ShowHover(start, end, text, nil)
})
}()
}
// definition 跳转到定义。
func (a *App) definition(d *Doc, offset int) {
c := a.lsp
if c == nil {
return
}
pos := positionAt(d, offset)
go func() {
ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
defer cancel()
locs, err := c.Definition(ctx, d.uri, pos)
if err != nil || len(locs) == 0 {
return
}
loc := locs[0]
path := lsp.URIToPath(loc.URI)
if path == "" {
return
}
a.win.Update(func() { a.openAt(path, loc.Range.Start) })
}()
}
// openAt 在指定位置打开文件,用于跳转定义。
func (a *App) openAt(path string, pos lsp.Position) {
d, err := a.loadDoc(path)
if err != nil {
a.alert("无法打开", err.Error())
return
}
line := pos.Line
if line >= d.buf.LineCount() {
line = d.buf.LineCount() - 1
}
col := lsp.UTF16ToByte(d.buf.Line(line), pos.Character)
d.st.GoTo(editor.Pos{Line: line, Col: col})
d.st.ScrollTo(line)
}
// formatCurrent 格式化当前文档。
func (a *App) FormatCurrent() {
d := a.doc()
if d == nil {
return
}
c := a.lsp
if c == nil || !lsp.IsGoFile(d.path) {
return
}
uri, path := d.uri, d.path
version := d.buf.Version()
go func() {
ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
defer cancel()
edits, err := c.Format(ctx, uri, lsp.FormattingOptions{TabSize: 4, InsertSpaces: false})
if err != nil || len(edits) == 0 {
return
}
a.win.Update(func() {
target := a.find(path)
if target == nil || target.buf.Version() != version {
return
}
a.applyEdits(target, edits)
})
}()
}
// applyEdits 应用一组文本修改,整个过程算一步撤销。
func (a *App) applyEdits(d *Doc, edits []lsp.TextEdit) {
if len(edits) == 0 {
return
}
text := d.buf.String()
type span struct {
start, end int
text string
}
spans := make([]span, 0, len(edits))
for _, e := range edits {
spans = append(spans, span{
start: lsp.PositionToOffset(text, e.Range.Start),
end: lsp.PositionToOffset(text, e.Range.End),
text: e.NewText,
})
}
sort.Slice(spans, func(i, j int) bool { return spans[i].start > spans[j].start })
d.buf.Transact(func() {
for _, s := range spans {
d.buf.Edit(editor.Edit{Start: s.start, End: s.end, Text: s.text})
}
})
}
// positionAt 把字节偏移转成 LSP 位置。
func positionAt(d *Doc, off int) lsp.Position {
p := d.buf.Pos(off)
line := d.buf.Line(p.Line)
col := p.Col
if col > len(line) {
col = len(line)
}
return lsp.Position{Line: p.Line, Character: lsp.UTF16Len(line[:col])}
}
// wordBounds 返回光标处单词的字节区间。
func wordBounds(d *Doc, off int) (int, int) {
isWord := func(b byte) bool {
return b == '_' || b >= 'a' && b <= 'z' || b >= 'A' && b <= 'Z' || b >= '0' && b <= '9'
}
p := d.buf.Pos(off)
line := d.buf.Line(p.Line)
if p.Col > len(line) {
return off, off
}
a, z := p.Col, p.Col
for a > 0 && isWord(line[a-1]) {
a--
}
for z < len(line) && isWord(line[z]) {
z++
}
start := off - (p.Col - a)
return start, start + (z - a)
}
// markdownToText 粗略去掉 markdown 标记,让悬停内容更好读。
func markdownToText(s string) string {
s = strings.ReplaceAll(s, "```go\n", "")
s = strings.ReplaceAll(s, "```", "")
return s
}
// firstLine 取错误信息的第一行。
func firstLine(s string) string {
if i := strings.IndexByte(s, '\n'); i >= 0 {
return s[:i]
}
return s
}