Skip to content
Merged
Original file line number Diff line number Diff line change
Expand Up @@ -4,37 +4,46 @@

## 先说结论

Viva 的 Core 适配层可以取得语言的行注释符号,并调用共享的注释、复制、删除和移动行规则。适配层不修改文档;快捷键、菜单、撤销和窗口接线还未完成,不能将接口可调用当作用户功能已实现。
切换行注释、复制、删除、移动行的变换规则只在 Core 的 `editor.lineEdit`;Core 不认识任何语言,行注释符号由桌面端语言注册表给出。桌面端只取选中行及前后各一行交给 Core,在后台调用,结果核对文档版本后作为一次可撤销编辑写回。

## 问题

行变换需要正确处理跨行选区、UTF-16 代理对、CRLF 和无操作边界。Go 中再实现这些规则会与 Core 和其他宿主分叉;但 Core 需要完整文本,如果直接在键盘事件中同步传入大文档,会阻塞交互并造成额外复制。
行变换需要正确处理跨行选区、UTF-16 代理对、CRLF 和无操作边界,Go 中再实现一遍会与 Core 分叉。注释符号是语言知识:Core 曾用一张写死的扩展名表回答 `editor.lineCommentToken`,与编辑器语言注册表重复,插件声明的语言也进不了那张表,违反 Core 对语言零特判的约束([#1856](https://github.com/1lck/Lithe-IDEA/issues/1856) 第 5 项)。Core 需要文本,在键盘事件里同步传入整份大文档会阻塞输入。

## 决策

行变换和注释符号由 `editor.lineEdit` 与 `editor.lineCommentToken` 决定。返回的替换范围和选区使用 UTF-16 偏移;`applied: false` 是无操作,不能改写文档或消费快捷键。未来接线必须核对文档身份、版本、选区和输入法组合状态,将已确认的变更作为一个可撤销编辑;迟到结果不能覆盖新内容。
- 变换规则:`editor.lineEdit` 返回 UTF-16 偏移的替换范围和选区;`applied: false` 是无操作,不改写文档。`toggleLineComment` 必须带 `commentToken`。
- 注释符号:`syntax.Registry.CommentsForPath` 是唯一来源。内置语言在 `desktop/internal/editor/syntax/languages.go` 声明 `Comments`;插件语言用 `languages[].configuration.lineComment` 声明,替换同 ID 内置语言时未声明的字段沿用内置值;只为服务器或调试器认领文件、既无语法也无注释的插件语言(如调试插件的 `clangd`)沿用按文件名选出的内置语言的注释,与 `SyntaxForPath` 沿用其配色一致。没有行注释符号时提示 `desktop.editor.noLineComment`,不调用 Core。
- 有界输入:`editorview.View.LineEditInput` 只取选中行及前后各一行,超过 1 MiB 不处理;输入法组合中或只读视图不处理。
- 接线:快捷键(Alt+上下、Alt+Shift+上下、Primary+Shift+K、Primary+/)和编辑器右键菜单都走 `workbench.runLineOperation`;Core 在后台调用,`ApplyLineEdit` 在文档版本变化后丢弃迟到结果。

完整文本同步调用的成本和局部范围方案跟踪 [#1805](https://github.com/1lck/Lithe-IDEA/issues/1805)。Core 规则未支持安全的有界输入前,不把完整文档调用直接放入 UI 线程,也不在 Go 复制无操作或行选择规则来规避约束。
整份文档复制的剩余成本跟踪 [#1805](https://github.com/1lck/Lithe-IDEA/issues/1805)。

## 考虑过的备选方案

- 各平台独立计算注释和行范围:会产生不同的空行、行尾和选区行为,故复用 Core。
- 整份文档同步调用 Core:小文件简单,但大文件的序列化和处理会阻塞输入;先处理性能与快捷键归属。
- 异步计算后无条件消费快捷键:无操作结果不能及时交给其他处理器,违反 Core 契约;需要先设计无损的接线方式。
- 各平台独立计算注释和行范围:空行、行尾和选区行为会分叉,故复用 Core。
- Core 保留注释符号表:与语言注册表是两份来源,插件新增语言时还要改 Core,违反 Core 零语言特判;已于 #1856 删除 `editor.lineCommentToken`。
- 整份文档同步调用 Core:大文件的序列化和处理会阻塞输入,改为局部窗口加后台调用。

## 后果

共享样例可验证桥接结果,但用户仍不能通过 Viva 执行这些命令。局部处理、界面接线、平台快捷键、组合输入、撤销与真实窗口性能验收均未完成。接口只处理内存快照,不创建资源或写入发行包。
新增语言只需在内置表或插件清单里声明注释,Core 和行操作代码不用改。`.json` 按内置语言表使用 `//`(与 VS Code 一致),不再提示没有行注释。接口只处理内存快照,不创建资源或写入发行包。

## 验证

- `scripts/desktop/desktop-go.sh test -race ./internal/core -run 'Test(LineEditsUseCoreFixtures|LineCommentTokenUsesCoreLanguageTable)' -count=3 -timeout=90s`:macOS 验证共享行变换 fixture、语言符号和未知语言。
- `scripts/desktop/desktop-go.sh test ./internal/editor/syntax -run '^TestCommentsForPath$' -count=1 -timeout=60s`:旧 Core 表覆盖的扩展名全部保留符号;插件声明覆盖、同 ID 继承、无语法插件语言回退、自带语法的插件语言不回退。
- `scripts/desktop/desktop-go.sh test ./internal/core -run '^TestLineEditsUseCoreFixtures$' -count=1 -timeout=90s`:共享行变换 fixture。
- `scripts/desktop/desktop-go.sh test ./internal/workbench -run '^Test(LineOperationKeys|LineOperationsThroughCore|EditorContextMenuRunsLineOperation)$' -count=1 -timeout=120s`:快捷键映射、经 Core 的注释切换与右键菜单。
- `scripts/desktop/desktop-go.sh test ./internal/core -run '^$' -bench '^BenchmarkCoreToggleLineComment$' -benchtime=3x -count=1 -timeout=90s`:Apple M4 上合成 100 KiB、1 MiB 和 8 MiB 文档的平均调用约为 5.37、31.2 和 248.6 ms;8 MiB 的 Go 分配约 29.5 MiB,不包含 Rust 分配或峰值。该单机基准不代表真实窗口或 Windows 性能。

## 适用范围

- `desktop/internal/core/line_edit.go`
- `desktop/internal/core/line_edit_test.go`
- `desktop/internal/editorview/lineedit.go`
- `desktop/internal/workbench/lineedit.go`
- `desktop/internal/workbench/editor_menu.go`
- `desktop/internal/editor/syntax/language.go`
- `desktop/internal/editor/syntax/languages.go`
- `https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/fixtures/editor/line-edit-v1.json`
- `shared/platform-feature-matrix/features/editor-line-operations.json`
- [固定 Core 的行变换实现](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/0ffd327b4329261e393b08ed76fbd134b4dd17e9/rust/lithe-core/src/editor/line_edit.rs)
12 changes: 0 additions & 12 deletions desktop/internal/core/line_edit.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,18 +35,6 @@ type LineEditOutcome struct {
SelectionLength int `json:"selectionLength"`
}

// LineCommentToken returns Core's language token or nil when none is known.
// The identifier may be a filename, extension or language ID.
func (c *Client) LineCommentToken(ctx context.Context, identifier string) (*string, error) {
var response struct {
Token *string `json:"token"`
}
err := c.Execute(ctx, "editor.lineCommentToken", struct {
Identifier string `json:"identifier"`
}{Identifier: identifier}, &response)
return response.Token, err
}

// LineEdit asks Core for a pure transformation. It does not write the file or
// change the live editor; the caller must check the captured document version
// and selection before applying the answer as one undoable edit.
Expand Down
31 changes: 0 additions & 31 deletions desktop/internal/core/line_edit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,25 +29,6 @@ func TestLineEditsUseCoreFixtures(t *testing.T) {
client := NewClient()
for _, item := range fixture.Cases {
t.Run(item.Name, func(t *testing.T) {
var kind struct {
Identifier *string `json:"identifier"`
}
if err := json.Unmarshal(item.Request, &kind); err != nil {
t.Fatal(err)
}
if kind.Identifier != nil {
var expected struct {
Token *string `json:"token"`
}
if err := json.Unmarshal(item.Expected, &expected); err != nil {
t.Fatal(err)
}
result, err := client.LineCommentToken(testContext(t), *kind.Identifier)
if err != nil || !reflect.DeepEqual(result, expected.Token) {
t.Fatalf("token = %v, error = %v; want %v", result, err, expected.Token)
}
return
}
var request LineEditRequest
var expected LineEditOutcome
if err := json.Unmarshal(item.Request, &request); err != nil {
Expand All @@ -64,18 +45,6 @@ func TestLineEditsUseCoreFixtures(t *testing.T) {
}
}

func TestLineCommentTokenUsesCoreLanguageTable(t *testing.T) {
client, ctx := NewClient(), testContext(t)
token, err := client.LineCommentToken(ctx, "example.go")
if err != nil || token == nil || *token != "//" {
t.Fatalf("Go token = %v, error = %v", token, err)
}
token, err = client.LineCommentToken(ctx, "unknown.fixture-extension")
if err != nil || token != nil {
t.Fatalf("unknown token = %v, error = %v", token, err)
}
}

func BenchmarkCoreToggleLineComment(b *testing.B) {
for _, size := range []struct {
name string
Expand Down
21 changes: 21 additions & 0 deletions desktop/internal/editor/syntax/language.go
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,27 @@ func (r *Registry) SyntaxForPath(path string) *Syntax {
return nil
}

// CommentsForPath returns the comment delimiters of a file by its name: those of the language
// ForPath gives the file, zero when no language takes it. The registry is the only source of
// comment delimiters; a plugin declares its language's through configuration.lineComment and
// blockComment.
//
// A plugin language that names files for its servers and debuggers and brings neither a
// grammar nor comments of its own keeps the comments of the bundled language its name
// selects, as SyntaxForPath keeps that language's colors.
func (r *Registry) CommentsForPath(path string) Comments {
language, ok := r.ForPath(path)
if !ok {
return Comments{}
}
if language.Comments == (Comments{}) && language.Scope == "" {
if bundled := bundledForName(fileName(path)); bundled != nil {
return bundled.Comments
}
}
return language.Comments
}

// fileName returns the lowercased last element of a path with "/" or "\" as separators.
func fileName(path string) string {
return strings.ToLower(path[strings.LastIndexAny(path, `/\`)+1:])
Expand Down
44 changes: 44 additions & 0 deletions desktop/internal/editor/syntax/language_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -394,3 +394,47 @@ func TestPluginLanguageWithoutGrammarKeepsBundledColors(t *testing.T) {
t.Fatalf("SyntaxForPath of an empty path = %v", s)
}
}

func TestCommentsForPath(t *testing.T) {
r := NewRegistry()
// Every file the line comment toggle took while Core kept its own table keeps its token.
for token, names := range map[string][]string{
"//": {"a.c", "a.h", "a.cpp", "a.cc", "a.cxx", "a.hpp", "a.hxx", "a.kt", "build.kts", "a.swift", "a.js",
"a.jsx", "a.mjs", "a.cjs", "a.ts", "a.tsx", "main.go", "lib.rs", "a.cs", "a.php", "a.dart", "a.scala",
"a.groovy", "a.m", "a.mm", "a.zig"},
"#": {"a.py", "a.rb", "a.sh", "a.bash", "a.zsh", "a.yml", "a.yaml", "Cargo.toml", "a.ini", "setup.cfg",
"nginx.conf", "app.properties", ".env", "prod.env", "a.r", "a.rmd", "a.pl", "a.ex"},
"--": {"a.sql", "a.lua", "Main.hs"},
} {
for _, name := range names {
if got := r.CommentsForPath("src/" + name).Line; got != token {
t.Errorf("CommentsForPath(%q).Line = %q, want %q", name, got, token)
}
}
}
// A language with block comments only, or a file no language takes, has no line token.
for _, path := range []string{"README.md", "site.css", "unknown.zzz", ""} {
if got := r.CommentsForPath(path).Line; got != "" {
t.Errorf("CommentsForPath(%q).Line = %q, want none", path, got)
}
}

own := strings.Replace(demoGrammar, "source.demo", "source.own", 1)
if failed, _ := r.SetPluginLanguages([]PluginLanguage{
// A plugin declares its language's comments.
{ID: "demo", Extensions: []string{"demo"}, Grammar: []byte(demoGrammar), Comments: Comments{Line: ";;"}},
// A plugin language for a bundled one inherits the comments it does not set.
{ID: "go", Extensions: []string{"go"}},
// A plugin language that only names files keeps the bundled language's comments.
{ID: "clangd", Extensions: []string{"c", "lua"}},
// A plugin language with a grammar of its own has only the comments it declares.
{ID: "own", Extensions: []string{"py"}, Grammar: []byte(own)},
}); len(failed) != 0 {
t.Fatalf("failed %v", failed)
}
for path, want := range map[string]string{"a.demo": ";;", "main.go": "//", "main.c": "//", "init.lua": "--", "a.py": ""} {
if got := r.CommentsForPath(path).Line; got != want {
t.Errorf("with plugins, CommentsForPath(%q).Line = %q, want %q", path, got, want)
}
}
}
9 changes: 7 additions & 2 deletions desktop/internal/editor/syntax/languages.go
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,7 @@ var bundledLanguages = []Language{
{ID: "shell", Extensions: []string{".sh", ".bash", ".zsh"},
FileNames: []string{".bashrc", ".zshrc", ".bash_profile", ".zprofile", ".profile"},
Comments: hashComments, Brackets: cBrackets, AutoClosing: cAutoClosing},
{ID: "dotenv", Scope: "source.dotenv", Rules: DotenvRules, FileNames: []string{".env"}, FilePrefixes: []string{".env."},
{ID: "dotenv", Scope: "source.dotenv", Rules: DotenvRules, Extensions: []string{".env"}, FileNames: []string{".env"}, FilePrefixes: []string{".env."},
Comments: hashComments, Brackets: cBrackets, AutoClosing: cAutoClosing},
{ID: "dockerfile", Extensions: []string{".dockerfile"}, FileNames: []string{"dockerfile", "containerfile"},
FilePrefixes: []string{"dockerfile.", "containerfile."},
Expand All @@ -316,11 +316,14 @@ var bundledLanguages = []Language{
{ID: "go", Scope: "source.go", Rules: CodeRules, Extensions: []string{".go"}, Comments: cComments, Brackets: cBrackets,
AutoClosing: scriptClosing},
{ID: "graphql", Extensions: []string{".graphql", ".gql"}, Comments: hashComments, Brackets: cBrackets, AutoClosing: cAutoClosing},
// ' is not paired: it marks primes in names, as foldl'.
{ID: "haskell", Extensions: []string{".hs"}, Comments: Comments{Line: "--", Block: Pair{"{-", "-}"}}, Brackets: cBrackets,
AutoClosing: []Pair{{"{", "}"}, {"[", "]"}, {"(", ")"}, {`"`, `"`}}},
{ID: "hcl", Extensions: []string{".tf", ".tfvars", ".hcl"},
Comments: Comments{Line: "#", Block: Pair{"/*", "*/"}}, Brackets: cBrackets, AutoClosing: cAutoClosing},
{ID: "html", Scope: "text.html.basic", Rules: HTMLRules, Extensions: []string{".html", ".htm", ".shtml", ".xhtml", ".mdoc", ".jsp", ".asp", ".aspx", ".jshtm"},
Comments: markupBlock, Brackets: markupBrackets, AutoClosing: markupClosing},
{ID: "ini", Scope: "source.ini", Rules: INIRules, Extensions: []string{".ini", ".properties", ".gitconfig"},
{ID: "ini", Scope: "source.ini", Rules: INIRules, Extensions: []string{".ini", ".properties", ".cfg", ".conf", ".gitconfig"},
FileNames: []string{".gitconfig", ".editorconfig"}, Comments: hashComments, Brackets: cBrackets, AutoClosing: cAutoClosing},
{ID: "javascript", Scope: "source.js", Rules: ScriptRules, Extensions: []string{".js", ".es6", ".mjs", ".cjs"},
FileNames: []string{"jakefile"}, Comments: cComments, Brackets: cBrackets, AutoClosing: scriptClosing},
Expand All @@ -339,6 +342,8 @@ var bundledLanguages = []Language{
{ID: "markdown", Scope: "text.html.markdown", Rules: MarkdownRules, Extensions: []string{".md", ".markdown", ".mdown", ".mkdn", ".mkd", ".mdwn", ".mdtxt", ".mdtext"},
Comments: markupBlock, Brackets: cBrackets, AutoClosing: []Pair{{"{", "}"}, {"[", "]"}, {"(", ")"}, {"<", ">"}}},
{ID: "objective-c", Extensions: []string{".m"}, Comments: cComments, Brackets: cBrackets, AutoClosing: cAutoClosing},
{ID: "objective-cpp", Extensions: []string{".mm"}, Comments: cComments, Brackets: cBrackets, AutoClosing: cAutoClosing},
{ID: "perl", Extensions: []string{".pl", ".pm"}, Comments: hashComments, Brackets: cBrackets, AutoClosing: cAutoClosing},
{ID: "php", Extensions: []string{".php", ".php4", ".php5", ".phtml", ".ctp"}, Comments: cComments, Brackets: cBrackets, AutoClosing: cAutoClosing},
{ID: "proto", Extensions: []string{".proto"}, Comments: cComments, Brackets: cBrackets, AutoClosing: cAutoClosing},
{ID: "python", Extensions: []string{".py", ".rpy", ".pyw", ".cpy", ".gyp", ".gypi"},
Expand Down
43 changes: 22 additions & 21 deletions desktop/internal/workbench/lineedit.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,19 @@ import (

// Line operations: toggle comment, delete, move and copy lines.
//
// Core owns every rule (what a comment is for a language, how a selection that ends at the
// start of a line is treated, CRLF, UTF-16 offsets). This file only takes the lines an
// operation can touch from the editor, asks Core off the window thread and puts the answer
// back as one undoable edit while the document is still at the revision the window was
// taken at. A no-op answer (moving the first line up) leaves the document alone.
// Core owns every rule of the edit (how a selection that ends at the start of a line is
// treated, CRLF, UTF-16 offsets) and knows no language: the comment token comes from the
// editor's language registry, where each bundled or plugin language declares its comments.
// This file only takes the lines an operation can touch from the editor, asks Core off the
// window thread and puts the answer back as one undoable edit while the document is still at
// the revision the window was taken at. A no-op answer (moving the first line up) leaves the
// document alone.

// editorKernel is what the editor features of this package need beyond the common Kernel. The
// application's kernel (core.Client) has all of it; keeping the list here keeps the editor
// features out of the shared interface.
type editorKernel interface {
LineEdit(context.Context, core.LineEditRequest) (core.LineEditOutcome, error)
LineCommentToken(context.Context, string) (*string, error)
DecodeFileBytes(context.Context, []byte, string) (core.DecodedFile, error)
EncodeFileText(context.Context, string, string, *bool) (core.EncodedText, error)
ReduceNavigationHistory(context.Context, core.NavigationHistory, core.NavigationHistoryEvent) (core.NavigationHistory, *core.NavigationLocation, error)
Expand Down Expand Up @@ -104,22 +105,22 @@ func (a *App) runLineOperation(p *project, d *document, op core.LineEditOperatio
return
}
a.performed("editor.lineEdit."+string(op), surfaceShortcut)
documentID, name := d.id, d.name
a.background(p, kernelCallTimeout, func(ctx context.Context) func(*App) {
request := core.LineEditRequest{
Operation: op, Source: in.Source,
SelectionStart: in.SelectionStart, SelectionLength: in.SelectionLength,
}
if op == core.ToggleLineComment {
token, err := kernel.LineCommentToken(ctx, name)
if err != nil {
return func(a *App) { a.lineEditFailed(err) }
}
if token == nil {
return func(a *App) { a.notifyInfo(i18n.Shared(a.language(), "desktop.editor.noLineComment")) }
}
request.CommentToken = token
request := core.LineEditRequest{
Operation: op, Source: in.Source,
SelectionStart: in.SelectionStart, SelectionLength: in.SelectionLength,
}
if op == core.ToggleLineComment {
// By the name, as the document's language was chosen when it opened: a plugin's content
// document has a URI for a path and its file name only in the name.
token := a.syntaxRegistry().CommentsForPath(d.name).Line
if token == "" {
a.notifyInfo(i18n.Shared(a.language(), "desktop.editor.noLineComment"))
return
}
request.CommentToken = &token
}
documentID := d.id
a.background(p, kernelCallTimeout, func(ctx context.Context) func(*App) {
outcome, err := kernel.LineEdit(ctx, request)
return func(a *App) {
if err != nil {
Expand Down
Loading
Loading