Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Agent 笔记:编辑器复制代码引用位置

状态:已实现

## 先说结论

Viva 编辑器的右键菜单提供复制源码位置,默认把所点行复制到剪贴板。有语言服务器同步提供的文档符号时,Rust Core 把包、类、方法及原始签名组成引用;没有可靠符号时只复制文件路径和行号,不推测源码。macOS 与 Windows 共用实现,避免两端产生不同格式。

## 问题

#2015 需要从编辑器快速得到方法引用及行号。原有标签页“复制路径/引用”只处理文件路径;从文件名和源码文本自己猜方法签名会在重载方法、嵌套类和未保存编辑时产生错误引用。

## 决策

- 使用语言服务器协议(LSP)的 `documentSymbols`:先确认当前文档已同步,随后由现有异步请求链获取符号;优先使用与文档修订相同的 Structure 缓存。
- 桌面端只捕获右键坐标、管理请求生命周期并写入系统剪贴板;格式规则属于 Rust Core 的 `editor.copyReferenceLocation`。
- Core 只消费上游提供的符号名称、类型、作用域及方法签名,没有可靠信息就按 `文件路径#L行号` 回退。用户看到的一基行号由 Core 统一处理。
- 旧文档或项目、关闭的标签、后续编辑以及新一次复制都不能接收过期操作。插件会话失败与缺少符号不阻断文件路径回退。
- 菜单复用现有共享 i18n 的“复制源码位置”(`native.copySourceLocation`),而不是在桌面端增加无法生成的硬编码界面文案。

## 考虑过的备选方案

- **直接解析 Java 源文件提取类/方法**:不采用。需要为每门语言维护解析规则,还会误识别重载方法与泛型,违反 Core 不特判语言的约束。
- **直接复制文件行号,不请求 LSP**:只作为缺失服务器的回退;否则无法实现 Issue 要求的符号级引用。
- **把格式规则写入 Go/Viva**:不采用。相同功能在两个平台的语义必须由共享 Core 定义。

## 后果

右键复制不启动新的常驻服务,也不阻塞编辑器线程。符号质量取决于语言服务器提供的名字与签名;有些服务器不提供包名或方法参数时,输出会相应变短。未保存修改尚未完成 LSP 同步时,优先保证位置正确并回退文件路径,不能拿旧符号当新信息。

## 验证

- Core: `cargo test -p lithe-editor`;`cargo test -p lithe-core copy_reference_location`。
- Viva: `scripts/desktop/desktop-go.sh test ./internal/workbench -run 'TestCopyReferenceLocation|TestEditorContextMenuCopiesReference' -count=1`。
- 视觉: `LITHE_VISUAL_OUTPUT_DIR=.artifacts/issue-2015 scripts/desktop/desktop-go.sh test -tags 'vivahead lithevisual' ./internal/workbench -run '^TestVisualCopyReferenceLocation$' -count=1`。
- 两个平台原生集成与粘贴结果仍需实际执行,不能以静态源代码检查替代。

## 适用范围

`desktop/internal/workbench/copy_reference.go`、`desktop/internal/workbench/editor_menu.go`、`desktop/internal/core/reference_location.go`、`rust/crates/editor/src/reference_location.rs`、`rust/contracts/rust-core-api.md`。
29 changes: 29 additions & 0 deletions desktop/internal/core/reference_location.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package core

import "context"

// ReferenceLocationRequest is a snapshot of the requested caret and the LSP
// symbols synchronized to that document revision. Coordinates are zero-based
// UTF-16 positions, while the result's human-readable line is one-based.
type ReferenceLocationRequest struct {
Path string `json:"path"`
Line int `json:"line"`
UTF16Column int `json:"utf16Column"`
Symbols []DocumentSymbol `json:"symbols"`
}

type ReferenceLocationResult struct {
Reference string `json:"reference"`
Source string `json:"source"`
}

// CopyReferenceLocation uses the shared Rust Core formatter. The desktop host
// does not interpret package, type, method names or signature conventions.
func (c *Client) CopyReferenceLocation(ctx context.Context, request ReferenceLocationRequest) (ReferenceLocationResult, error) {
if request.Symbols == nil {
request.Symbols = []DocumentSymbol{}
}
var result ReferenceLocationResult
err := c.Execute(ctx, "editor.copyReferenceLocation", request, &result)
return result, err
}
130 changes: 130 additions & 0 deletions desktop/internal/workbench/copy_reference.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
package workbench

