package app import ( "context" "strings" "time" "github.com/egoist/mygo/ui/editor" "mygoland/internal/lsp" ) // inlayDelay 是请求内联提示前的等待:连续输入时不该每一帧都问一次 gopls。 const inlayDelay = 350 * time.Millisecond // scheduleInlays 安排一次内联提示刷新。 // // 用代数(gen)来丢弃过期结果:每次请求都会拿到一个新的 gen, // 回来时如果 d.inlayGen 已经变了,说明这期间文档又改过,结果作废。 func (a *App) scheduleInlays(d *Doc) { if a.lsp == nil || d == nil || d.st == nil || !lsp.IsGoFile(d.path) { return } if !a.inlaysOn() { d.st.SetInlays(nil) return } d.inlayGen++ gen := d.inlayGen time.AfterFunc(inlayDelay, func() { a.requestInlays(d, gen) }) } // requestInlays 向 gopls 要一次提示并交给编辑器。 // // gopls 在包还没分析完时会返回空结果,所以空结果要重试几次: // 打开大项目时分析可能要一两秒。 func (a *App) requestInlays(d *Doc, gen int) { a.requestInlaysTry(d, gen, 0) } func (a *App) requestInlaysTry(d *Doc, gen, attempt int) { if a.lsp == nil || d.inlayGen != gen { return } text := d.buf.String() ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() // 范围必须落在文档之内:gopls 会校验,给个超大列号会报 // 「column is beyond end of file」。用最后一行的实际长度最稳。 hints, err := a.lsp.InlayHints(ctx, d.uri, lsp.Range{ Start: lsp.Position{Line: 0, Character: 0}, End: endPosition(text), }) if err != nil { return } if len(hints) == 0 && attempt < 3 { // 还没分析完,过一会儿再问。 delay := time.Duration(attempt+1) * 1500 * time.Millisecond time.AfterFunc(delay, func() { a.requestInlaysTry(d, gen, attempt+1) }) return } ins := make([]editor.Inlay, 0, len(hints)) for _, h := range hints { label := h.Label.Text() if label == "" { continue } // 协议用 padding 表达「和前后留个空格」,这里翻成真实的空格。 if h.PaddingLeft { label = " " + label } if h.PaddingRight { label += " " } ins = append(ins, editor.Inlay{ Offset: lsp.PositionToOffset(text, h.Position), Text: label, }) } a.win.Update(func() { if d.inlayGen != gen { return } d.st.SetInlays(ins) }) } // endPosition 返回文本末尾的位置(最后一行 + 该行长度)。 func endPosition(text string) lsp.Position { lines := strings.Split(text, "\n") last := len(lines) - 1 if last < 0 { return lsp.Position{} } return lsp.Position{Line: last, Character: len(lines[last])} }