Skip to content
Merged
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
Expand Up @@ -51,6 +51,14 @@
- 历史回放不保存来源语言,而是把文件当作它自己语言的源码重新校验。
- 外部文件始终只读,保存被拒绝。普通打开(项目树、搜索、外部 URL)仍然拒绝工作区外路径。

### 6. 无后缀文件按首行识别

名称和扩展名先交给编辑器原有的路径关联。只有无后缀且未命中关联的文本文件才使用已安装 TextMate 语法文件中的首行规则。Core 验证语法时一并提取规则。宿主在打开文档的后台任务中从已解码的缓冲区取完整首行,交给 Core 按启用插件的注册顺序匹配。启动恢复时,已有路径关联的文档可以立即打开。无后缀且尚无路径关联的文档等待首份语言注册表,然后再检查路径关联和首行规则。文档保存本次选中的语法,Git Diff 的可编辑侧和源码预览复用它。行注释与语言服务使用选中的语言。关闭后重新打开文件时重新识别。

例如,插件可以用一条首行规则覆盖用户环境里的解释器路径和常见的 `env` 写法。把解释器名称写进宿主,或执行首行来猜测文件类型,都会破坏插件声明与文件内容之间的边界。匹配只消耗有界文本,沿用打开文档已读取的内容。规则在启动语言服务器之前可用。

提供自有语法的插件可以在语法文件内带首行规则。沿用宿主语法的插件使用独立首行元数据,由 Core 解码后只注册匹配规则。包装宿主语法会触发旧版编辑器替换内置 token 分类规则,导致已有文件的配色变化。独立文件随插件包签名,宿主运行时按包内只读资源读取,旧版忽略该文件。

### 正确与错误示例

正确:为新语言写 `plugin.json`,声明 `languageServers` 和执行提供者,在契约 fixture 中补一个命令展开样例,并在 Core 测试中验证。
Expand All @@ -77,6 +85,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`

## 适用范围
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/desktop-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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' }}
Expand Down
52 changes: 52 additions & 0 deletions desktop/internal/core/first_line_language_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
}
4 changes: 4 additions & 0 deletions desktop/internal/core/plugin_session.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,13 +176,17 @@ 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.
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
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 @@ -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.
Expand Down Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions desktop/internal/editorview/prepared_edit.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion desktop/internal/pluginhost/pluginhost.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion desktop/internal/pluginhost/pluginhost_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
Expand Down
52 changes: 26 additions & 26 deletions desktop/internal/pluginservice/languages.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -22,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
Expand Down Expand Up @@ -103,15 +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 {
language.Grammar = grammar
}
} 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) {
Expand All @@ -123,38 +133,28 @@ 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)
}
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) ([]byte, 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
}
source, err := readBounded(path, MaxGrammarBytes)
if err != nil {
return nil, err
return core.PluginEditorLanguage{}, err
}
decoded, err := s.kernel.DecodePluginGrammar(ctx, manifest, languageID, string(source))
source, err := readBounded(path, limit)
if err != nil {
return nil, err
}
if decoded.Grammar == nil {
return nil, nil
return core.PluginEditorLanguage{}, err
}
return []byte(decoded.Grammar.Source), nil
return s.kernel.DecodePluginGrammar(ctx, manifest, languageID, string(source))
}

// delimiterPair converts one two-element delimiter declaration.
Expand Down
3 changes: 3 additions & 0 deletions desktop/internal/workbench/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -609,6 +609,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 unknown extensionless files wait for the
// enabled language snapshot while the project restores known paths immediately.
initialLanguageLoad atomic.Pointer[languageLoad]

settings settings
// fonts is the font of each scope the settings name, worked out by applyFonts.
Expand Down
24 changes: 16 additions & 8 deletions desktop/internal/workbench/difftab.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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() {
Expand Down
77 changes: 77 additions & 0 deletions desktop/internal/workbench/document_language.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
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) != ""
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
}
}
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
}
Loading
Loading