import (
"context"

"github.com/1lck/Lithe-IDEA/desktop/internal/core"
"github.com/1lck/Lithe-IDEA/desktop/internal/i18n"
"github.com/vivaui/viva/app"
)

// A secondary press chooses the line under the pointer, not the previous
// keyboard caret. The context-menu item consumes the coordinate after the
// popup closes; each operation owns a revision and an identity token.
type referenceClick struct {
documentID int
line, column int
}

type referenceRequest struct {
project *project
documentID, revision int
line, column int
path string
pending *semanticPending
}

type copyReferenceState struct {
click *referenceClick
request *referenceRequest
}

type referenceKernel interface {
CopyReferenceLocation(context.Context, core.ReferenceLocationRequest) (core.ReferenceLocationResult, error)
}

func (a *App) copyReferenceLocation(p *project, d *document) {
if p == nil || d == nil || d.virtual || d.path == "" || a.project != p {
return
}
kernel, ok := a.kernel.(referenceKernel)
if !ok {
return
}
a.performed("editor.copyReferenceLocation", surfaceContextMenu)
line, column := d.view.CaretUTF16()
if click := a.editor.copyReference.click; click != nil && click.documentID == d.id {
line, column = click.line, click.column
}
a.editor.copyReference.click = nil
if previous := a.editor.copyReference.request; previous != nil && previous.pending != nil {
a.cancelSemantic(previous.pending)
}
request := &referenceRequest{
project: p, documentID: d.id, revision: d.view.Revision(),
line: line, column: column, path: d.path,
}
a.editor.copyReference.request = request

// A loaded Structure result can be used only for exactly this document
// revision. Otherwise ask the same LSP documentSymbols feature directly;
// never use a stale tree from a previous document or unsaved edit.
outline := &a.editor.outline
if outline.project == p && outline.documentID == d.id && outline.loaded &&
outline.revision == request.revision {
a.finishReferenceLocation(request, outline.symbols, kernel)
return
}
server, offered := a.editorServer(d, featureDocumentSymbols)
if offered && server != nil && a.semanticDocumentReady(d) {
request.pending = a.submitEditorRequest(pluginSemanticCopyReference, p, d, server, core.PluginSemanticRequest{})
return
}
// An unavailable or unsynchronized language server does not block copying:
// the shared Core produces a path reference instead of guessing symbols.
a.finishReferenceLocation(request, nil, kernel)
}

// applyReferenceSymbols is reached through the ordinary semantic event router.
// Failed, unsupported or malformed symbols retain a useful file/line fallback.
func (a *App) applyReferenceSymbols(pending *semanticPending, event core.BackendEvent, failed bool) {
request := a.editor.copyReference.request
if request == nil || request.pending != pending {
return
}
request.pending = nil
p, d := a.currentSemanticDocument(request.documentID)
if p != request.project || d == nil || d.view.Revision() != request.revision {
return
}
var symbols []core.DocumentSymbol
if !failed {
var err error
symbols, err = core.PluginDocumentSymbols(event)
if err != nil {
a.backgroundFailed("editor_copy_reference_symbols", err)
}
}
if kernel, ok := a.kernel.(referenceKernel); ok {
a.finishReferenceLocation(request, symbols, kernel)
}
}

func (a *App) finishReferenceLocation(request *referenceRequest, symbols []core.DocumentSymbol, kernel referenceKernel) {
a.background(request.project, kernelCallTimeout, func(ctx context.Context) func(*App) {
result, err := kernel.CopyReferenceLocation(ctx, core.ReferenceLocationRequest{
Path: request.path, Line: request.line, UTF16Column: request.column, Symbols: symbols,
})
return func(a *App) {
if a.editor.copyReference.request != request || a.project != request.project {
return
}
d := request.project.docs.find(request.documentID)
if d == nil || d.view.Revision() != request.revision ||
request.project.selectedDocument(request.project.docs.group) != d {
a.editor.copyReference.request = nil
return
}
a.editor.copyReference.request = nil
if err != nil {
a.operationFailed("editor_copy_reference", err)
a.notifyError(a.text.Errors.Core(err.Error()))
return
}
if err := app.SetClipboardText(result.Reference); err != nil {
a.operationFailed("clipboard_copy", err)
a.notifyError(i18n.SharedFormat(a.language(), "desktop.files.copyFailed", map[string]string{"reason": err.Error()}))
}
}
})
}
106 changes: 106 additions & 0 deletions desktop/internal/workbench/copy_reference_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
package workbench

