package app import ( "strings" "sync" "github.com/egoist/mygo/ui/editor" "mygoland/internal/lsp" ) // snippetCache 缓存 LSP 补全模板的解析结果(含失败,值为 nil)。 // // 同一个模板(如 Print(${1:}))在每次补全里都会出现,解析虽然便宜但 // 没必要每帧重做。key 是原始 snippet 文本,缓存随会话增长但条目有限, // 因为服务端能给出的模板种类是收敛的。 var snippetCache sync.Map // map[string]*editor.Snippet func parseCompletionSnippet(src string) *editor.Snippet { if v, ok := snippetCache.Load(src); ok { return v.(*editor.Snippet) } s, err := editor.ParseSnippet(src) if err != nil { s = nil } snippetCache.Store(src, s) return s } // plainSnippetText 把服务端返回的 snippet 剥成能直接插入的纯文本。 // // 只在 ParseSnippet 拒绝模板时走这里(例如服务端用了 choices 或 transform)。 // 不剥的话用户会看到 "Print(${1:})" 这种字面量,比没有补全还糟。 // 支持 ${1:name} → name(含嵌套占位递归剥离)、${1|a,b|} → a、 // $1/$0 → 空、\$ 转义。这是解析失败后的降级路径,只求不把 ${...} // 原样插进代码,不追求完整还原 TextMate 语义。 func plainSnippetText(s string) string { var b strings.Builder b.Grow(len(s)) for i := 0; i < len(s); { if s[i] == '\\' && i+1 < len(s) { b.WriteByte(s[i+1]) i += 2 continue } if s[i] != '$' { b.WriteByte(s[i]) i++ continue } i++ if i < len(s) && s[i] == '{' { // 花括号要配平:${2:${3:nested}} 里第一个 } 属于内层。 depth, j := 1, i+1 for j < len(s) && depth > 0 { switch { case s[j] == '\\' && j+1 < len(s): j += 2 case s[j] == '$' && j+1 < len(s) && s[j+1] == '{': depth++ j += 2 case s[j] == '}': depth-- j++ default: j++ } } if depth > 0 { b.WriteString(s[i-1:]) break } body := s[i+1 : j-1] switch { case strings.Contains(body, ":"): c := strings.IndexByte(body, ':') b.WriteString(plainSnippetText(body[c+1:])) // 内层继续剥 case strings.Contains(body, "|"): // choices 语法 ${1|a,b|}:降级取第一个选项。 opts := body[strings.IndexByte(body, '|')+1:] if e := strings.LastIndexByte(opts, '|'); e >= 0 { opts = opts[:e] } if comma := strings.IndexByte(opts, ','); comma >= 0 { opts = opts[:comma] } b.WriteString(opts) } i = j continue } j := i for j < len(s) && s[j] >= '0' && s[j] <= '9' { j++ } if j == i { b.WriteByte('$') } i = j } return b.String() } // applyCompletionSnippet 把 LSP 的 snippet 补全接到框架的模板能力上。 // // insertTextFormat==2 才是 snippet(实测 gopls v0.23 给函数补全返回 // Print(${1:}) 这类模板)。解析成功就交给 Completion.Snippet,由框架 // 负责 Tab/Shift+Tab 跳转;解析失败降级成纯文本,绝不整条丢掉。 // Kind 保持不变——它只决定图标,函数补全不该因为能跳占位就变成模板图标。 func applyCompletionSnippet(c *editor.Completion, it lsp.CompletionItem, insert string) { if it.InsertTextFormat != 2 { return } if s := parseCompletionSnippet(insert); s != nil { c.Snippet = s return } c.Insert = plainSnippetText(insert) }