代码动作改用选区、补文件级请求、滤掉 gopls 的浏览类命令

第 10 项。原报告说「代码动作只取光标行 range,所以生成测试/实现接口取
不到」——实测(gopls v0.23)推翻了一半,真问题在别处:

1. 选区被忽略。原来一律传整行,用户选中 foo() 按 Alt+Enter,gopls 收到
   整行,只能给 refactor.extract.function;refactor.extract.variable 和
   refactor.inline.call **只在范围正好圈住表达式时才返回**。
2. 噪音淹没有效动作。一次请求 6–9 项,其中 5 项是 gopls.doc(开
   pkg.go.dev)、assembly、free_symbols、client_open_url、gc_details。
   「Extract variable」被挤到第七位。

而「生成测试」(source.addTest)本来就有;「零宽位置会丢快速修复」也是
错的——gopls 会把位置摊到所属节点,行首零宽照样拿得到 quickfix。

改法:
- 有选区用选区,没有才用整行;
- 发两次请求:光标/选区(带同行诊断)+ 整文件且 only=refactor.rewrite
  (refactor.rewrite.addTags 这类只有范围覆盖到才出现);
- 按**命令名**过滤那 5 个浏览命令(不是标题,标题会随版本变),只黑
  已知噪音、其余放行,gopls 加新能力不会被误杀;
- 同标题取第一次出现的那份(与用户眼前范围一致),再按
  IsPreferred → quickfix → refactor → source 稳定排序;
- 全是浏览命令时提示「这里有 N 项,但都只是打开文档/汇编之类的浏览
  命令,已隐藏」,不再假装什么都没发生。

验证分三层:
- 13 条 app 层单测:范围(含 UTF-16 中文列)、诊断相交、噪音判定、
  合并去重首见优先、排序稳定性;
- 3 条真 gopls 回归:选区给 extract.variable/inline.call、整行不给、
  整文件 only=refactor.rewrite 给 addTags、缺 import 的 quickfix 依赖
  诊断且对零宽位置也宽容;
- 1 条 app 层全管线集成:选中表达式 → 必须出现 extract.variable 且不得
  混入浏览命令。
真实窗口截图 docs/code-action-panel.png 只剩两项,5 个浏览命令没露头。

顺带把 Client.CodeActions 拆出 CodeActionsOnly(支持 context.only),
queryCodeActions 从 goroutine 里拆出来以支持集成测试;actionKindLabel
给 source.addTest/organizeImports/fixAll 单列文案,并给 IsPreferred 加
「推荐 ·」前缀。
This commit is contained in:
zerorigin committed 2026-11-05 16:38:30 +08:00
1 parent c35564b65e
commit 6b07d16738
7 files changed
+857 -33

No files matched your search

+18 -1
View File
@@ -367,11 +367,28 @@ func (c *Client) Rename(ctx context.Context, uri string, pos Position, newName s
// CodeActions 请求指定范围上的代码动作(快速修复、整理 import 等)。
func (c *Client) CodeActions(ctx context.Context, uri string, r Range, diags []Diagnostic) ([]CodeAction, error) {
return c.CodeActionsOnly(ctx, uri, r, diags, nil)
}
// CodeActionsOnly 同 CodeActions,但可以按 kind 过滤(LSP 的 context.only)。
//
// only 为空表示不过滤。gopls 支持 "quickfix"、"refactor"、"refactor.rewrite"、
// "source" 这些前缀;用它最实际的好处是「只问整文件级的重构」时不会顺带
// 把一堆焦点相关的动作再拉一遍。
func (c *Client) CodeActionsOnly(ctx context.Context, uri string, r Range, diags []Diagnostic, only []string) ([]CodeAction, error) {
if diags == nil {
// JSON 里 null 和 [] 对某些服务端不等价,统一给空数组。
diags = []Diagnostic{}
}
cctx := map[string]any{"diagnostics": diags}
if len(only) > 0 {
cctx["only"] = only
}
var out []CodeAction
err := c.conn.call(ctx, "textDocument/codeAction", map[string]any{
"textDocument": TextDocumentIdentifier{URI: uri},
"range": r,
"context": map[string]any{"diagnostics": diags},
"context": cctx,
}, &out)
return out, err
}