package app import ( "context" "path/filepath" "strings" "time" "mygoland/internal/lsp" ) // symbolDelay 是输入停顿多久后才问 gopls:每敲一个字都查一次会很卡。 const symbolDelay = 180 * time.Millisecond // OpenSymbols 打开「转到符号」(全工作区)。 func (a *App) OpenSymbols() { a.pal = paletteState{open: true, symbol: true, waiting: true} a.pal.gen++ gen := a.pal.gen go a.searchSymbols("", gen) a.win.Update(func() {}) } // searchSymbols 向 gopls 要一组符号填进面板。 func (a *App) searchSymbols(query string, gen int) { if a.lsp == nil || a.root == "" { a.win.Update(func() { if a.pal.gen == gen { a.pal.waiting = false } }) return } ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) defer cancel() syms, err := a.lsp.WorkspaceSymbols(ctx, query) items := make([]paletteItem, 0, len(syms)) if err == nil { for _, s := range syms { uri := s.Location.URI if uri == "" { uri = s.TargetURI } path := lsp.URIToPath(uri) if path == "" { continue } // gopls 的 workspace/symbol 会把依赖包也算进来 // (空查询时尤其明显),这里只留工作区内的符号。 if !within(a.root, path) { continue } rel := filepath.ToSlash(path) if r, err := filepath.Rel(a.root, path); err == nil { rel = filepath.ToSlash(r) } // 面板的 itemLine 行是「小字 Label 在上、大字 Text 在下」, // 所以名字放 Text,种类和文件放 Label。 items = append(items, paletteItem{ Kind: itemLine, Path: path, Line: s.Location.Range.Start.Line + 1, Label: kindName(s.Kind) + " · " + rel, Hint: rel + " " + s.ContainerName, Text: s.Name, }) } } a.win.Update(func() { // 期间用户又敲了字,这批结果作废。 if a.pal.gen != gen || !a.pal.symbol { return } a.pal.items = items a.pal.waiting = false a.pal.sel = 0 }) } // kindName 把 LSP 的符号类型编号转成中文,放在副标题里帮助区分。 func kindName(kind int) string { switch kind { case 2, 3, 4, 23: return "模块/包/命名空间" case 5: return "类" case 6: return "方法" case 7, 8: return "属性/字段" case 9: return "构造函数" case 10: return "枚举" case 11: return "接口" case 12: return "函数" case 13: return "变量" case 14: return "常量" case 22: return "结构体" case 26: return "类型参数" } return "符号" } // scheduleSymbols 输入变化后延迟查询,避免每个按键都打一次 gopls。 func (a *App) scheduleSymbols(query string) { a.pal.gen++ gen := a.pal.gen a.pal.waiting = true time.AfterFunc(symbolDelay, func() { a.searchSymbols(query, gen) }) } // symbolHint 把查询串规整一下:gopls 对空串会返回一大把,直接原样用。 func symbolHint(q string) string { return strings.TrimSpace(q) }