import (
"os"
"path/filepath"
"strconv"
"strings"
"testing"

"github.com/1lck/Lithe-IDEA/desktop/internal/core"
)

func TestCopyReferenceLocationWithoutServerCopiesFileLine(t *testing.T) {
h := newHarness(t, &testKernel{Client: core.NewClient()})
root := t.TempDir()
h.open(root)
path := filepath.Join(root, "reference.go")
if err := os.WriteFile(path, []byte("package main\nfunc work() {}\n"), 0600); err != nil {
t.Fatal(err)
}
p := h.app.project
h.app.openFile(p, path)
h.settleChain()
d := p.docs.byPath(path)
if d == nil {
t.Fatal("document not opened")
}
d.view.GoToLine(2)
h.app.copyReferenceLocation(p, d)
h.await("copy file and line", func() bool {
return h.driver.Clipboard() == path+"#L2"
})
}

func TestCopyReferenceLocationUsesLanguageSymbols(t *testing.T) {
f := newSemanticFixture(t)
f.server.features = map[string]bool{featureDocumentSymbols: true}
f.d.view.SetSelection(0, 0)
f.h.app.copyReferenceLocation(f.p, f.d)
f.h.await("reference symbol request submitted", func() bool {
req := f.h.app.editor.copyReference.request
return req != nil && req.pending != nil && req.pending.operation != ""
})
pending := f.h.app.editor.copyReference.request.pending
f.deliver(t, pending.operation, pluginMethodDocumentSymbols, symbolsResult(t,
symbolAt("DemoClass", 5, 0, 1,
symbolAt("goHome(String,Integer)", 6, 0, 1)),
))
t.Cleanup(func() {
req := f.h.app.editor.copyReference.request
t.Logf("reference diagnostics: clipboard=%q pendingRequest=%v activeGroup=%q docGroup=%q selected=%p expectedDoc=%p", f.h.driver.Clipboard(), req != nil, f.p.docs.group, f.d.group, f.p.selectedDocument(f.p.docs.group), f.d)
})
f.h.await("symbol reference request settled", func() bool {
return f.h.app.editor.copyReference.request == nil
})
if got := f.h.driver.Clipboard(); got != "DemoClass#goHome(String,Integer)#L1" {
t.Fatalf("copied %q, want method reference", got)
}
}

func TestCopyReferenceLocationDiscardsOldDocumentRevision(t *testing.T) {
f := newSemanticFixture(t)
f.server.features = map[string]bool{featureDocumentSymbols: true}
f.h.app.copyReferenceLocation(f.p, f.d)
f.h.await("stale-reference symbol request submitted", func() bool {
req := f.h.app.editor.copyReference.request
return req != nil && req.pending != nil && req.pending.operation != ""
})
pending := f.h.app.editor.copyReference.request.pending
f.h.app.insertForTest(f.d, "changed")
f.deliver(t, pending.operation, pluginMethodDocumentSymbols, symbolsResult(t,
symbolAt("Outdated", 5, 0, 1),
))
f.h.settleChain()
if got := f.h.driver.Clipboard(); strings.Contains(got, "Outdated") {
t.Fatalf("stale reference copied: %q", got)
}
}

func TestEditorContextMenuCopiesReferenceAtSecondaryPress(t *testing.T) {
h := newHarness(t, &testKernel{Client: core.NewClient()})
root := t.TempDir()
h.open(root)
path := filepath.Join(root, "reference.txt")
if err := os.WriteFile(path, []byte("one\ntwo\nthree\n"), 0600); err != nil {
t.Fatal(err)
}
p := h.app.project
h.app.openFile(p, path)
h.settleChain()
d := p.docs.byPath(path)
if d == nil {
t.Fatal("document missing")
}
bounds := h.topHit(d.hit)
at := center(bounds)
line, _, ok := d.view.PositionAt(at.X, at.Y)
if !ok {
t.Fatal("editor has not painted")
}
h.rightClickAt(bounds)
h.clickNamed(h.shared("native.copySourceLocation"))
h.await("right-click location copied", func() bool {
return h.driver.Clipboard() == path+"#L"+strconv.Itoa(line+1)
})
}
Loading
Loading