From 3630758b9a446ee36bd36fc5dd2acd3eb78928c3 Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Fri, 20 Nov 2026 07:46:05 +0800 Subject: [PATCH 1/5] feat(editor): use plugin first-line rules for extensionless documents --- ...2026-10-12-declarative-language-plugins.md | 7 ++ desktop/internal/editor/syntax/language.go | 21 +++++ desktop/internal/editorview/prepared_edit.go | 3 + desktop/internal/pluginhost/pluginhost.go | 2 + .../internal/pluginhost/pluginhost_test.go | 3 + desktop/internal/pluginservice/languages.go | 19 ++--- .../pluginservice/pluginservice_test.go | 5 +- desktop/internal/workbench/app.go | 3 + .../internal/workbench/document_language.go | 63 ++++++++++++++ .../workbench/document_language_test.go | 82 +++++++++++++++++++ desktop/internal/workbench/documents.go | 7 +- .../internal/workbench/documents_tabless.go | 12 +-- desktop/internal/workbench/lineedit.go | 12 ++- desktop/internal/workbench/plugins.go | 26 +++++- desktop/internal/workbench/source_preview.go | 11 ++- scripts/desktop/build-desktop-core.sh | 2 +- .../features/plugin-first-line-language.json | 29 +++++++ 17 files changed, 276 insertions(+), 31 deletions(-) create mode 100644 desktop/internal/workbench/document_language.go create mode 100644 desktop/internal/workbench/document_language_test.go create mode 100644 shared/platform-feature-matrix/features/plugin-first-line-language.json diff --git a/.agents/notes/implemented/architecture/2026-10-12-declarative-language-plugins.md b/.agents/notes/implemented/architecture/2026-10-12-declarative-language-plugins.md index 1b94b03f1d..7f333134d4 100644 --- a/.agents/notes/implemented/architecture/2026-10-12-declarative-language-plugins.md +++ b/.agents/notes/implemented/architecture/2026-10-12-declarative-language-plugins.md @@ -51,6 +51,12 @@ - 历史回放不保存来源语言,而是把文件当作它自己语言的源码重新校验。 - 外部文件始终只读,保存被拒绝。普通打开(项目树、搜索、外部 URL)仍然拒绝工作区外路径。 +### 6. 无后缀文件按首行识别 + +名称和扩展名先交给编辑器原有的路径关联。只有无后缀且未命中关联的文本文件才使用插件声明的首行规则。宿主在打开文档的后台任务中从已解码的缓冲区取完整首行,交给 Core 按启用插件的注册顺序匹配。启动时恢复的无后缀标签等待首份语言注册表,再决定语言。高亮、行注释和语言服务使用选中的语言。关闭后重新打开文件时重新识别。 + +例如,插件可以用一条首行规则覆盖用户环境里的解释器路径和常见的 `env` 写法。把解释器名称写进宿主,或执行首行来猜测文件类型,都会破坏插件声明与文件内容之间的边界。匹配只消耗有界文本,沿用打开文档已读取的内容,无需创建缓存文件。 + ### 正确与错误示例 正确:为新语言写 `plugin.json`,声明 `languageServers` 和执行提供者,在契约 fixture 中补一个命令展开样例,并在 Core 测试中验证。 @@ -77,6 +83,7 @@ - 桌面端:`scripts/desktop/desktop-go.sh test ./internal/pluginhost/... ./internal/pluginbackend/... ./internal/plugintrust/... ./internal/plugininstall/...` 覆盖包校验、信任策略、安装审查与进程清理。 - `scripts/desktop/verify/verify-runtime-bundle-immutability.sh` 检查插件安装不写入发行目录。 - 新增插件还要验证下载失败、签名失败、取消、等待重启、重装、回滚、禁用和卸载后的进程与文件清理。 +- 首行识别:`scripts/desktop/desktop-go.sh test ./internal/workbench -run TestOpenFileUsesPluginFirstLineLanguage`。 - `./scripts/agent-notes/verify-agent-notes.sh` ## 适用范围 diff --git a/desktop/internal/editor/syntax/language.go b/desktop/internal/editor/syntax/language.go index 730f9dd0d8..bf01398ebe 100644 --- a/desktop/internal/editor/syntax/language.go +++ b/desktop/internal/editor/syntax/language.go @@ -134,6 +134,8 @@ func (l *Language) rules() []Rule { // language its ID resolves to, if any, when they are set; the rest are inherited. type PluginLanguage struct { ID string + // FirstLineMatch is the plugin's Core-validated pattern for an unknown extensionless file. + FirstLineMatch string // Extensions are file name suffixes, with or without their dot, in any case. Extensions []string // FileNames are base names, in any case. @@ -186,6 +188,25 @@ type Registry struct { version uint64 } +// FirstLineCandidate is one enabled language's pattern, ready for the Core matcher. +type FirstLineCandidate struct { + LanguageID string `json:"languageID"` + FirstLineMatch string `json:"firstLineMatch"` +} + +// FirstLineCandidates returns candidates in the same registration order as ForPath. +func (r *Registry) FirstLineCandidates() []FirstLineCandidate { + r.mu.Lock() + defer r.mu.Unlock() + var candidates []FirstLineCandidate + for _, id := range r.pluginOrder { + if pattern := r.plugins[id].source.FirstLineMatch; pattern != "" { + candidates = append(candidates, FirstLineCandidate{LanguageID: id, FirstLineMatch: pattern}) + } + } + return candidates +} + type pluginEntry struct { source PluginLanguage language *Language diff --git a/desktop/internal/editorview/prepared_edit.go b/desktop/internal/editorview/prepared_edit.go index d75415584b..3f11f95b15 100644 --- a/desktop/internal/editorview/prepared_edit.go +++ b/desktop/internal/editorview/prepared_edit.go @@ -55,6 +55,9 @@ func PrepareEdits(before, saved rope.Rope, edits []TextEdit) (PreparedEdit, erro return prepared, nil } +// Snapshot returns the replacement text prepared on the worker. +func (p PreparedEdit) Snapshot() rope.Rope { return p.after } + // ApplyPreparedEdit keeps saved contents and undo history while replacing the native // buffer. A stale result, composing input or a read-only view changes nothing. func (v *View) ApplyPreparedEdit(prepared PreparedEdit) bool { diff --git a/desktop/internal/pluginhost/pluginhost.go b/desktop/internal/pluginhost/pluginhost.go index 7fa38f2f13..1aa05da795 100644 --- a/desktop/internal/pluginhost/pluginhost.go +++ b/desktop/internal/pluginhost/pluginhost.go @@ -194,6 +194,8 @@ func Declared() Capabilities { declared["sourceSettings"] = []int{0, 1} // Version 1 adds command-sourced discovery in the Build test tree. declared["buildSystems"] = []int{0, 1} + // Version 1 adds first-line patterns for extensionless editor documents. + declared["languages"] = []int{0, 1} // Version 1 adds entrypoint runs, which Run on Current File starts. declared["buildProviders"] = []int{0, 1} // Version 1 adds a definition's category and audience, by which the diff --git a/desktop/internal/pluginhost/pluginhost_test.go b/desktop/internal/pluginhost/pluginhost_test.go index 362a6d34b5..4d2ba7cb81 100644 --- a/desktop/internal/pluginhost/pluginhost_test.go +++ b/desktop/internal/pluginhost/pluginhost_test.go @@ -91,6 +91,9 @@ func TestDeclaredServesTheBaselineOfEveryWiredCapability(t *testing.T) { if name == "managedRuntimes" { wanted = []int{0, 1} } + if name == "languages" { + wanted = []int{0, 1} + } if versions := declared[name]; !slices.Equal(versions, wanted) { t.Fatalf("%s = %v, want %v", name, versions, wanted) } diff --git a/desktop/internal/pluginservice/languages.go b/desktop/internal/pluginservice/languages.go index 0eb9f58814..6f62fcafb1 100644 --- a/desktop/internal/pluginservice/languages.go +++ b/desktop/internal/pluginservice/languages.go @@ -69,6 +69,7 @@ type languageDeclaration struct { ID string `json:"id"` FileExtensions []string `json:"fileExtensions"` FileNames []string `json:"fileNames"` + FirstLineMatch string `json:"firstLineMatch"` Grammar *struct { Kind string `json:"kind"` Path string `json:"path"` @@ -99,9 +100,10 @@ func (s *Service) pluginLanguages(ctx context.Context, directory string) ([]synt continue } language := syntax.PluginLanguage{ - ID: item.ID, - Extensions: item.FileExtensions, - FileNames: item.FileNames, + ID: item.ID, + Extensions: item.FileExtensions, + FileNames: item.FileNames, + FirstLineMatch: item.FirstLineMatch, } if item.Grammar != nil { // The contract has a language whose grammar is refused open as plain text @@ -123,13 +125,10 @@ func (s *Service) pluginLanguages(ctx context.Context, directory string) ([]synt language.Brackets = delimiterPairs(configuration.Brackets) language.AutoClosing = delimiterPairs(configuration.AutoClosingPairs) } - if len(language.Extensions) == 0 && len(language.FileNames) == 0 { - // The editor matches a language by extension or base name only. A - // declaration that names nothing but projectFileNames is a project - // signal, which this client does not use to choose a language, so the - // language would be invisible. Reporting it is better than registering a - // language that can never match. - failures = append(failures, fmt.Errorf("%s: declares no file extensions or file names", item.ID)) + if len(language.Extensions) == 0 && len(language.FileNames) == 0 && language.FirstLineMatch == "" { + // Project file names alone describe a project signal, so this language + // cannot match any document. + failures = append(failures, fmt.Errorf("%s: declares no file extensions, file names or first-line pattern", item.ID)) continue } languages = append(languages, language) diff --git a/desktop/internal/pluginservice/pluginservice_test.go b/desktop/internal/pluginservice/pluginservice_test.go index d3b10fe849..81048c73e0 100644 --- a/desktop/internal/pluginservice/pluginservice_test.go +++ b/desktop/internal/pluginservice/pluginservice_test.go @@ -6,6 +6,7 @@ import ( "errors" "os" "path/filepath" + "slices" "testing" "github.com/1lck/Lithe-IDEA/desktop/internal/core" @@ -150,7 +151,7 @@ func TestOpenAssemblesEveryPart(t *testing.T) { if service.Root == "" { t.Fatal("the service has no root") } - if versions := service.Capabilities()["languages"]; len(versions) != 1 || versions[0] != 0 { + if versions := service.Capabilities()["languages"]; !slices.Equal(versions, []int{0, 1}) { t.Fatalf("capabilities = %v", service.Capabilities()) } } @@ -205,7 +206,7 @@ func TestReviewerAdaptsCoreReview(t *testing.T) { } // The capabilities handed to Core must be the ones this client implements, not // what Core could parse. - if caps := kernel.reviewCaps["languages"]; len(caps) != 1 || caps[0] != 0 { + if caps := kernel.reviewCaps["languages"]; !slices.Equal(caps, []int{0, 1}) { t.Fatalf("capabilities = %v", kernel.reviewCaps) } } diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 43da31d25d..c12214a14d 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -608,6 +608,9 @@ type App struct { tasks taskQueue // languages are the languages the editor knows, made when the first file is opened. languages *syntax.Registry + // initialLanguageLoad lets early opens of extensionless files wait for the enabled + // language snapshot, even when the project restores its tabs during app startup. + initialLanguageLoad atomic.Pointer[languageLoad] settings settings // fonts is the font of each scope the settings name, worked out by applyFonts. diff --git a/desktop/internal/workbench/document_language.go b/desktop/internal/workbench/document_language.go new file mode 100644 index 0000000000..eb0c21f4fa --- /dev/null +++ b/desktop/internal/workbench/document_language.go @@ -0,0 +1,63 @@ +package workbench + +import ( + "context" + "path/filepath" + "slices" + "strings" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/editor/rope" + "github.com/1lck/Lithe-IDEA/desktop/internal/editor/syntax" +) + +type languageLoad struct { + done chan struct{} +} + +// resolveDocumentLanguage runs on the worker that opens editable text. Path +// matches keep priority. Core receives only the bounded, decoded first line. +func (a *App) resolveDocumentLanguage(ctx context.Context, registry *syntax.Registry, path string, text rope.Rope) (string, *syntax.Syntax) { + hasExtension := filepath.Ext(path) != "" + if initial := a.initialLanguageLoad.Load(); initial != nil && !hasExtension { + select { + case <-initial.done: + case <-ctx.Done(): + return "", nil + } + } + if language, ok := registry.ForPath(path); ok { + return language.ID, registry.SyntaxForPath(path) + } + if hasExtension { + return "", nil + } + const maxFirstLineBytes = 1024 + end := text.LineEnd(0) + if end == 0 || end > maxFirstLineBytes+1 { + return "", nil + } + line := strings.TrimSuffix(text.Line(0), "\r") + if len(line) == 0 || len(line) > maxFirstLineBytes { + return "", nil + } + const maxCandidates = 64 + kernel := core.NewClient() + for batch := range slices.Chunk(registry.FirstLineCandidates(), maxCandidates) { + var match struct { + LanguageID string `json:"languageID"` + } + err := kernel.Execute(ctx, "languages.matchFirstLine", struct { + FirstLine string `json:"firstLine"` + Candidates []syntax.FirstLineCandidate `json:"candidates"` + }{line, batch}, &match) + if err != nil { + a.backgroundFailedIn(ctx, "plugin_languages", err) + return "", nil + } + if match.LanguageID != "" { + return match.LanguageID, registry.Syntax(match.LanguageID) + } + } + return "", nil +} diff --git a/desktop/internal/workbench/document_language_test.go b/desktop/internal/workbench/document_language_test.go new file mode 100644 index 0000000000..dcbbba538c --- /dev/null +++ b/desktop/internal/workbench/document_language_test.go @@ -0,0 +1,82 @@ +package workbench + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginstate" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" +) + +func TestOpenFileUsesPluginFirstLineLanguage(t *testing.T) { + kernel := core.NewClient() + manifest, err := os.ReadFile(contractfixture.Path("fixtures/languages/first-line.plugin.json")) + if err != nil { + t.Fatal(err) + } + if _, err := pluginhost.Validate(t.Context(), kernel, manifest, pluginhost.Declared()); err != nil { + t.Fatal(err) + } + const id = "dev.lithe.test.first-line" + pluginRoot := t.TempDir() + installed := filepath.Join(pluginRoot, id, "1.0.0") + if err := os.MkdirAll(installed, 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(installed, "plugin.json"), manifest, 0o600); err != nil { + t.Fatal(err) + } + settings := store.At(t.TempDir()) + if err := os.WriteFile(filepath.Join(settings.Dir(), settingsFile), []byte(`{"theme":"dark"}`), 0o600); err != nil { + t.Fatal(err) + } + if err := pluginstate.New(settings).SetEnabled(id, true); err != nil { + t.Fatal(err) + } + h := newHarnessWithOptions(t, Options{Kernel: kernel, PluginKernel: kernel, Store: settings, PluginRoot: pluginRoot}) + root := t.TempDir() + h.open(root) + h.app.reloadPluginLanguages() + p := h.app.project + start := "#!/usr/bin/env -S sample3" + for _, tc := range []struct{ name, text, want string }{ + {"script", start + " -f\r\nvalue\r\n", "sample"}, + {"no-newline", start, "sample"}, + {"later-line", "\n" + start, ""}, + {"long-header", start + " " + strings.Repeat("x", 1024) + "\n", ""}, + {"main.go", start, "go"}, + {"Makefile", start, "makefile"}, + {"unmapped.ext", start, ""}, + {"script.sh", start, "shell"}, + } { + t.Run(tc.name, func(t *testing.T) { + path := filepath.Join(root, tc.name) + if err := os.WriteFile(path, []byte(tc.text), 0o600); err != nil { + t.Fatal(err) + } + h.app.openFile(p, path) + h.settle() + doc := p.docs.byPath(path) + if doc == nil { + t.Fatal("document did not open") + } + if doc.languageID != tc.want { + t.Fatalf("language = %q, want %q", doc.languageID, tc.want) + } + if tc.name == "script" { + doc.view.GoToLine(2) + h.app.runLineOperation(p, doc, core.ToggleLineComment) + h.settle() + text := doc.view.TextSnapshot().String() + if !strings.Contains(text, "// value") { + t.Fatalf("edit did not use the resolved language's line comment: %q", text) + } + } + }) + } +} diff --git a/desktop/internal/workbench/documents.go b/desktop/internal/workbench/documents.go index 4ba2bab3e0..d6cb121192 100644 --- a/desktop/internal/workbench/documents.go +++ b/desktop/internal/workbench/documents.go @@ -308,10 +308,11 @@ func (a *App) openFile(p *project, path string) { } else { content = editorview.Prepare(data) } - grammar = registry.SyntaxForPath(path) - if language, ok := registry.ForPath(path); ok { - languageID = language.ID + snapshot := content.Snapshot() + if restored.found { + snapshot = restored.prepared.Snapshot() } + languageID, grammar = a.resolveDocumentLanguage(ctx, registry, path, snapshot) } return func(a *App) { delete(p.docs.opening, path) diff --git a/desktop/internal/workbench/documents_tabless.go b/desktop/internal/workbench/documents_tabless.go index 26b93af5dc..b88027f448 100644 --- a/desktop/internal/workbench/documents_tabless.go +++ b/desktop/internal/workbench/documents_tabless.go @@ -42,7 +42,7 @@ func (a *App) openTablessDocument(p *project, path string) { registry := a.syntaxRegistry() kernel, _ := a.kernel.(editorKernel) a.background(p, 0, func(ctx context.Context) func(*App) { - file := readTablessFile(ctx, kernel, registry, path) + file := a.readTablessFile(ctx, kernel, registry, path) return func(a *App) { delete(p.docs.opening, path) // A file that is not text, or that cannot be read, has no document; its Diff stays read only. @@ -64,17 +64,14 @@ type tablessFile struct { } // readTablessFile reads path and prepares its text and grammar; it runs on a worker. -func readTablessFile(ctx context.Context, kernel editorKernel, registry *syntax.Registry, path string) tablessFile { +func (a *App) readTablessFile(ctx context.Context, kernel editorKernel, registry *syntax.Registry, path string) tablessFile { read, err := readDocumentEncoded(ctx, kernel, path) file := tablessFile{read: read, err: err} if err != nil { return file } file.content = editorview.Prepare(read.text) - file.grammar = registry.SyntaxForPath(path) - if language, ok := registry.ForPath(path); ok { - file.languageID = language.ID - } + file.languageID, file.grammar = a.resolveDocumentLanguage(ctx, registry, path, file.content.Snapshot()) return file } @@ -129,6 +126,9 @@ func (a *App) attachDocumentTab(p *project, d *document) bool { a.refreshInlineBlame(p, d) a.watchDocument(p, d) a.startDocumentSync(p, d) + if d.languageID != "" { + a.startPluginServer(d.languageID) + } a.scheduleEditorActions(p, d) a.enforceTabLimit(p, d) return true diff --git a/desktop/internal/workbench/lineedit.go b/desktop/internal/workbench/lineedit.go index 28cd9a19d1..25cc870534 100644 --- a/desktop/internal/workbench/lineedit.go +++ b/desktop/internal/workbench/lineedit.go @@ -114,9 +114,15 @@ func (a *App) runLineOperation(p *project, d *document, op core.LineEditOperatio 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 + // Use the resolved document language for an extensionless file. Path lookup + // also preserves the bundled fallback and handles plugin virtual documents. + registry := a.syntaxRegistry() + token := registry.CommentsForPath(d.name).Line + if token == "" && d.languageID != "" { + if language, ok := registry.Language(d.languageID); ok { + token = language.Comments.Line + } + } if token == "" { a.notifyInfo(i18n.Shared(a.language(), "desktop.editor.noLineComment")) return diff --git a/desktop/internal/workbench/plugins.go b/desktop/internal/workbench/plugins.go index bac70f20b0..6114ad2e57 100644 --- a/desktop/internal/workbench/plugins.go +++ b/desktop/internal/workbench/plugins.go @@ -344,14 +344,31 @@ func (a *App) reloadPluginLanguages() { if a.plugins == nil { return } + registry := a.syntaxRegistry() + var initial *languageLoad + if a.initialLanguageLoad.Load() == nil { + initial = &languageLoad{done: make(chan struct{})} + a.initialLanguageLoad.Store(initial) + } a.background(nil, pluginStateTimeout, func(ctx context.Context) func(*App) { entries, err := a.plugins.Manager.Installed() if err != nil { + if initial != nil { + close(initial.done) + } return func(a *App) { a.backgroundFailed("plugin_languages", err) } } languages, loadErr := a.plugins.LoadLanguages(ctx, entries) + failedCount := 0 + if initial != nil { + // Publish the first language snapshot on the worker before allowing restored + // documents to resolve. They need no tool window or visibility results. + failed, _ := registry.SetPluginLanguages(languages) + failedCount = len(failed) + close(initial.done) + } windows, windowsErr := a.plugins.ToolWindows(ctx, entries) commands, commandsErr := a.plugins.ToolCommands(ctx, entries) vcsPlugins, vcsErr := a.plugins.VcsPlugins(ctx, entries) @@ -379,9 +396,12 @@ func (a *App) reloadPluginLanguages() { a.backgroundFailed("plugin_vcs_providers", vcsErr) } a.setPluginTools(windows, vcsWindows(vcsPlugins)) - failed, _ := a.syntaxRegistry().SetPluginLanguages(languages) - if len(failed) > 0 { - a.backgroundFailed("plugin_languages", fmt.Errorf("%d plugin languages were rejected", len(failed))) + if initial == nil { + failed, _ := registry.SetPluginLanguages(languages) + failedCount = len(failed) + } + if failedCount > 0 { + a.backgroundFailed("plugin_languages", fmt.Errorf("%d plugin languages were rejected", failedCount)) } } }) diff --git a/desktop/internal/workbench/source_preview.go b/desktop/internal/workbench/source_preview.go index 7c1ab7cf20..57eb4746ce 100644 --- a/desktop/internal/workbench/source_preview.go +++ b/desktop/internal/workbench/source_preview.go @@ -193,7 +193,7 @@ func (a *App) showSourcePreview(p *project, sp *sourcePreview, path string, line var grammar *syntax.Syntax if err == nil { content = editorview.Prepare(data) - grammar = registry.SyntaxForPath(path) + _, grammar = a.resolveDocumentLanguage(ctx, registry, path, content.Snapshot()) } return func(a *App) { if sp.generation != generation || a.project != p || !alive(a) { @@ -222,7 +222,7 @@ func (a *App) showEditablePreview(p *project, sp *sourcePreview, path string, li registry := a.syntaxRegistry() kernel, _ := a.kernel.(editorKernel) a.background(p, 0, func(ctx context.Context) func(*App) { - file := readTablessFile(ctx, kernel, registry, path) + file := a.readTablessFile(ctx, kernel, registry, path) return func(a *App) { if sp.generation != generation || a.project != p || !alive(a) { return @@ -244,11 +244,16 @@ func (a *App) showEditablePreview(p *project, sp *sourcePreview, path string, li // bindSourcePreview makes the editable view of document d, which shares the document's text, // and reveals the line. func (a *App) bindSourcePreview(p *project, sp *sourcePreview, d *document) { + registry := a.syntaxRegistry() + grammar := registry.SyntaxForPath(d.path) + if grammar == nil && d.languageID != "" { + grammar = registry.Syntax(d.languageID) + } var view *editorview.View view = editorview.New(editorview.Config{ Label: d.name, Content: d.view.CopyContent(), - Syntax: a.syntaxRegistry().SyntaxForPath(d.path), + Syntax: grammar, Notify: a.invalidator.Invalidate, Save: func() { a.saveDocument(p, d.id) }, OnEdit: func(edit editorview.Edit) { a.previewEdited(p, sp, view, edit) }, diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index aac25baae8..2cedbc4b10 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -286,7 +286,7 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # rows), #13, #8, #7, #6 and #4. # Search pages, unsaved snapshots, source identities and budgets from Core #125, # merged on top of the build-option changes through Core #124. -PINNED_CORE_REVISION="9399f16312df63efdf6f56aaeea5024df82cbe04" +PINNED_CORE_REVISION="871f12a176303039dc655688af9d269091ff20df" PROFILE="debug" while [[ $# -gt 0 ]]; do case "$1" in diff --git a/shared/platform-feature-matrix/features/plugin-first-line-language.json b/shared/platform-feature-matrix/features/plugin-first-line-language.json new file mode 100644 index 0000000000..b00738019b --- /dev/null +++ b/shared/platform-feature-matrix/features/plugin-first-line-language.json @@ -0,0 +1,29 @@ +{ + "id": "plugin-first-line-language", + "area": "扩展", + "group": "插件与主题", + "capability": "安装并启用声明首行规则的语言插件后,可按无后缀脚本的首行选择语法和语言服务,并使用该语言的编辑配置", + "macos": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/pluginservice/languages.go", + "desktop/internal/editor/syntax/language.go", + "desktop/internal/workbench/document_language.go", + "desktop/internal/workbench/document_language_test.go" + ] + }, + "windows": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/pluginservice/languages.go", + "desktop/internal/editor/syntax/language.go", + "desktop/internal/workbench/document_language.go", + "desktop/internal/workbench/document_language_test.go" + ] + }, + "owner": "Extensions", + "verification": "运行 scripts/desktop/desktop-go.sh test ./internal/workbench -run TestOpenFileUsesPluginFirstLineLanguage,确认无后缀文件按首行选择语言,能按该语言切换注释,现有名称与扩展关联优先,带未关联扩展名和超长首行的文件保留原行为。原生窗口另行验收。", + "notes": "仅传入已有文本缓冲区的完整且有界的首行。Core 按启用插件的语言注册顺序匹配。识别结果用于此次文档打开和随后编辑。" +} From 79b97fa6428df3c28d2c338c56cfdf4153c14008 Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Fri, 20 Nov 2026 09:03:27 +0800 Subject: [PATCH 2/5] fix(editor): read first-line hints from existing grammar resources --- ...2026-10-12-declarative-language-plugins.md | 4 ++-- desktop/internal/core/plugin_session.go | 2 ++ desktop/internal/pluginhost/pluginhost.go | 2 -- .../internal/pluginhost/pluginhost_test.go | 3 --- desktop/internal/pluginservice/languages.go | 21 ++++++++----------- .../pluginservice/pluginservice_test.go | 5 ++--- .../workbench/document_language_test.go | 17 ++++++++++++--- docs/development/macos-plugin-api-plan.md | 1 + scripts/desktop/build-desktop-core.sh | 2 +- .../features/plugin-first-line-language.json | 4 ++-- 10 files changed, 33 insertions(+), 28 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-10-12-declarative-language-plugins.md b/.agents/notes/implemented/architecture/2026-10-12-declarative-language-plugins.md index 7f333134d4..034931e180 100644 --- a/.agents/notes/implemented/architecture/2026-10-12-declarative-language-plugins.md +++ b/.agents/notes/implemented/architecture/2026-10-12-declarative-language-plugins.md @@ -53,9 +53,9 @@ ### 6. 无后缀文件按首行识别 -名称和扩展名先交给编辑器原有的路径关联。只有无后缀且未命中关联的文本文件才使用插件声明的首行规则。宿主在打开文档的后台任务中从已解码的缓冲区取完整首行,交给 Core 按启用插件的注册顺序匹配。启动时恢复的无后缀标签等待首份语言注册表,再决定语言。高亮、行注释和语言服务使用选中的语言。关闭后重新打开文件时重新识别。 +名称和扩展名先交给编辑器原有的路径关联。只有无后缀且未命中关联的文本文件才使用已安装 TextMate 语法文件中的首行规则。Core 验证语法时一并提取规则。宿主在打开文档的后台任务中从已解码的缓冲区取完整首行,交给 Core 按启用插件的注册顺序匹配。启动时恢复的无后缀标签等待首份语言注册表,再决定语言。高亮、行注释和语言服务使用选中的语言。关闭后重新打开文件时重新识别。 -例如,插件可以用一条首行规则覆盖用户环境里的解释器路径和常见的 `env` 写法。把解释器名称写进宿主,或执行首行来猜测文件类型,都会破坏插件声明与文件内容之间的边界。匹配只消耗有界文本,沿用打开文档已读取的内容,无需创建缓存文件。 +例如,插件可以用一条首行规则覆盖用户环境里的解释器路径和常见的 `env` 写法。把解释器名称写进宿主,或执行首行来猜测文件类型,都会破坏插件声明与文件内容之间的边界。匹配只消耗有界文本,沿用打开文档已读取的内容。规则是可选的语法元数据,旧版桌面会忽略该元数据,继续安装插件并使用语法文件的高亮规则。规则在启动语言服务器之前已可用。 ### 正确与错误示例 diff --git a/desktop/internal/core/plugin_session.go b/desktop/internal/core/plugin_session.go index c33ced10fe..c24398937a 100644 --- a/desktop/internal/core/plugin_session.go +++ b/desktop/internal/core/plugin_session.go @@ -183,6 +183,8 @@ type PluginGrammar struct { Kind string `json:"kind"` ScopeName string `json:"scopeName"` Source string `json:"source"` + // FirstLineMatch is the optional language detection hint accepted by Core. + FirstLineMatch string `json:"firstLineMatch,omitempty"` } // DecodePluginGrammar asks Core to validate static editor resources. The diff --git a/desktop/internal/pluginhost/pluginhost.go b/desktop/internal/pluginhost/pluginhost.go index 1aa05da795..7fa38f2f13 100644 --- a/desktop/internal/pluginhost/pluginhost.go +++ b/desktop/internal/pluginhost/pluginhost.go @@ -194,8 +194,6 @@ func Declared() Capabilities { declared["sourceSettings"] = []int{0, 1} // Version 1 adds command-sourced discovery in the Build test tree. declared["buildSystems"] = []int{0, 1} - // Version 1 adds first-line patterns for extensionless editor documents. - declared["languages"] = []int{0, 1} // Version 1 adds entrypoint runs, which Run on Current File starts. declared["buildProviders"] = []int{0, 1} // Version 1 adds a definition's category and audience, by which the diff --git a/desktop/internal/pluginhost/pluginhost_test.go b/desktop/internal/pluginhost/pluginhost_test.go index 4d2ba7cb81..362a6d34b5 100644 --- a/desktop/internal/pluginhost/pluginhost_test.go +++ b/desktop/internal/pluginhost/pluginhost_test.go @@ -91,9 +91,6 @@ func TestDeclaredServesTheBaselineOfEveryWiredCapability(t *testing.T) { if name == "managedRuntimes" { wanted = []int{0, 1} } - if name == "languages" { - wanted = []int{0, 1} - } if versions := declared[name]; !slices.Equal(versions, wanted) { t.Fatalf("%s = %v, want %v", name, versions, wanted) } diff --git a/desktop/internal/pluginservice/languages.go b/desktop/internal/pluginservice/languages.go index 6f62fcafb1..5b295af9e2 100644 --- a/desktop/internal/pluginservice/languages.go +++ b/desktop/internal/pluginservice/languages.go @@ -9,6 +9,7 @@ import ( "os" "path/filepath" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/editor/syntax" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginmanager" @@ -69,7 +70,6 @@ type languageDeclaration struct { ID string `json:"id"` FileExtensions []string `json:"fileExtensions"` FileNames []string `json:"fileNames"` - FirstLineMatch string `json:"firstLineMatch"` Grammar *struct { Kind string `json:"kind"` Path string `json:"path"` @@ -100,10 +100,9 @@ func (s *Service) pluginLanguages(ctx context.Context, directory string) ([]synt continue } language := syntax.PluginLanguage{ - ID: item.ID, - Extensions: item.FileExtensions, - FileNames: item.FileNames, - FirstLineMatch: item.FirstLineMatch, + ID: item.ID, + Extensions: item.FileExtensions, + FileNames: item.FileNames, } if item.Grammar != nil { // The contract has a language whose grammar is refused open as plain text @@ -111,8 +110,9 @@ func (s *Service) pluginLanguages(ctx context.Context, directory string) ([]synt // language its highlighting and nothing else. if grammar, err := s.grammar(ctx, directory, manifest, item.ID, item.Grammar.Path); err != nil { failures = append(failures, fmt.Errorf("%s: %w", item.ID, err)) - } else { - language.Grammar = grammar + } else if grammar != nil { + language.Grammar = []byte(grammar.Source) + language.FirstLineMatch = grammar.FirstLineMatch } } if configuration := item.Configuration; configuration != nil { @@ -137,7 +137,7 @@ func (s *Service) pluginLanguages(ctx context.Context, directory string) ([]synt } // grammar reads one grammar file from the package and has Core validate it. -func (s *Service) grammar(ctx context.Context, directory string, manifest json.RawMessage, languageID, name string) ([]byte, error) { +func (s *Service) grammar(ctx context.Context, directory string, manifest json.RawMessage, languageID, name string) (*core.PluginGrammar, error) { path, err := pluginhost.ResolvePackagePath(directory, name) if err != nil { return nil, err @@ -150,10 +150,7 @@ func (s *Service) grammar(ctx context.Context, directory string, manifest json.R if err != nil { return nil, err } - if decoded.Grammar == nil { - return nil, nil - } - return []byte(decoded.Grammar.Source), nil + return decoded.Grammar, nil } // delimiterPair converts one two-element delimiter declaration. diff --git a/desktop/internal/pluginservice/pluginservice_test.go b/desktop/internal/pluginservice/pluginservice_test.go index 81048c73e0..d3b10fe849 100644 --- a/desktop/internal/pluginservice/pluginservice_test.go +++ b/desktop/internal/pluginservice/pluginservice_test.go @@ -6,7 +6,6 @@ import ( "errors" "os" "path/filepath" - "slices" "testing" "github.com/1lck/Lithe-IDEA/desktop/internal/core" @@ -151,7 +150,7 @@ func TestOpenAssemblesEveryPart(t *testing.T) { if service.Root == "" { t.Fatal("the service has no root") } - if versions := service.Capabilities()["languages"]; !slices.Equal(versions, []int{0, 1}) { + if versions := service.Capabilities()["languages"]; len(versions) != 1 || versions[0] != 0 { t.Fatalf("capabilities = %v", service.Capabilities()) } } @@ -206,7 +205,7 @@ func TestReviewerAdaptsCoreReview(t *testing.T) { } // The capabilities handed to Core must be the ones this client implements, not // what Core could parse. - if caps := kernel.reviewCaps["languages"]; !slices.Equal(caps, []int{0, 1}) { + if caps := kernel.reviewCaps["languages"]; len(caps) != 1 || caps[0] != 0 { t.Fatalf("capabilities = %v", kernel.reviewCaps) } } diff --git a/desktop/internal/workbench/document_language_test.go b/desktop/internal/workbench/document_language_test.go index dcbbba538c..9ac35e421b 100644 --- a/desktop/internal/workbench/document_language_test.go +++ b/desktop/internal/workbench/document_language_test.go @@ -23,13 +23,23 @@ func TestOpenFileUsesPluginFirstLineLanguage(t *testing.T) { t.Fatal(err) } const id = "dev.lithe.test.first-line" + const grammarPath = "grammars/sample.tmLanguage.json" + grammar, err := os.ReadFile(contractfixture.Path("fixtures/languages/" + grammarPath)) + if err != nil { + t.Fatal(err) + } pluginRoot := t.TempDir() installed := filepath.Join(pluginRoot, id, "1.0.0") - if err := os.MkdirAll(installed, 0o700); err != nil { + if err := os.MkdirAll(filepath.Join(installed, "grammars"), 0o700); err != nil { t.Fatal(err) } - if err := os.WriteFile(filepath.Join(installed, "plugin.json"), manifest, 0o600); err != nil { - t.Fatal(err) + for path, contents := range map[string][]byte{ + "plugin.json": manifest, + grammarPath: grammar, + } { + if err := os.WriteFile(filepath.Join(installed, path), contents, 0o600); err != nil { + t.Fatal(err) + } } settings := store.At(t.TempDir()) if err := os.WriteFile(filepath.Join(settings.Dir(), settingsFile), []byte(`{"theme":"dark"}`), 0o600); err != nil { @@ -49,6 +59,7 @@ func TestOpenFileUsesPluginFirstLineLanguage(t *testing.T) { {"no-newline", start, "sample"}, {"later-line", "\n" + start, ""}, {"long-header", start + " " + strings.Repeat("x", 1024) + "\n", ""}, + {"typed.sample", "value", "sample"}, {"main.go", start, "go"}, {"Makefile", start, "makefile"}, {"unmapped.ext", start, ""}, diff --git a/docs/development/macos-plugin-api-plan.md b/docs/development/macos-plugin-api-plan.md index b9694aebf1..b47ba84769 100644 --- a/docs/development/macos-plugin-api-plan.md +++ b/docs/development/macos-plugin-api-plan.md @@ -77,6 +77,7 @@ Windows 不在本轮,平台矩阵的 partial/pending 保持真实。 | 新增文本格式或高亮规则 | 通过插件清单 `languages[]` 声明文件类型,`grammar.path` 引用包内 JSON 语法;宿主校验后由 worker 执行,不需要 LSP 或后端 | | 注释、括号、自动配对 | 可仅贡献 `configuration`,不要求同时提供 grammar | | 安装、更新、停用或卸载纯静态贡献 | 随已验证插件包的生命周期更新编辑器;这不等于插件可以调用动态 Provider 注册方法,也不授权修改已安装包或监听任意 JSON 文件自动重载 | +| 识别无后缀文本文件 | Viva 可通过已安装的 TextMate 语法文件提供首行规则。走现有的静态语言贡献入口,见 [Core 语法与编辑配置](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/shared/plugins/contract/v1/README.md#grammars-and-editor-configuration)。 | | 运行中直接提交 JSON,注册、替换或释放高亮 Provider | 尚未开放公共方法;当前不是接收任意内联 grammar 的注册入口。`semanticTokens` Provider 提供的是按文档请求的语义着色,只在语言服务器没有语义着色的位置生效,不替代 grammar | | 将补全、悬浮、定义、CodeLens、折叠、语义着色或文档链接绑定到普通插件函数 | 已开放:`lithe/host/editor/registerProviders`,需要 `editor.providers` 权限;每次最多 32 个注册,答案形状与预算由 Core 规定,宿主只能补充语言服务器的答案(见 Agent Note) | | 符号、格式化、重命名、Code Action、签名帮助、内联提示、诊断 | 尚未开放;`registerProviders` 对这些类型返回 `plugin.host.unsupportedOption`(`details.option` 为 `providers.<类型>`),诊断属于 API-26 | diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index 2cedbc4b10..9662e8a68f 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -286,7 +286,7 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # rows), #13, #8, #7, #6 and #4. # Search pages, unsaved snapshots, source identities and budgets from Core #125, # merged on top of the build-option changes through Core #124. -PINNED_CORE_REVISION="871f12a176303039dc655688af9d269091ff20df" +PINNED_CORE_REVISION="4d45d668223c30e818f67270fb06efd08aef95be" PROFILE="debug" while [[ $# -gt 0 ]]; do case "$1" in diff --git a/shared/platform-feature-matrix/features/plugin-first-line-language.json b/shared/platform-feature-matrix/features/plugin-first-line-language.json index b00738019b..f36ac8651e 100644 --- a/shared/platform-feature-matrix/features/plugin-first-line-language.json +++ b/shared/platform-feature-matrix/features/plugin-first-line-language.json @@ -2,7 +2,7 @@ "id": "plugin-first-line-language", "area": "扩展", "group": "插件与主题", - "capability": "安装并启用声明首行规则的语言插件后,可按无后缀脚本的首行选择语法和语言服务,并使用该语言的编辑配置", + "capability": "安装并启用在 TextMate 语法文件中提供首行规则的语言插件后,可按无后缀脚本的首行选择语法和语言服务,并使用该语言的编辑配置", "macos": { "implementationStatus": "implemented", "verificationStatus": "pending", @@ -25,5 +25,5 @@ }, "owner": "Extensions", "verification": "运行 scripts/desktop/desktop-go.sh test ./internal/workbench -run TestOpenFileUsesPluginFirstLineLanguage,确认无后缀文件按首行选择语言,能按该语言切换注释,现有名称与扩展关联优先,带未关联扩展名和超长首行的文件保留原行为。原生窗口另行验收。", - "notes": "仅传入已有文本缓冲区的完整且有界的首行。Core 按启用插件的语言注册顺序匹配。识别结果用于此次文档打开和随后编辑。" + "notes": "通过现有的包内语法文件入口加载首行规则,旧版桌面仍可安装同一插件。仅传入已有文本缓冲区的完整且有界的首行。Core 按启用插件的语言注册顺序匹配。识别结果用于此次文档打开和随后编辑。" } From 0813d3cf4aea08f558441ae7f2733da7cd5ea4df Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Fri, 20 Nov 2026 09:05:46 +0800 Subject: [PATCH 3/5] docs(plugin-api): identify Viva language hints in the API plan --- docs/development/macos-plugin-api-plan.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/development/macos-plugin-api-plan.md b/docs/development/macos-plugin-api-plan.md index b47ba84769..c360b07ced 100644 --- a/docs/development/macos-plugin-api-plan.md +++ b/docs/development/macos-plugin-api-plan.md @@ -77,7 +77,6 @@ Windows 不在本轮,平台矩阵的 partial/pending 保持真实。 | 新增文本格式或高亮规则 | 通过插件清单 `languages[]` 声明文件类型,`grammar.path` 引用包内 JSON 语法;宿主校验后由 worker 执行,不需要 LSP 或后端 | | 注释、括号、自动配对 | 可仅贡献 `configuration`,不要求同时提供 grammar | | 安装、更新、停用或卸载纯静态贡献 | 随已验证插件包的生命周期更新编辑器;这不等于插件可以调用动态 Provider 注册方法,也不授权修改已安装包或监听任意 JSON 文件自动重载 | -| 识别无后缀文本文件 | Viva 可通过已安装的 TextMate 语法文件提供首行规则。走现有的静态语言贡献入口,见 [Core 语法与编辑配置](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/shared/plugins/contract/v1/README.md#grammars-and-editor-configuration)。 | | 运行中直接提交 JSON,注册、替换或释放高亮 Provider | 尚未开放公共方法;当前不是接收任意内联 grammar 的注册入口。`semanticTokens` Provider 提供的是按文档请求的语义着色,只在语言服务器没有语义着色的位置生效,不替代 grammar | | 将补全、悬浮、定义、CodeLens、折叠、语义着色或文档链接绑定到普通插件函数 | 已开放:`lithe/host/editor/registerProviders`,需要 `editor.providers` 权限;每次最多 32 个注册,答案形状与预算由 Core 规定,宿主只能补充语言服务器的答案(见 Agent Note) | | 符号、格式化、重命名、Code Action、签名帮助、内联提示、诊断 | 尚未开放;`registerProviders` 对这些类型返回 `plugin.host.unsupportedOption`(`details.option` 为 `providers.<类型>`),诊断属于 API-26 | @@ -93,6 +92,10 @@ Windows 不在本轮,平台矩阵的 partial/pending 保持真实。 决策边界见[独立插件编辑器 API](../../.agents/notes/implemented/architecture/2026-10-31-plugin-editor-extension-apis.md), 正式资源契约见[语法与编辑配置](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/shared/plugins/contract/v1/README.md#grammars-and-editor-configuration)。 +#### Viva 的首行语言识别 + +上表保留 PR #1595 的盘点。Viva 支持通过 API-25 的静态语法入口为无后缀文件提供首行识别规则。语法文件格式与版本说明见 [Core 语法与编辑配置](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/shared/plugins/contract/v1/README.md#grammars-and-editor-configuration)。 + ### 当前公共调用面汇总 所有宿主请求以 `lithe/host/` 为前缀;这里的点号是阅读简写,正式方法使用 `/`。 From 3dd5a79e97d0c4ac2eedddd06baaf327a20487d0 Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Fri, 20 Nov 2026 10:28:01 +0800 Subject: [PATCH 4/5] =?UTF-8?q?fix(plugins):=20=E8=AF=BB=E5=8F=96=E4=BF=9D?= =?UTF-8?q?=E7=95=99=E5=8E=9F=E9=AB=98=E4=BA=AE=E7=9A=84=E9=A6=96=E8=A1=8C?= =?UTF-8?q?=E5=85=83=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...2026-10-12-declarative-language-plugins.md | 4 +- desktop/internal/core/plugin_session.go | 2 + desktop/internal/pluginhost/pluginhost.go | 2 +- .../internal/pluginhost/pluginhost_test.go | 2 +- desktop/internal/pluginservice/languages.go | 38 ++++++++++--------- .../workbench/document_language_test.go | 31 ++++++++++++++- docs/ci-builds.md | 2 + docs/development/macos-plugin-api-plan.md | 2 +- scripts/desktop/build-desktop-core.sh | 2 +- .../features/plugin-first-line-language.json | 6 +-- 10 files changed, 64 insertions(+), 27 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-10-12-declarative-language-plugins.md b/.agents/notes/implemented/architecture/2026-10-12-declarative-language-plugins.md index 034931e180..ef8e308f4c 100644 --- a/.agents/notes/implemented/architecture/2026-10-12-declarative-language-plugins.md +++ b/.agents/notes/implemented/architecture/2026-10-12-declarative-language-plugins.md @@ -55,7 +55,9 @@ 名称和扩展名先交给编辑器原有的路径关联。只有无后缀且未命中关联的文本文件才使用已安装 TextMate 语法文件中的首行规则。Core 验证语法时一并提取规则。宿主在打开文档的后台任务中从已解码的缓冲区取完整首行,交给 Core 按启用插件的注册顺序匹配。启动时恢复的无后缀标签等待首份语言注册表,再决定语言。高亮、行注释和语言服务使用选中的语言。关闭后重新打开文件时重新识别。 -例如,插件可以用一条首行规则覆盖用户环境里的解释器路径和常见的 `env` 写法。把解释器名称写进宿主,或执行首行来猜测文件类型,都会破坏插件声明与文件内容之间的边界。匹配只消耗有界文本,沿用打开文档已读取的内容。规则是可选的语法元数据,旧版桌面会忽略该元数据,继续安装插件并使用语法文件的高亮规则。规则在启动语言服务器之前已可用。 +例如,插件可以用一条首行规则覆盖用户环境里的解释器路径和常见的 `env` 写法。把解释器名称写进宿主,或执行首行来猜测文件类型,都会破坏插件声明与文件内容之间的边界。匹配只消耗有界文本,沿用打开文档已读取的内容。规则在启动语言服务器之前可用。 + +提供自有语法的插件可以在语法文件内带首行规则。沿用宿主语法的插件使用独立首行元数据,由 Core 解码后只注册匹配规则。包装宿主语法会触发旧版编辑器替换内置 token 分类规则,导致已有文件的配色变化。独立文件随插件包签名,宿主运行时按包内只读资源读取,旧版忽略该文件。 ### 正确与错误示例 diff --git a/desktop/internal/core/plugin_session.go b/desktop/internal/core/plugin_session.go index c24398937a..eac1e3cfd7 100644 --- a/desktop/internal/core/plugin_session.go +++ b/desktop/internal/core/plugin_session.go @@ -176,6 +176,8 @@ type PluginEditorLanguage struct { FileNames []string `json:"fileNames"` Grammar *PluginGrammar `json:"grammar"` Configuration json.RawMessage `json:"configuration"` + // FirstLineMatch comes from standalone metadata and leaves the current grammar intact. + FirstLineMatch string `json:"firstLineMatch,omitempty"` } // PluginGrammar is a validated TextMate source, retained byte for byte. diff --git a/desktop/internal/pluginhost/pluginhost.go b/desktop/internal/pluginhost/pluginhost.go index 7fa38f2f13..5009a39332 100644 --- a/desktop/internal/pluginhost/pluginhost.go +++ b/desktop/internal/pluginhost/pluginhost.go @@ -284,7 +284,7 @@ func resolve(packageDirectory, name string, executable bool) (string, error) { last := i == len(segments)-1 info, statErr := os.Lstat(current) if errors.Is(statErr, os.ErrNotExist) { - return "", fmt.Errorf("%w: %q does not exist", ErrPackagePath, name) + return "", fmt.Errorf("%w: %q: %w", ErrPackagePath, name, os.ErrNotExist) } if statErr != nil { return "", statErr diff --git a/desktop/internal/pluginhost/pluginhost_test.go b/desktop/internal/pluginhost/pluginhost_test.go index 362a6d34b5..725375f8e6 100644 --- a/desktop/internal/pluginhost/pluginhost_test.go +++ b/desktop/internal/pluginhost/pluginhost_test.go @@ -167,7 +167,7 @@ func TestResolvePackagePathRefusesUnsafeNames(t *testing.T) { func TestResolvePackagePathRefusesMissingFile(t *testing.T) { root := writePackage(t, map[string]string{"plugin.json": "{}"}) - if _, err := ResolvePackagePath(root, "bin/absent"); !errors.Is(err, ErrPackagePath) { + if _, err := ResolvePackagePath(root, "bin/absent"); !errors.Is(err, ErrPackagePath) || !errors.Is(err, os.ErrNotExist) { t.Fatalf("err = %v", err) } } diff --git a/desktop/internal/pluginservice/languages.go b/desktop/internal/pluginservice/languages.go index 5b295af9e2..00fbddf9ff 100644 --- a/desktop/internal/pluginservice/languages.go +++ b/desktop/internal/pluginservice/languages.go @@ -23,6 +23,8 @@ const ( // language is well under a megabyte; the ceiling only stops a malformed // package from being read into memory. MaxGrammarBytes = 16 << 20 + // maxFirstLineMetadataBytes bounds an optional TextMate hint without a grammar. + maxFirstLineMetadataBytes = 4096 // MaxDelimiterBytes bounds one comment or bracket delimiter, matching the // contract's editorDelimiter. MaxDelimiterBytes = 16 @@ -104,16 +106,22 @@ func (s *Service) pluginLanguages(ctx context.Context, directory string) ([]synt Extensions: item.FileExtensions, FileNames: item.FileNames, } + name := "grammars/" + item.ID + ".first-line.json" + limit := int64(maxFirstLineMetadataBytes) if item.Grammar != nil { - // The contract has a language whose grammar is refused open as plain text - // while the rest of the plugin keeps working, so a bad grammar costs that - // language its highlighting and nothing else. - if grammar, err := s.grammar(ctx, directory, manifest, item.ID, item.Grammar.Path); err != nil { + name, limit = item.Grammar.Path, MaxGrammarBytes + } + decoded, err := s.editorLanguage(ctx, directory, manifest, item.ID, name, limit) + if err != nil { + // log-exempt: 预期的缺失:独立首行元数据是语言插件的可选资源。 + if item.Grammar != nil || !errors.Is(err, os.ErrNotExist) { failures = append(failures, fmt.Errorf("%s: %w", item.ID, err)) - } else if grammar != nil { - language.Grammar = []byte(grammar.Source) - language.FirstLineMatch = grammar.FirstLineMatch } + } else if grammar := decoded.Grammar; grammar != nil { + language.Grammar = []byte(grammar.Source) + language.FirstLineMatch = grammar.FirstLineMatch + } else { + language.FirstLineMatch = decoded.FirstLineMatch } if configuration := item.Configuration; configuration != nil { if validDelimiter(configuration.LineComment) { @@ -136,21 +144,17 @@ func (s *Service) pluginLanguages(ctx context.Context, directory string) ([]synt return languages, errors.Join(failures...) } -// grammar reads one grammar file from the package and has Core validate it. -func (s *Service) grammar(ctx context.Context, directory string, manifest json.RawMessage, languageID, name string) (*core.PluginGrammar, error) { +// editorLanguage reads one grammar or metadata file and has Core validate it. +func (s *Service) editorLanguage(ctx context.Context, directory string, manifest json.RawMessage, languageID, name string, limit int64) (core.PluginEditorLanguage, error) { path, err := pluginhost.ResolvePackagePath(directory, name) if err != nil { - return nil, err + return core.PluginEditorLanguage{}, err } - source, err := readBounded(path, MaxGrammarBytes) + source, err := readBounded(path, limit) if err != nil { - return nil, err - } - decoded, err := s.kernel.DecodePluginGrammar(ctx, manifest, languageID, string(source)) - if err != nil { - return nil, err + return core.PluginEditorLanguage{}, err } - return decoded.Grammar, nil + return s.kernel.DecodePluginGrammar(ctx, manifest, languageID, string(source)) } // delimiterPair converts one two-element delimiter declaration. diff --git a/desktop/internal/workbench/document_language_test.go b/desktop/internal/workbench/document_language_test.go index 9ac35e421b..55d3ea5732 100644 --- a/desktop/internal/workbench/document_language_test.go +++ b/desktop/internal/workbench/document_language_test.go @@ -1,6 +1,7 @@ package workbench import ( + "encoding/json" "os" "path/filepath" "strings" @@ -14,16 +15,42 @@ import ( ) func TestOpenFileUsesPluginFirstLineLanguage(t *testing.T) { + t.Run("grammar", func(t *testing.T) { testOpenFileUsesPluginFirstLineLanguage(t, false) }) + t.Run("metadata", func(t *testing.T) { testOpenFileUsesPluginFirstLineLanguage(t, true) }) +} + +func testOpenFileUsesPluginFirstLineLanguage(t *testing.T, standalone bool) { + t.Helper() kernel := core.NewClient() manifest, err := os.ReadFile(contractfixture.Path("fixtures/languages/first-line.plugin.json")) if err != nil { t.Fatal(err) } + const id = "dev.lithe.test.first-line" + grammarPath := "grammars/sample.tmLanguage.json" + if standalone { + var declaration map[string]json.RawMessage + var languages []map[string]json.RawMessage + if err := json.Unmarshal(manifest, &declaration); err != nil { + t.Fatal(err) + } + if err := json.Unmarshal(declaration["languages"], &languages); err != nil { + t.Fatal(err) + } + delete(languages[0], "grammar") + declaration["languages"], err = json.Marshal(languages) + if err != nil { + t.Fatal(err) + } + manifest, err = json.Marshal(declaration) + if err != nil { + t.Fatal(err) + } + grammarPath = "grammars/sample.first-line.json" + } if _, err := pluginhost.Validate(t.Context(), kernel, manifest, pluginhost.Declared()); err != nil { t.Fatal(err) } - const id = "dev.lithe.test.first-line" - const grammarPath = "grammars/sample.tmLanguage.json" grammar, err := os.ReadFile(contractfixture.Path("fixtures/languages/" + grammarPath)) if err != nil { t.Fatal(err) diff --git a/docs/ci-builds.md b/docs/ci-builds.md index 0ce7726a4e..5907341d23 100644 --- a/docs/ci-builds.md +++ b/docs/ci-builds.md @@ -68,6 +68,8 @@ macOS 的本地手动打包可用 `package-desktop.sh --ad-hoc-sign` 生成有 ### 独立工作树的本地编译 +TextMate 首行元数据随各插件归档发布,从已安装版本目录只读加载。宿主的匹配缓存只保留当前进程内的编译结果,没有可跨工作树复用的状态。加载过程不写入应用或插件包,不改变签名和增量更新基线。 + 搜索偏好 `/search.json` 由桌面原生存储适配器持有,最多64 KiB;只在用户应用/恢复默认时条件原子写回,打开页面不创建文件。它是用户状态,没有源码、版本、平台、架构或工具链复用身份,不跨工作树复制。搜索索引和未保存快照仅在当前进程内,绑定工作区、可见性与读取预算,关闭项目后释放,不写入安装目录。它们不改变代码签名或增量更新基线。`TestVisualSearchResults` 和 `TestVisualSearchPreferences` 的截图写入当前检出的 `.artifacts/search-visual/`,绑定本次源码、语言、主题和渲染环境,不跨工作树复制;Linux Desktop CI上传后由runner清理,不进入发行包。 工具链提供方回包只在窗口进程内短期缓存。缓存由当前插件版本、工作区上下文和工具输入决定,关闭项目或停用插件时清理。原生文件观察器随缓存释放。该状态没有可复制的编译身份,不跨工作树复用,也不写入插件包或发行目录。 Linux Desktop CI 的工具链提供方截图写入当前检出的 `.artifacts/toolchain-provider-visual/`,按语言分目录,绑定本次源码、Go 工具链与固定的 Viva 和 Core 版本。截图上传后由运行器清理,不跨工作树复制,也不进入安装包。 diff --git a/docs/development/macos-plugin-api-plan.md b/docs/development/macos-plugin-api-plan.md index c360b07ced..8eee1390dc 100644 --- a/docs/development/macos-plugin-api-plan.md +++ b/docs/development/macos-plugin-api-plan.md @@ -94,7 +94,7 @@ Windows 不在本轮,平台矩阵的 partial/pending 保持真实。 #### Viva 的首行语言识别 -上表保留 PR #1595 的盘点。Viva 支持通过 API-25 的静态语法入口为无后缀文件提供首行识别规则。语法文件格式与版本说明见 [Core 语法与编辑配置](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/shared/plugins/contract/v1/README.md#grammars-and-editor-configuration)。 +上表保留 PR #1595 的盘点。Viva 支持通过 API-25 的静态语法入口为无后缀文件提供首行识别规则。沿用已有语法的插件可提供独立的首行元数据。语法文件格式与版本说明见 [Core 语法与编辑配置](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/shared/plugins/contract/v1/README.md#grammars-and-editor-configuration)。 ### 当前公共调用面汇总 diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index 9662e8a68f..42a8495ead 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -286,7 +286,7 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # rows), #13, #8, #7, #6 and #4. # Search pages, unsaved snapshots, source identities and budgets from Core #125, # merged on top of the build-option changes through Core #124. -PINNED_CORE_REVISION="4d45d668223c30e818f67270fb06efd08aef95be" +PINNED_CORE_REVISION="3c0fcffcbc7067be86b832ca2ee3acfc48bf6187" PROFILE="debug" while [[ $# -gt 0 ]]; do case "$1" in diff --git a/shared/platform-feature-matrix/features/plugin-first-line-language.json b/shared/platform-feature-matrix/features/plugin-first-line-language.json index f36ac8651e..ad93a96b53 100644 --- a/shared/platform-feature-matrix/features/plugin-first-line-language.json +++ b/shared/platform-feature-matrix/features/plugin-first-line-language.json @@ -2,7 +2,7 @@ "id": "plugin-first-line-language", "area": "扩展", "group": "插件与主题", - "capability": "安装并启用在 TextMate 语法文件中提供首行规则的语言插件后,可按无后缀脚本的首行选择语法和语言服务,并使用该语言的编辑配置", + "capability": "安装并启用提供 TextMate 首行规则的语言插件后,可按无后缀脚本的首行选择语法和语言服务,并使用该语言的编辑配置", "macos": { "implementationStatus": "implemented", "verificationStatus": "pending", @@ -24,6 +24,6 @@ ] }, "owner": "Extensions", - "verification": "运行 scripts/desktop/desktop-go.sh test ./internal/workbench -run TestOpenFileUsesPluginFirstLineLanguage,确认无后缀文件按首行选择语言,能按该语言切换注释,现有名称与扩展关联优先,带未关联扩展名和超长首行的文件保留原行为。原生窗口另行验收。", - "notes": "通过现有的包内语法文件入口加载首行规则,旧版桌面仍可安装同一插件。仅传入已有文本缓冲区的完整且有界的首行。Core 按启用插件的语言注册顺序匹配。识别结果用于此次文档打开和随后编辑。" + "verification": "运行 scripts/desktop/desktop-go.sh test ./internal/workbench -run TestOpenFileUsesPluginFirstLineLanguage,验证包内语法和独立元数据两种入口都能按首行选择语言并切换注释,名称与扩展关联优先,带未关联扩展名和超长首行的文件保留原行为。原生窗口另行验收。", + "notes": "首行规则来自包内语法文件或独立元数据。独立元数据保留已有高亮,旧版桌面仍可安装同一插件。Core 按启用插件的语言注册顺序匹配已有文本缓冲区的有界首行。识别结果用于此次文档打开和随后编辑。" } From 3ff530de863d3b129fb153f76d3d0d685b56f21f Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Fri, 20 Nov 2026 10:37:33 +0800 Subject: [PATCH 5/5] =?UTF-8?q?fix(editor):=20=E4=BF=9D=E7=95=99=E9=A6=96?= =?UTF-8?q?=E8=A1=8C=E8=AF=AD=E8=A8=80=E5=9C=A8=E6=81=A2=E5=A4=8D=E5=92=8C?= =?UTF-8?q?=E9=A2=84=E8=A7=88=E4=B8=AD=E7=9A=84=E8=AF=AD=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...2026-10-12-declarative-language-plugins.md | 2 +- .github/workflows/desktop-ci.yml | 2 +- .../internal/core/first_line_language_test.go | 52 +++++++++ desktop/internal/workbench/app.go | 4 +- desktop/internal/workbench/difftab.go | 24 ++-- .../internal/workbench/document_language.go | 26 ++++- .../workbench/document_language_views_test.go | 108 ++++++++++++++++++ .../document_language_visual_test.go | 76 ++++++++++++ desktop/internal/workbench/documents.go | 7 +- .../internal/workbench/documents_tabless.go | 2 +- desktop/internal/workbench/source_preview.go | 18 ++- .../features/plugin-first-line-language.json | 8 +- 12 files changed, 295 insertions(+), 34 deletions(-) create mode 100644 desktop/internal/core/first_line_language_test.go create mode 100644 desktop/internal/workbench/document_language_views_test.go create mode 100644 desktop/internal/workbench/document_language_visual_test.go diff --git a/.agents/notes/implemented/architecture/2026-10-12-declarative-language-plugins.md b/.agents/notes/implemented/architecture/2026-10-12-declarative-language-plugins.md index ef8e308f4c..0ea128153d 100644 --- a/.agents/notes/implemented/architecture/2026-10-12-declarative-language-plugins.md +++ b/.agents/notes/implemented/architecture/2026-10-12-declarative-language-plugins.md @@ -53,7 +53,7 @@ ### 6. 无后缀文件按首行识别 -名称和扩展名先交给编辑器原有的路径关联。只有无后缀且未命中关联的文本文件才使用已安装 TextMate 语法文件中的首行规则。Core 验证语法时一并提取规则。宿主在打开文档的后台任务中从已解码的缓冲区取完整首行,交给 Core 按启用插件的注册顺序匹配。启动时恢复的无后缀标签等待首份语言注册表,再决定语言。高亮、行注释和语言服务使用选中的语言。关闭后重新打开文件时重新识别。 +名称和扩展名先交给编辑器原有的路径关联。只有无后缀且未命中关联的文本文件才使用已安装 TextMate 语法文件中的首行规则。Core 验证语法时一并提取规则。宿主在打开文档的后台任务中从已解码的缓冲区取完整首行,交给 Core 按启用插件的注册顺序匹配。启动恢复时,已有路径关联的文档可以立即打开。无后缀且尚无路径关联的文档等待首份语言注册表,然后再检查路径关联和首行规则。文档保存本次选中的语法,Git Diff 的可编辑侧和源码预览复用它。行注释与语言服务使用选中的语言。关闭后重新打开文件时重新识别。 例如,插件可以用一条首行规则覆盖用户环境里的解释器路径和常见的 `env` 写法。把解释器名称写进宿主,或执行首行来猜测文件类型,都会破坏插件声明与文件内容之间的边界。匹配只消耗有界文本,沿用打开文档已读取的内容。规则在启动语言服务器之前可用。 diff --git a/.github/workflows/desktop-ci.yml b/.github/workflows/desktop-ci.yml index df52b29e2a..f0522286e1 100644 --- a/.github/workflows/desktop-ci.yml +++ b/.github/workflows/desktop-ci.yml @@ -216,7 +216,7 @@ jobs: LITHE_VISUAL_OUTPUT_DIR: ${{ github.workspace }}/.artifacts/search-visual run: | ./scripts/desktop/desktop-go.sh test -tags 'vivahead lithevisual' ./internal/workbench ./internal/settingswindow \ - -run '^TestVisualSearch(Results|Preferences)$' -count=1 -timeout=120s + -run '^TestVisualSearch(Results|Preferences|FirstLineLanguage)$' -count=1 -timeout=120s - name: Upload search screenshots if: ${{ !cancelled() && steps.search-visual.outcome != 'skipped' }} diff --git a/desktop/internal/core/first_line_language_test.go b/desktop/internal/core/first_line_language_test.go new file mode 100644 index 0000000000..7297f9d57b --- /dev/null +++ b/desktop/internal/core/first_line_language_test.go @@ -0,0 +1,52 @@ +package core + +import ( + "encoding/json" + "os" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture" +) + +func TestFirstLineLanguageSharedFixture(t *testing.T) { + data, err := os.ReadFile(contractfixture.CoreFixture("plugins/first-line-match-v1.json")) + if err != nil { + t.Fatal(err) + } + type matchResult struct { + LanguageID json.RawMessage `json:"languageID"` + } + var fixture struct { + SchemaVersion int + Command string + Cases []struct { + Name string + Payload json.RawMessage + Expected struct{ Data matchResult } + ErrorCode ErrorCode + } + } + if err := json.Unmarshal(data, &fixture); err != nil { + t.Fatal(err) + } + if fixture.SchemaVersion != 1 || fixture.Command != "languages.matchFirstLine" || len(fixture.Cases) == 0 { + t.Fatal("invalid first-line language fixture") + } + client := NewClient() + for _, c := range fixture.Cases { + t.Run(c.Name, func(t *testing.T) { + var result matchResult + err := client.Execute(testContext(t), fixture.Command, c.Payload, &result) + if c.ErrorCode != "" { + requireCode(t, err, c.ErrorCode) + return + } + if err != nil { + t.Fatal(err) + } + if len(c.Expected.Data.LanguageID) == 0 || string(result.LanguageID) != string(c.Expected.Data.LanguageID) { + t.Fatalf("languageID = %s, want %s", result.LanguageID, c.Expected.Data.LanguageID) + } + }) + } +} diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 80b41329d8..b5c60936d7 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -609,8 +609,8 @@ type App struct { tasks taskQueue // languages are the languages the editor knows, made when the first file is opened. languages *syntax.Registry - // initialLanguageLoad lets early opens of extensionless files wait for the enabled - // language snapshot, even when the project restores its tabs during app startup. + // initialLanguageLoad lets early opens of unknown extensionless files wait for the + // enabled language snapshot while the project restores known paths immediately. initialLanguageLoad atomic.Pointer[languageLoad] settings settings diff --git a/desktop/internal/workbench/difftab.go b/desktop/internal/workbench/difftab.go index fd26643f67..ca6a598603 100644 --- a/desktop/internal/workbench/difftab.go +++ b/desktop/internal/workbench/difftab.go @@ -604,13 +604,21 @@ func (a *App) presentDiff(t *diffTab) { // diffSideEditor shows pane in e, or in a new editor when e is nil or was made with another // grammar; a new editor takes the scroll of the one it replaces. func (a *App) diffSideEditor(t *diffTab, e *diffEditor, pane *diffPane, before bool) *diffEditor { - content := editorview.Prepare(pane.text) // The right side of a working copy shows its document, which may hold edits the disk does not. - editable := !before && a.diffDocument(t) != nil - if editable { - content = a.diffDocument(t).view.CopyContent() - } - if e != nil && e.grammar == t.grammar { + var doc *document + if !before { + doc = a.diffDocument(t) + } + grammar := t.grammar + var content editorview.Content + if doc != nil { + grammar = doc.grammar + content = doc.view.CopyContent() + } else { + content = editorview.Prepare(pane.text) + } + editable := doc != nil + if e != nil && e.grammar == grammar { e.view.ShowContent(content) e.view.SetReadOnly(!editable) e.decorated = nil @@ -626,8 +634,8 @@ func (a *App) diffSideEditor(t *diffTab, e *diffEditor, pane *diffPane, before b if before { label = left + " " + t.change.Path } - e = &diffEditor{label: label, grammar: t.grammar, x: x, y: y} - cfg := editorview.Config{Label: label, Content: content, Syntax: t.grammar, Notify: a.invalidator.Invalidate} + e = &diffEditor{label: label, grammar: grammar, x: x, y: y} + cfg := editorview.Config{Label: label, Content: content, Syntax: grammar, Notify: a.invalidator.Invalidate} if !before { cfg.OnEdit = func(edit editorview.Edit) { a.diffEdited(t, edit) } cfg.Save = func() { diff --git a/desktop/internal/workbench/document_language.go b/desktop/internal/workbench/document_language.go index eb0c21f4fa..445e5a4098 100644 --- a/desktop/internal/workbench/document_language.go +++ b/desktop/internal/workbench/document_language.go @@ -19,19 +19,33 @@ type languageLoad struct { // matches keep priority. Core receives only the bounded, decoded first line. func (a *App) resolveDocumentLanguage(ctx context.Context, registry *syntax.Registry, path string, text rope.Rope) (string, *syntax.Syntax) { hasExtension := filepath.Ext(path) != "" + var pending <-chan struct{} if initial := a.initialLanguageLoad.Load(); initial != nil && !hasExtension { select { case <-initial.done: + default: + pending = initial.done + } + } + for { + if language, ok := registry.ForPath(path); ok { + return language.ID, registry.SyntaxForPath(path) + } + if hasExtension { + return "", nil + } + if pending == nil { + break + } + // Known paths restore immediately. For unknown paths, the initial snapshot + // may add an exact file name, which still wins over a first-line match. + select { + case <-pending: + pending = nil case <-ctx.Done(): return "", nil } } - if language, ok := registry.ForPath(path); ok { - return language.ID, registry.SyntaxForPath(path) - } - if hasExtension { - return "", nil - } const maxFirstLineBytes = 1024 end := text.LineEnd(0) if end == 0 || end > maxFirstLineBytes+1 { diff --git a/desktop/internal/workbench/document_language_views_test.go b/desktop/internal/workbench/document_language_views_test.go new file mode 100644 index 0000000000..d6f04fac11 --- /dev/null +++ b/desktop/internal/workbench/document_language_views_test.go @@ -0,0 +1,108 @@ +package workbench + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/editor/rope" + "github.com/1lck/Lithe-IDEA/desktop/internal/editor/syntax" + "github.com/1lck/Lithe-IDEA/desktop/internal/editorview" +) + +func TestKnownPathOpensWhilePluginLanguagesLoad(t *testing.T) { + var a App + load := &languageLoad{done: make(chan struct{})} + defer close(load.done) + a.initialLanguageLoad.Store(load) + ctx, cancel := context.WithTimeout(t.Context(), time.Second) + defer cancel() + + language, grammar := a.resolveDocumentLanguage(ctx, syntax.NewRegistry(), "Makefile", rope.New([]byte("all:\n"))) + if language != "makefile" || grammar == nil { + t.Fatalf("language = %q, grammar = %v, want Makefile syntax without waiting for plugins", language, grammar) + } +} + +func newFirstLineViewHarness(t *testing.T) *harness { + t.Helper() + h := newHarness(t, &gitKernel{Client: core.NewClient()}) + registerFirstLineViewSyntax(t, h) + return h +} + +func registerFirstLineViewSyntax(t *testing.T, h *harness) { + t.Helper() + failed, _ := h.app.syntaxRegistry().SetPluginLanguages([]syntax.PluginLanguage{{ + ID: "sample", FirstLineMatch: "^#! */opt/tools/sample$", + Grammar: []byte(`{"scopeName":"source.sample","patterns":[{"match":"sample","name":"keyword.control.sample"}]}`), + }}) + if len(failed) != 0 { + t.Fatal(failed) + } +} + +func writeFirstLineViewFile(t *testing.T, root string) string { + t.Helper() + path := filepath.Join(root, "script") + if err := os.WriteFile(path, []byte("#!/opt/tools/sample\nsample\n"), 0o600); err != nil { + t.Fatal(err) + } + return path +} + +func requireFirstLineViewHighlight(t *testing.T, view *editorview.View, line int) { + t.Helper() + tokens := view.SyntaxLine(nil, line) + for _, token := range tokens { + if strings.HasPrefix(token.Name.String(), "keyword") { + return + } + } + t.Fatalf("sample keyword has no syntax highlighting: %v", tokens) +} + +func TestDiffWorkingCopyUsesFirstLineSyntax(t *testing.T) { + root := newTestRepository(t) + path := writeFirstLineViewFile(t, root) + h := newFirstLineViewHarness(t) + p := h.openCommit(root) + tab := openDiffTab(t, h, p, filepath.Base(path)) + doc := p.docs.byPath(path) + if doc == nil || !doc.tabless || doc.languageID != "sample" { + t.Fatal("Diff did not open a tabless sample document") + } + if tab.after == nil || tab.after.view.ReadOnly() { + t.Fatal("the working copy is not editable") + } + requireFirstLineViewHighlight(t, doc.view, 1) + requireFirstLineViewHighlight(t, tab.after.view, 1) +} + +func TestSourcePreviewKeepsOpenDocumentsFirstLineSyntax(t *testing.T) { + root := t.TempDir() + path := writeFirstLineViewFile(t, root) + h := newFirstLineViewHarness(t) + h.open(root) + p := h.app.project + h.app.openFile(p, path) + h.await("the extensionless file to open", func() bool { return p.docs.byPath(path) != nil }) + doc := p.docs.byPath(path) + if doc.languageID != "sample" { + t.Fatalf("language = %q, want sample", doc.languageID) + } + if !doc.view.ApplyEdit(editorview.Edit{StartLine: 0, EndLine: 1, Text: "ordinary text\n"}, true) { + t.Fatal("could not replace the first line") + } + requireFirstLineViewHighlight(t, doc.view, 1) + + var preview sourcePreview + defer preview.close() + h.app.showSourcePreview(p, &preview, path, 2, func(*App) bool { return true }) + h.await("the read-only preview to open", func() bool { return preview.view != nil }) + requireFirstLineViewHighlight(t, preview.view, 1) +} diff --git a/desktop/internal/workbench/document_language_visual_test.go b/desktop/internal/workbench/document_language_visual_test.go new file mode 100644 index 0000000000..47a9c909f9 --- /dev/null +++ b/desktop/internal/workbench/document_language_visual_test.go @@ -0,0 +1,76 @@ +//go:build vivahead && lithevisual + +package workbench + +import ( + "os" + "path/filepath" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/editorview" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/headless" +) + +func TestVisualSearchFirstLineLanguage(t *testing.T) { + out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") + if out == "" { + t.Skip("set LITHE_VISUAL_OUTPUT_DIR") + } + if err := os.MkdirAll(out, 0o755); err != nil { + t.Fatal(err) + } + for _, theme := range []string{"light", "dark"} { + for _, language := range []string{"en", "zh-Hans"} { + name := theme + "-" + language + t.Run(name, func(t *testing.T) { + root := newTestRepository(t) + path := writeFirstLineViewFile(t, root) + prefs := store.At(t.TempDir()) + if err := prefs.Save(settingsFile, settings{Theme: themeChoice(theme), Language: language, DisableAutoSave: true}); err != nil { + t.Fatal(err) + } + var session *headless.Session + h := newHarnessWithDriver(t, Options{Kernel: &gitKernel{Client: core.NewClient()}, Store: prefs, Languages: []string{language}}, func(config app.Config) (*app.Driver, func(), error) { + config.Width, config.Height = 1280, 800 + var err error + session, err = headless.Open(config, nil, headless.Options{}) + if err != nil { + return nil, nil, err + } + return session.Driver(), session.Close, nil + }) + registerFirstLineViewSyntax(t, h) + p := h.openCommit(root) + tab := openDiffTab(t, h, p, filepath.Base(path)) + if tab.after == nil || tab.after.view.ReadOnly() { + t.Fatal("the working copy is not editable") + } + if err := session.Screenshot(filepath.Join(out, "first-line-diff-"+name+".png")); err != nil { + t.Fatal(err) + } + + h.app.openFile(p, path) + doc := p.docs.byPath(path) + if doc == nil || doc.tabless || !doc.view.ApplyEdit(editorview.Edit{StartLine: 0, EndLine: 1, Text: "ordinary text\n"}, true) { + t.Fatal("could not edit the first line in the document tab") + } + h.app.openEverywhere(p) + h.settle() + h.clickNamed(h.shared("desktop.everywhere.text")) + h.app.everywhereView.delay = 0 + h.app.everywhereView.preview = true + h.app.everywhereView.query.SetText("ordinary") + preview := &h.app.everywhereView.source + h.await("the changed script in the search preview", func() bool { + return preview.view != nil && preview.path == path + }) + if err := session.Screenshot(filepath.Join(out, "first-line-preview-"+name+".png")); err != nil { + t.Fatal(err) + } + }) + } + } +} diff --git a/desktop/internal/workbench/documents.go b/desktop/internal/workbench/documents.go index d6cb121192..6a94be0ace 100644 --- a/desktop/internal/workbench/documents.go +++ b/desktop/internal/workbench/documents.go @@ -74,7 +74,10 @@ type document struct { // by. path, name string languageID string - view *editorview.View + // grammar is the syntax selected on open, including any bundled fallback. + // Views of this document share it for the lifetime of the open document. + grammar *syntax.Syntax + view *editorview.View // lens is a second view of the text that the user last typed or clicked in: the editable // preview of the Problems tool window (source_preview.go). The language features follow its // caret while it is set, so completion, hover and the rest work there as in the editor; nil @@ -512,7 +515,7 @@ func (a *App) placeDocumentAs(p *project, path, name string, content editorview. return } p.docs.next = id - d := &document{id: id, path: path, name: name, languageID: languageID, virtual: virtual} + d := &document{id: id, path: path, name: name, languageID: languageID, grammar: grammar, virtual: virtual} d.view = editorview.New(editorview.Config{ Label: name, Content: content, diff --git a/desktop/internal/workbench/documents_tabless.go b/desktop/internal/workbench/documents_tabless.go index b88027f448..cbc730b181 100644 --- a/desktop/internal/workbench/documents_tabless.go +++ b/desktop/internal/workbench/documents_tabless.go @@ -94,7 +94,7 @@ func (a *App) addTablessDocument(p *project, path string, file tablessFile) *doc // newTablessDocument makes the document of path with its editor, wired the way a tab's document is, // except for its tab, its input and its watch, which attachDocumentTab adds. func (a *App) newTablessDocument(p *project, id int, path, name string, content editorview.Content, grammar *syntax.Syntax, languageID string) *document { - d := &document{id: id, path: path, name: name, languageID: languageID} + d := &document{id: id, path: path, name: name, languageID: languageID, grammar: grammar} d.view = editorview.New(editorview.Config{ Label: name, Content: content, diff --git a/desktop/internal/workbench/source_preview.go b/desktop/internal/workbench/source_preview.go index 57eb4746ce..24500de32d 100644 --- a/desktop/internal/workbench/source_preview.go +++ b/desktop/internal/workbench/source_preview.go @@ -173,10 +173,11 @@ func (a *App) showSourcePreview(p *project, sp *sourcePreview, path string, line sp.path, sp.line = path, line generation := sp.generation var openText []byte + var openGrammar *syntax.Syntax open := false if d := p.docs.byPath(path); d != nil { - data, _ := d.view.Text() - openText = append([]byte(nil), data...) + openText, _ = d.view.Text() + openGrammar = d.grammar open = true } registry := a.syntaxRegistry() @@ -190,10 +191,12 @@ func (a *App) showSourcePreview(p *project, sp *sourcePreview, path string, line data = read.text } var content editorview.Content - var grammar *syntax.Syntax + grammar := openGrammar if err == nil { content = editorview.Prepare(data) - _, grammar = a.resolveDocumentLanguage(ctx, registry, path, content.Snapshot()) + if !open { + _, grammar = a.resolveDocumentLanguage(ctx, registry, path, content.Snapshot()) + } } return func(a *App) { if sp.generation != generation || a.project != p || !alive(a) { @@ -244,16 +247,11 @@ func (a *App) showEditablePreview(p *project, sp *sourcePreview, path string, li // bindSourcePreview makes the editable view of document d, which shares the document's text, // and reveals the line. func (a *App) bindSourcePreview(p *project, sp *sourcePreview, d *document) { - registry := a.syntaxRegistry() - grammar := registry.SyntaxForPath(d.path) - if grammar == nil && d.languageID != "" { - grammar = registry.Syntax(d.languageID) - } var view *editorview.View view = editorview.New(editorview.Config{ Label: d.name, Content: d.view.CopyContent(), - Syntax: grammar, + Syntax: d.grammar, Notify: a.invalidator.Invalidate, Save: func() { a.saveDocument(p, d.id) }, OnEdit: func(edit editorview.Edit) { a.previewEdited(p, sp, view, edit) }, diff --git a/shared/platform-feature-matrix/features/plugin-first-line-language.json b/shared/platform-feature-matrix/features/plugin-first-line-language.json index ad93a96b53..5b00d423e1 100644 --- a/shared/platform-feature-matrix/features/plugin-first-line-language.json +++ b/shared/platform-feature-matrix/features/plugin-first-line-language.json @@ -10,7 +10,8 @@ "desktop/internal/pluginservice/languages.go", "desktop/internal/editor/syntax/language.go", "desktop/internal/workbench/document_language.go", - "desktop/internal/workbench/document_language_test.go" + "desktop/internal/workbench/document_language_test.go", + "desktop/internal/workbench/document_language_views_test.go" ] }, "windows": { @@ -20,10 +21,11 @@ "desktop/internal/pluginservice/languages.go", "desktop/internal/editor/syntax/language.go", "desktop/internal/workbench/document_language.go", - "desktop/internal/workbench/document_language_test.go" + "desktop/internal/workbench/document_language_test.go", + "desktop/internal/workbench/document_language_views_test.go" ] }, "owner": "Extensions", "verification": "运行 scripts/desktop/desktop-go.sh test ./internal/workbench -run TestOpenFileUsesPluginFirstLineLanguage,验证包内语法和独立元数据两种入口都能按首行选择语言并切换注释,名称与扩展关联优先,带未关联扩展名和超长首行的文件保留原行为。原生窗口另行验收。", - "notes": "首行规则来自包内语法文件或独立元数据。独立元数据保留已有高亮,旧版桌面仍可安装同一插件。Core 按启用插件的语言注册顺序匹配已有文本缓冲区的有界首行。识别结果用于此次文档打开和随后编辑。" + "notes": "首行规则来自包内语法文件或独立元数据。独立元数据保留已有高亮,旧版桌面仍可安装同一插件。Core 按启用插件的语言注册顺序匹配已有文本缓冲区的有界首行。已有路径关联的文件恢复时可直接打开。识别结果用于此次文档打开、预览、Git Diff 的可编辑侧和随后编辑。" }