Порівняти коміти

..
Автор SHA1 Повідомлення Дата
l0ng-ai b3dc32c5ec fix(plugins): deliver document-changed events to plugins
The event queue relativized every path event at enqueue time, which turned a
document-changed path into a project-relative one before the delivery filter
ran; the filter then looked up a relative path, found no project for it and
dropped the event, so subscribed plugins never saw edits.

The queue now keeps document paths absolute through filtering and relativizes
them to the file's own project when handing events to the plugin. The
path-events test fixture subscribes document-changed to cover the flow.

Fixes #4008
2026-11-17 23:13:29 +08:00
l0ng-ai 7e5277eaa6 feat(languages): Typst with the tinymist language server (#4023)
Typst (.typ) files get syntax colouring for markup, embedded code and math, a file icon, and the tinymist language server (installable from its GitHub releases) for completion, diagnostics, navigation and the outline.

Closes #3924
2026-11-17 22:44:13 +08:00
l0ng-ai 2278cf6e8f fix(editor): don't indent C++ namespace and extern "C" contents on Enter (#4018)
Enter inside namespace x { … } or extern "C" { … } indented the new line one level, like any brace body. clang-format's built-in styles (LLVM, Google, Chromium, Mozilla, Microsoft, GNU) keep those contents at the level of the braces' line (NamespaceIndentation: None), so the editor now does too; other brace bodies keep their indentation.

Fixes #3993
2026-11-17 22:10:13 +08:00
l0ng-ai d4f6114be1 feat(settings): context menu for the deployment server list (#4017)
Right-clicking a server or server group in Settings › Build, Execution, Deployment › Deployment selects it and offers Add (Server / Server Group), Duplicate and Use as Default for a server, and Remove; the empty part of the list offers Add.

Closes #3910
2026-11-17 22:03:35 +08:00
l0ng-ai ad93e491c9 feat(settings): choose PHP include paths with a folder chooser (#4016)
+ under Settings › Languages & Frameworks › PHP › Include paths opens a folder chooser and adds the picked folder; Edit and double-click still take a typed path, and outside the desktop app + keeps adding a row to type into. Additional stubs are stub names, so that list stays typed.

Closes #3912
2026-11-17 22:00:43 +08:00
l0ng-ai 098e80dbef fix(agents): name the task's agent in the session status line (#4015)
The session status line under the composer lost the agent's icon and name when it was reduced to one quiet line; with several tasks open side by side there was no way to tell which agent answered without opening the picker. It starts with the agent's icon and name again, before the branch.

Fixes #3917
2026-11-17 21:58:00 +08:00
l0ng-ai 6ab7627fc4 feat(vcs): project conventions for Generate Commit Message with Agent (#4014)
Settings › Version Control › Commit gets a Commit Message Generation section with a multi-line field (vcs.commit.agentInstructions, global or per project). Its text is added to the agent's prompt as the conventions to follow, ahead of the style taken from recent commit subjects.

Closes #3934
2026-11-17 21:53:38 +08:00
27 змінених файлів з 754 додано та 48 видалено

No files matched your search

+41 -28
Переглянути файл
@@ -5,7 +5,7 @@ use ide_extension::Capability;
use ide_plugin::{EventKind, HostError, WorkbenchEvent};
use std::{
collections::{BTreeSet, HashMap},
path::Path,
path::{Path, PathBuf},
};
#[derive(Clone, Default)]
@@ -136,32 +136,14 @@ impl PluginHost {
if !path.is_absolute() {
return None;
}
let workspace = workspace.as_ref()?;
let real = ide_plugin::resolve_real(path);
// The file's own project, not the invoking window's: annotations follow
// the file, so a plugin hears about a file another window has open.
let root = match client {
Some(client) => workspace
.project_of(client)
.filter(|r| real.starts_with(ide_plugin::resolve_real(r)))
.or_else(|| {
workspace
.projects()
.into_iter()
.filter(|r| real.starts_with(ide_plugin::resolve_real(r)))
.max_by_key(|r| r.components().count())
}),
None => workspace
.projects()
.into_iter()
.filter(|r| real.starts_with(ide_plugin::resolve_real(r)))
.max_by_key(|r| r.components().count()),
}?;
let root = file_project(workspace.as_deref()?, client, path)?;
if plugin.dev_root.as_deref().is_some_and(|r| r != root) {
return None;
}
if let WorkbenchEvent::DocumentChanged(change) = event {
if let WorkbenchEvent::DocumentChanged(_) = event {
// Typed text: only for plugins that may read editors, and only for paths they named.
// The path stays absolute until delivery (`relativize_documents`): the batch is
// filtered again then, against the grants and subscriptions of that moment.
let filter = filters.and_then(|filters| filters.get(event.kind().name()))?;
let granted = &plugin.meta.lock().granted;
if !granted.contains(&Capability::ProjectRead)
@@ -170,11 +152,7 @@ impl PluginHost {
{
return None;
}
let real = ide_plugin::resolve_real(path);
let relative = real.strip_prefix(ide_plugin::resolve_real(&root)).ok()?;
let mut change = change.clone();
change.path = relative.to_string_lossy().replace('\\', "/");
return Some(WorkbenchEvent::DocumentChanged(change));
return Some(event.clone());
}
filters
.and_then(|filters| filters.get(event.kind().name()))
@@ -183,6 +161,41 @@ impl PluginHost {
})
.collect()
}
/// What a plugin receives for `document-changed`: the path relative to the file's own project.
pub(super) fn relativize_documents(
shared: &super::api::Shared,
client: Option<&str>,
events: Vec<WorkbenchEvent>,
) -> Vec<WorkbenchEvent> {
let workspace = shared.workspace();
events
.into_iter()
.filter_map(|event| {
let WorkbenchEvent::DocumentChanged(mut change) = event else { return Some(event) };
let path = Path::new(&change.path);
let root = file_project(workspace.as_deref()?, client, path)?;
let relative = ide_plugin::resolve_real(path)
.strip_prefix(ide_plugin::resolve_real(&root))
.ok()?
.to_string_lossy()
.replace('\\', "/");
change.path = relative;
Some(WorkbenchEvent::DocumentChanged(change))
})
.collect()
}
}
/// The open project an absolute `path` belongs to: the invoking window's when the file is in
/// it, else the innermost open project containing it. Annotations follow the file, so a
/// plugin hears about a file another window has open.
fn file_project(workspace: &dyn super::api::PluginWorkspace, client: Option<&str>, path: &Path) -> Option<PathBuf> {
let real = ide_plugin::resolve_real(path);
let contains = |r: &PathBuf| real.starts_with(ide_plugin::resolve_real(r));
client
.and_then(|client| workspace.project_of(client).filter(contains))
.or_else(|| workspace.projects().into_iter().filter(contains).max_by_key(|r| r.components().count()))
}
#[cfg(test)]
+1
Переглянути файл
@@ -2214,6 +2214,7 @@ impl PluginHost {
if events.is_empty() {
return Ok(());
}
let events = Self::relativize_documents(&shared, invocation.client.as_deref(), events);
rt.handle_events(events, invocation)
},
move |result| {
+23
Переглянути файл
@@ -5284,6 +5284,29 @@ fn plugin_readonly_fields_and_table_row_extensions_round_trip() {
}
}
#[test]
fn document_changes_reach_plugins_relative_to_the_project() {
let f = fixture(Limits::default());
f.install(&sample("path-events"));
f.run("test.path-events", "count", None).unwrap();
let deliver = |path: &str| {
let change = ide_plugin::DocumentChanged {
path: to_ipc(&f.project.join(path)),
base_version: 1,
version: 2,
changes: Vec::new(),
};
f.host.post_events(Some("main"), vec![WorkbenchEvent::DocumentChanged(change)]);
f.host.flush_events_at(Instant::now() + Duration::from_secs(3));
assert!(f.host.wait_events(Duration::from_secs(10)));
};
deliver("src/main.rs");
assert_eq!(f.run("test.path-events", "document", None).unwrap(), None, "outside the subscribed paths");
// Queued with the absolute path, filtered again at delivery, handed over project-relative.
deliver("config/app.yaml");
assert_eq!(f.run("test.path-events", "document", None).unwrap().as_deref(), Some("config/app.yaml"));
}
#[test]
fn path_filtered_events_do_not_wake_idle_plugins_and_recheck_queued_filters() {
let f = fixture(Limits { idle_timeout: Some(Duration::from_millis(100)), ..Limits::default() });
+2
Переглянути файл
@@ -90,6 +90,7 @@ const BUILTIN: &[(&str, &str)] = &[
("toml", include_str!("../../../languages/toml.toml")),
("typescript", include_str!("../../../languages/typescript.toml")),
("typescriptreact", include_str!("../../../languages/typescriptreact.toml")),
("typst", include_str!("../../../languages/typst.toml")),
("vue", include_str!("../../../languages/vue.toml")),
("xml", include_str!("../../../languages/xml.toml")),
("yaml", include_str!("../../../languages/yaml.toml")),
@@ -612,6 +613,7 @@ mod tests {
"TTCN",
"TTCN_CFG",
"Turtle",
"Typst",
"Web IDL",
"VB.NET",
"VBScript",
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
f9c0cb4fca66ede5adcb1951dd05c3938c218224cb61e63a574ba08a93f4a041
872f94f4bbc441457f36ed7b44b3a2fb6b87021f2f0a66104caf5c807b524147
+6 -2
Переглянути файл
@@ -1,13 +1,13 @@
id = "test.path-events"
name = "Path event fixture"
version = "0.1.0"
engines.openidea = "^1.3"
engines.openidea = "^1.6"
wasm = "dist/plugin.wasm"
activation = ["on-command:*"]
[capabilities]
required = ["storage"]
optional = ["events", "project.read"]
optional = ["events", "project.read", "editor.read"]
[[contributes.providers]]
kinds = ["hover"]
@@ -29,6 +29,10 @@ title = "all"
id = "off"
title = "off"
[[contributes.commands]]
id = "document"
title = "document"
[[contributes.commands]]
id = "count"
title = "count"
+7
Переглянути файл
@@ -11,6 +11,7 @@ impl Plugin for Fixture {
let globs: Vec<_> = glob.lines().collect();
let _ = host::subscribe_paths("file-opened", &globs);
let _ = host::subscribe_paths("file-saved", &["config/*.yaml"]);
let _ = host::subscribe_paths("document-changed", &["config/*.yaml"]);
Ok(())
}
fn run_command(&mut self, id: &str, _: &Invocation, arg: Option<&str>) -> Result<Option<String>, Error> {
@@ -31,12 +32,18 @@ impl Plugin for Fixture {
Ok(None)
}
"count" => Ok(host::storage::get("count")?),
"document" => Ok(host::storage::get("document")?),
_ => Err(Error::NotFound(id.into())),
}
}
fn handle_events(&mut self, events: &[Event], _: &Invocation) {
let count = host::storage::get("count").ok().flatten().and_then(|n| n.parse::<usize>().ok()).unwrap_or(0);
host::storage::set("count", &(count + events.len()).to_string()).unwrap();
for event in events {
if let Event::DocumentChanged(change) = event {
host::storage::set("document", &change.path).unwrap();
}
}
}
}
impl HoverProvider for Fixture {
+22
Переглянути файл
@@ -992,6 +992,28 @@ pub static TOOLS: &[ToolSpec] = &[
homepage: "https://github.com/latex-lsp/texlab",
needs: &[],
},
ToolSpec {
name: "tinymist",
display: "Tinymist (Typst)",
kind: LanguageServer,
commands: &["tinymist"],
method: Method::Release {
source: ReleaseSource::GitHub { repo: "Myriad-Dreamin/tinymist" },
assets: &[
rule(Mac, Arm64, "tinymist-aarch64-apple-darwin.tar.gz"),
rule(Mac, X64, "tinymist-x86_64-apple-darwin.tar.gz"),
rule(Linux, X64, "tinymist-x86_64-unknown-linux-gnu.tar.gz"),
rule(Linux, Arm64, "tinymist-aarch64-unknown-linux-gnu.tar.gz"),
rule(Windows, X64, "tinymist-x86_64-pc-windows-msvc.zip"),
rule(Windows, Arm64, "tinymist-aarch64-pc-windows-msvc.zip"),
],
locate: &["tinymist"],
},
fallback: None,
version: ver("tinymist"),
homepage: "https://myriad-dreamin.github.io/tinymist/",
needs: &[],
},
ToolSpec {
name: "slint-lsp",
display: "Slint LSP",
+1
Переглянути файл
@@ -172,6 +172,7 @@ The table lists every built-in language definition. Server and debugger names in
| TOML | `toml` | `.toml` | Yes | Yes | **taplo** | — |
| TypeScript | `typescript` | `.ts`, `.mts`, `.cts` | Yes | Yes | **vtsls** → **typescript-language-server** + **angular-language-server** + **oxlint** | **js-debug** |
| TypeScript JSX | `typescriptreact` | `.tsx` | Yes | Yes | **vtsls** → **typescript-language-server** + **oxlint** | **js-debug** |
| Typst | `typst` | `.typ` | — | — | **tinymist** | — |
| Vue | `vue` | `.vue` | Yes | — | **vue-language-server**, **vtsls** + **oxlint** | — |
| XML | `xml` | `.xml`, `.xsd`, `.xsl`, `.xslt`, `.svg`, … | Yes | Yes | **lemminx** | — |
| YAML | `yaml` | `.yaml`, `.yml` | Yes | Yes | **yaml-language-server** | — |
+1
Переглянути файл
@@ -167,6 +167,7 @@ IDE 安装工具从不需要 `sudo`。工具装在本地数据目录下 IDE 自
| TOML | `toml` | `.toml` | 是 | 是 | **taplo** | — |
| TypeScript | `typescript` | `.ts`, `.mts`, `.cts` | 是 | 是 | **vtsls** → **typescript-language-server** + **angular-language-server** + **oxlint** | **js-debug** |
| TypeScript JSX | `typescriptreact` | `.tsx` | 是 | 是 | **vtsls** → **typescript-language-server** + **oxlint** | **js-debug** |
| Typst | `typst` | `.typ` | — | — | **tinymist** | — |
| Vue | `vue` | `.vue` | 是 | — | **vue-language-server**, **vtsls** + **oxlint** | — |
| XML | `xml` | `.xml`, `.xsd`, `.xsl`, `.xslt`, `.svg`, … | 是 | 是 | **lemminx** | — |
| YAML | `yaml` | `.yaml`, `.yml` | 是 | 是 | **yaml-language-server** | — |
+14
Переглянути файл
@@ -0,0 +1,14 @@
id = "typst"
name = "Typst"
extensions = ["typ"]
line-comment = "//"
block-comment = ["/*", "*/"]
indent = { tab-size = 2, insert-spaces = true }
ui-mode = "Typst"
[[language-servers]]
name = "tinymist"
command = "tinymist"
args = ["lsp"]
root-markers = ["typst.toml"]
install-hint = "cargo install --locked --git https://github.com/Myriad-Dreamin/tinymist tinymist-cli (or brew install tinymist)"
+77
Переглянути файл
@@ -1,6 +1,7 @@
import { EditorState } from "@codemirror/state";
import { LanguageDescription, type Language } from "@codemirror/language";
import { describe, expect, it } from "vitest";
import { getIndentation } from "@codemirror/language";
import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight";
import { logWarning } from "./highlight";
import { fencedCodeMode, findLanguageDescription, loadSupport } from "./languages";
@@ -271,6 +272,28 @@ describe("language modes", () => {
}
});
it('keeps C++ namespace and extern "C" contents at the level of their braces', async () => {
const support = await loadSupport(findLanguageDescription("C++", "/p/a.cpp")!);
const doc = [
"namespace foo {",
"class Bar {",
" int x;",
"};",
"namespace inner {",
"void f() {",
" g();",
"}",
"} // namespace inner",
"} // namespace foo",
'extern "C" {',
"int h();",
"}",
].join("\n");
const state = EditorState.create({ doc, extensions: [support!, EditorState.tabSize.of(2)] });
const indent = (line: number) => getIndentation(state, state.doc.line(line).from);
expect([2, 3, 4, 5, 6, 7, 9, 10, 12, 13].map(indent)).toEqual([0, 2, 0, 0, 0, 2, 0, 0, 0, 0]);
});
it("colours `this`, `super` and Rust's `self` as keywords", async () => {
const highlighter = tagHighlighter([
{ tag: t.keyword, class: "keyword" },
@@ -415,4 +438,58 @@ describe("language modes", () => {
]);
}
});
it("colours Typst markup, embedded code and math", async () => {
const support = await loadSupport(findLanguageDescription("Typst", "/p/notes.typ")!);
const highlighter = tagHighlighter([
{ tag: t.keyword, class: "keyword" },
{ tag: t.comment, class: "comment" },
{ tag: t.heading, class: "heading" },
{ tag: t.strong, class: "strong" },
{ tag: t.emphasis, class: "emphasis" },
{ tag: t.string, class: "string" },
{ tag: t.number, class: "number" },
{ tag: t.function(t.variableName), class: "function" },
{ tag: t.labelName, class: "label" },
{ tag: t.monospace, class: "raw" },
{ tag: t.atom, class: "atom" },
]);
const source = [
"#set page(width: 10cm)",
"// note",
"= Intro <intro>",
"Some *bold* and _it_ in snake_case, `raw` and $x^2$ see @intro.",
"#let total = 1 + 2",
"#if true [yes]",
"```rust",
"let x = 1;",
"```",
].join("\n");
const found: string[] = [];
highlightTree(support!.language.parser.parse(source), highlighter, (from, to, cls) =>
found.push(`${source.slice(from, to)}:${cls}`),
);
expect(found).toEqual(
expect.arrayContaining([
"#set:keyword",
"page:function",
"10cm:number",
"// note:comment",
"= Intro :heading",
"<intro>:label",
"*bold*:strong",
"_it_:emphasis",
"`raw`:raw",
"$:keyword",
"@intro:label",
"#let:keyword",
"1:number",
"#if:keyword",
"true:atom",
"```rust:raw",
"let x = 1;:raw",
]),
);
expect(found.filter((f) => f.endsWith(":emphasis"))).toEqual(["_it_:emphasis"]);
expect(found).not.toContain("yes:keyword");
});
});
+26 -3
Переглянути файл
@@ -11,6 +11,8 @@ import {
LanguageDescription,
LanguageSupport,
StreamLanguage,
delimitedIndent,
indentNodeProp,
indentService,
language as languageFacet,
type StreamParser,
@@ -112,6 +114,11 @@ const OWN_MODES = [
extensions: ["rst"],
load: () => import("./restructuredtext").then((m) => new LanguageSupport(m.restructuredtextLanguage)),
}),
LanguageDescription.of({
name: "Typst",
extensions: ["typ"],
load: async () => new LanguageSupport(StreamLanguage.define((await import("./typst")).typstParser)),
}),
LanguageDescription.of({
name: "Gherkin",
extensions: ["feature"],
@@ -421,12 +428,28 @@ const EXTRA_TAGS: Record<string, Parameters<typeof styleTags>[0]> = {
YAML: { "Key/Literal Key/QuotedLiteral": t.keyword },
};
const bracedIndent = delimitedIndent({ closing: "}" });
/** Grammar props the stock languages lack: indentation that follows the language's usual style. */
const EXTRA_PROPS: Record<string, NonNullable<Parameters<LRLanguage["configure"]>[0]["props"]>> = {
// clang-format's built-in styles (NamespaceIndentation: None, no extern block indent) keep the
// contents of `namespace x { … }` and `extern "C" { … }` at the level of the braces' line.
"C++": [
indentNodeProp.add({
// The stock rule for every `{ … }` body, except the bodies of these two.
CompoundStatement: (cx) =>
cx.node.parent?.name === "NamespaceDefinition" || cx.node.parent?.name === "LinkageSpecification"
? cx.baseIndent
: bracedIndent(cx),
}),
],
};
function patchSupport(desc: LanguageDescription, support: LanguageSupport): LanguageSupport {
const extra = EXTRA_TAGS[desc.name];
const props = [...(extra ? [styleTags(extra)] : []), ...(EXTRA_PROPS[desc.name] ?? [])];
const language =
extra && support.language instanceof LRLanguage
? support.language.configure({ props: [styleTags(extra)] })
: support.language;
props.length && support.language instanceof LRLanguage ? support.language.configure({ props }) : support.language;
const result = new LanguageSupport(language, [
support.support,
docCommentTags(desc.name),
+321
Переглянути файл
@@ -0,0 +1,321 @@
/**
* Typst markup, code and math as Typst's own lexer splits them (typst-syntax `lexer.rs`): markup
* with `#` embedding a code expression, `[...]` content blocks and `$...$` math nesting in code
* and back. A `#keyword` statement lasts to the end of its line unless a bracket keeps it open.
*/
import type { StreamParser, StringStream } from "@codemirror/language";
type Frame =
/** Markup inside `[...]`; the document itself is the markup below every frame. */
| { kind: "content" }
/** Code in `(...)` or `{...}`, closed by `close`. */
| { kind: "code"; close: ")" | "}" }
/** A `#let` / `#set` / `#show` … statement, ending with its line. */
| { kind: "statement" }
/** An embedded `#name`: calls, content arguments and field accesses may follow it directly. */
| { kind: "expr" }
| { kind: "math" };
export interface TypstState {
stack: Frame[];
strong: boolean;
emph: boolean;
heading: boolean;
/** Nesting depth of an open block comment. */
comment: number;
/** The backtick fence of an open raw block. */
raw: string | null;
}
const KEYWORDS = new Set([
"let",
"set",
"show",
"context",
"if",
"else",
"for",
"in",
"while",
"break",
"continue",
"return",
"import",
"include",
"as",
"and",
"or",
"not",
]);
const ATOMS = new Set(["none", "auto", "true", "false"]);
const IDENT = /^[\p{L}_][\p{L}\p{N}_-]*/u;
const NUMBER = /^(?:0x[0-9a-fA-F]+|0o[0-7]+|0b[01]+|(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?(?:pt|mm|cm|in|em|fr|deg|rad|%)?)/;
const LABEL = /^<[\p{L}\p{N}_\-.:]+>/u;
const REF = /^@[\p{L}\p{N}_\-.:]*[\p{L}\p{N}_]/u;
const URL = /^https?:\/\/[^\s<>[\](){}"]*[^\s<>[\](){}".,;:!?'"]/;
const MARKUP_TEXT = /^[^\\#$*_`<@/[\]\nhH-]+/;
const top = (state: TypstState): Frame | undefined => state.stack[state.stack.length - 1];
function blockComment(stream: StringStream, state: TypstState): string {
while (!stream.eol()) {
if (stream.match("/*")) state.comment++;
else if (stream.match("*/")) {
if (--state.comment === 0) break;
} else stream.next();
}
return "comment";
}
function comment(stream: StringStream, state: TypstState): string | null {
if (stream.match("//")) {
stream.skipToEnd();
return "comment";
}
if (stream.match("/*")) {
state.comment = 1;
return blockComment(stream, state);
}
return null;
}
function string(stream: StringStream): string {
stream.next();
let escaped = false;
for (let ch = stream.next(); ch !== undefined; ch = stream.next()) {
if (ch === '"' && !escaped) break;
escaped = !escaped && ch === "\\";
}
return "string";
}
function raw(stream: StringStream, state: TypstState): string {
const fence = (stream.match(/^`+/) as RegExpMatchArray)[0];
if (fence.length === 2) return "monospace";
if (fence.length >= 3) {
state.raw = fence;
if (!stream.match(/^[\p{L}\p{N}_-]+/u)) return rawBody(stream, state);
return "monospace";
}
while (!stream.eol()) if (stream.next() === "`") break;
return "monospace";
}
function rawBody(stream: StringStream, state: TypstState): string {
const fence = state.raw!;
while (!stream.eol()) {
if (stream.match(fence)) {
state.raw = null;
break;
}
stream.next();
}
return "monospace";
}
/** `#` followed by a keyword, a name, or a bracketed expression. */
function embed(stream: StringStream, state: TypstState): string {
stream.next();
const word = stream.match(IDENT, false) as RegExpMatchArray | null;
if (word && KEYWORDS.has(word[0])) {
stream.pos += word[0].length;
state.stack.push({ kind: "statement" });
return "keyword";
}
if (word) {
state.stack.push({ kind: "expr" });
return name(stream);
}
const ch = stream.peek();
if (ch === "(" || ch === "{") {
stream.next();
state.stack.push({ kind: "code", close: ch === "(" ? ")" : "}" });
return "keyword";
}
if (ch === "[") {
stream.next();
state.stack.push({ kind: "content" });
return "keyword";
}
if (ch === '"') return string(stream);
return "keyword";
}
/** An identifier: a function when a call or content block follows, a value otherwise. */
function name(stream: StringStream): string {
const word = (stream.match(IDENT) as RegExpMatchArray)[0];
if (ATOMS.has(word)) return "atom";
const next = stream.peek();
return next === "(" || next === "[" ? "variableName.function" : "variableName";
}
function code(stream: StringStream, state: TypstState): string | null {
if (stream.eatSpace()) return null;
const c = comment(stream, state);
if (c) return c;
const ch = stream.peek()!;
if (ch === '"') return string(stream);
if (ch === "$") {
stream.next();
state.stack.push({ kind: "math" });
return "keyword";
}
if (ch === "(" || ch === "{") {
stream.next();
state.stack.push({ kind: "code", close: ch === "(" ? ")" : "}" });
return "bracket";
}
if (ch === "[") {
stream.next();
state.stack.push({ kind: "content" });
return "bracket";
}
const frame = top(state);
if (ch === ")" || ch === "}") {
stream.next();
if (frame?.kind === "code" && frame.close === ch) state.stack.pop();
return "bracket";
}
if (stream.match(LABEL)) return "labelName";
if (stream.match(NUMBER)) return "number";
const word = stream.match(IDENT, false) as RegExpMatchArray | null;
if (word) {
if (KEYWORDS.has(word[0])) {
stream.pos += word[0].length;
return "keyword";
}
return name(stream);
}
if (stream.match(/^(?:=>|==|!=|<=|>=|\+=|-=|\*=|\/=|\.\.|[-+*/=<>.:,;!])/)) return "operator";
stream.next();
return null;
}
/** What may directly follow an embedded name: `(args)`, `[content]` or `.field`. */
function exprTail(stream: StringStream, state: TypstState): string | null | undefined {
const ch = stream.peek();
if (ch === "(") {
stream.next();
state.stack.push({ kind: "code", close: ")" });
return "bracket";
}
if (ch === "[") {
stream.next();
state.stack.push({ kind: "content" });
return "bracket";
}
if (ch === "." && stream.match(/^\.(?=[\p{L}_])/u, false)) {
stream.next();
return name(stream);
}
state.stack.pop();
return undefined;
}
function math(stream: StringStream, state: TypstState): string | null {
if (stream.eatSpace()) return null;
const c = comment(stream, state);
if (c) return c;
const ch = stream.peek()!;
if (ch === "$") {
stream.next();
state.stack.pop();
return "keyword";
}
if (ch === "#") return embed(stream, state);
if (ch === "\\") {
stream.next();
stream.next();
return "escape";
}
if (ch === '"') return string(stream);
if (stream.match(/^\d+(?:\.\d+)?/)) return "number";
if (stream.match(/^[\p{L}][\p{L}.]+/u)) return "variableName";
if (stream.match(/^[\^_/&=<>+\-*|!']/)) return "operator";
stream.next();
return null;
}
function markup(stream: StringStream, state: TypstState): string | null {
const inline = (style: string | null): string | null => {
const extra = [state.heading && "heading", state.strong && "strong", state.emph && "emphasis"].filter(Boolean);
return [...new Set([style, ...extra].filter(Boolean))].join(" ") || null;
};
if (stream.sol()) {
state.heading = false;
if (stream.match(/^\s*=+(?=\s|$)/)) {
state.heading = true;
return "heading";
}
if (stream.match(/^\s*(?:[-+]|\d+\.)(?=\s|$)/) || stream.match(/^\s*\/(?=\s)/)) return "list";
}
const c = comment(stream, state);
if (c) return c;
const ch = stream.peek()!;
switch (ch) {
case "#":
return embed(stream, state);
case "$":
stream.next();
state.stack.push({ kind: "math" });
return "keyword";
case "`":
return raw(stream, state);
case "\\":
stream.next();
if (!stream.match(/^u\{[0-9a-fA-F]+\}/)) stream.next();
return "escape";
case "]":
stream.next();
if (top(state)?.kind === "content") state.stack.pop();
return "bracket";
case "*":
case "_": {
// Inside a word, `*` and `_` are text (`snake_case`, `2*3`).
const before = stream.string.charAt(stream.pos - 1);
const after = stream.string.charAt(stream.pos + 1);
stream.next();
if (/[\p{L}\p{N}]/u.test(before) && /[\p{L}\p{N}]/u.test(after)) return inline(null);
if (ch === "*") state.strong = !state.strong;
else state.emph = !state.emph;
return inline(ch === "*" ? "strong" : "emphasis");
}
}
if (stream.match(LABEL)) return "labelName";
if (stream.match(REF)) return "labelName";
if (stream.match(URL)) return "url";
if (stream.match(/^\/ (?=[^:]*:)/) || stream.match(/^-{2,3}|^~/)) return inline(null);
if (!stream.match(MARKUP_TEXT)) stream.next();
return inline(null);
}
export const typstParser: StreamParser<TypstState> = {
name: "typst",
startState: () => ({ stack: [], strong: false, emph: false, heading: false, comment: 0, raw: null }),
copyState: (state) => ({ ...state, stack: state.stack.slice() }),
blankLine(state) {
state.strong = state.emph = false;
},
token(stream, state) {
if (state.comment) return blockComment(stream, state);
if (state.raw) return rawBody(stream, state);
let style: string | null | undefined;
do {
const frame = top(state);
if (frame?.kind === "expr") style = exprTail(stream, state);
else if (frame?.kind === "code" || frame?.kind === "statement") style = code(stream, state);
else if (frame?.kind === "math") style = math(stream, state);
else style = markup(stream, state);
} while (style === undefined);
// A statement ends with its line once its brackets are closed.
if (stream.eol()) {
while (top(state)?.kind === "expr") state.stack.pop();
if (top(state)?.kind === "statement") state.stack.pop();
}
return style;
},
languageData: {
commentTokens: { line: "//", block: { open: "/*", close: "*/" } },
closeBrackets: { brackets: ["(", "[", "{", '"', "$"] },
},
};
+5
Переглянути файл
@@ -406,6 +406,11 @@ function SessionStatus({
>
{/* Where the task works, in one quiet line like the new-task page: project (in a workspace), branch, worktree. */}
<span className={styles.where} title={task.cwd}>
{/* Which agent runs the task: with several tasks side by side, this tells their answers apart. */}
<span className={styles.fact} title={providerName(task.provider)}>
<Icon name={providerIcon(task.provider)} size={13} />
<span className={styles.factText}>{providerName(task.provider)}</span>
</span>
{project?.workspace && projectName && (
<span className={styles.fact}>
<Icon name="folder" size={13} />
+5
Переглянути файл
@@ -373,6 +373,11 @@ describe("composer UI during submission", () => {
expect(screen.getByRole("button", { name: "Send" })).toBeEnabled();
});
it("names the task's agent under the composer", () => {
render(<SessionEditor input={{ kind: SESSION_KIND, key: sessionKey("A"), data: { task: "A" } }} />);
expect(screen.getByTitle("Codex")).toHaveTextContent("Codex");
});
it("clears an unchanged session draft after only moving the caret", async () => {
const response = deferred();
backend.prompt.mockReturnValue(response.promise);
+70
Переглянути файл
@@ -0,0 +1,70 @@
import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
import type { ComponentType } from "react";
import { afterEach, beforeEach, expect, it } from "vitest";
import { DEFAULT_DEPLOYMENT_SERVER } from "@/platform/remoteSettings";
import { useContextMenuStore } from "@/ui";
import { PageContext } from "../components/context";
import { DEFAULT_SETTINGS } from "../model/schema";
import { stagedValue, useSettingsDialog } from "../model/staging";
import { DEPLOYMENT_PAGES } from "../pages/deployment";
const server = (id: string, name: string) => ({ ...DEFAULT_DEPLOYMENT_SERVER, id, name });
beforeEach(() => {
const base = structuredClone(DEFAULT_SETTINGS) as typeof DEFAULT_SETTINGS & { deployment: Record<string, unknown> };
base.deployment = { ...base.deployment, servers: [server("a", "Alpha"), server("b", "Beta")], defaultServer: "a" };
useSettingsDialog.setState({ base, globalBase: structuredClone(DEFAULT_SETTINGS), staged: {}, query: "" });
});
afterEach(() => {
act(() => useContextMenuStore.setState({ menu: null }));
cleanup();
});
function renderList() {
const page = DEPLOYMENT_PAGES.find((p) => p.id === "build.deployment")!;
const option = page
.sections!.flatMap((s) => s.options)
.find((o) => o.kind === "custom" && o.label === "Deployment servers");
const Editor = (option as unknown as { component: ComponentType }).component;
render(
<PageContext.Provider value={{ pageId: page.id, scope: "project" }}>
<Editor />
</PageContext.Provider>,
);
}
const menuItem = (label: string) => {
const item = useContextMenuStore.getState().menu!.items.find((i) => "label" in i && i.label === label) as {
run?: () => void;
disabled?: boolean;
};
return item;
};
const staged = (key: string) => stagedValue(useSettingsDialog.getState(), "project", key);
it("offers Add, Duplicate, Use as Default and Remove on a server row", () => {
renderList();
fireEvent.contextMenu(screen.getByRole("option", { name: /Beta/ }));
expect(screen.getByRole("option", { name: /Beta/ })).toHaveAttribute("aria-selected", "true");
expect(menuItem("Add")).toBeDefined();
act(() => menuItem("Use as Default").run!());
expect(staged("deployment.defaultServer")).toBe("b");
fireEvent.contextMenu(screen.getByRole("option", { name: /Beta/ }));
expect(menuItem("Use as Default").disabled).toBe(true);
act(() => menuItem("Duplicate").run!());
expect((staged("deployment.servers") as { name: string }[]).map((s) => s.name)).toEqual([
"Alpha",
"Beta",
"Beta (copy)",
]);
fireEvent.contextMenu(screen.getByRole("option", { name: /Alpha/ }));
act(() => menuItem("Remove").run!());
expect((staged("deployment.servers") as { name: string }[]).map((s) => s.name)).toEqual(["Beta", "Beta (copy)"]);
});
it("only adds from the empty part of the list", () => {
renderList();
fireEvent.contextMenu(screen.getByRole("listbox", { name: "Deployment servers" }));
const labels = useContextMenuStore.getState().menu!.items.map((i) => ("label" in i ? i.label : i.kind));
expect(labels).toEqual(["Add"]);
});
+37
Переглянути файл
@@ -0,0 +1,37 @@
import { beforeEach, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen } from "@testing-library/react";
const { choose, tauri } = vi.hoisted(() => ({ choose: vi.fn(), tauri: { on: true } }));
vi.mock("@/platform/choosePath", () => ({ choosePath: choose }));
vi.mock("@/platform/ipc", async (original) => ({
...(await original<typeof import("@/platform/ipc")>()),
isTauri: () => tauri.on,
}));
import { GlobListEditor } from "../components/Form";
beforeEach(() => {
choose.mockReset();
tauri.on = true;
});
const browse = { directory: true, title: "Choose Include Path" };
it("adds the folder picked in the chooser and leaves the list alone when it is cancelled", async () => {
const onChange = vi.fn();
choose.mockResolvedValueOnce("/opt/platform").mockResolvedValueOnce(null);
render(<GlobListEditor value={["/a"]} onChange={onChange} browse={browse} aria-label="Include paths" />);
await act(async () => fireEvent.click(screen.getByRole("button", { name: "Add" })));
expect(choose).toHaveBeenCalledWith({ directory: true, title: "Choose Include Path" });
expect(onChange).toHaveBeenCalledWith(["/a", "/opt/platform"]);
await act(async () => fireEvent.click(screen.getByRole("button", { name: "Add" })));
expect(onChange).toHaveBeenCalledTimes(1);
expect(screen.queryByRole("textbox")).not.toBeInTheDocument();
});
it("types the path inline without a chooser", async () => {
tauri.on = false;
render(<GlobListEditor value={[]} onChange={vi.fn()} browse={browse} itemLabel="Include path" />);
await act(async () => fireEvent.click(screen.getByRole("button", { name: "Add" })));
expect(choose).not.toHaveBeenCalled();
expect(screen.getByRole("textbox", { name: "Include path" })).toBeInTheDocument();
});
+19 -6
Переглянути файл
@@ -7,6 +7,8 @@ import { useId, useRef, useState, type KeyboardEvent, type ReactNode } from "rea
import clsx from "clsx";
import { Checkbox, IconButton, Input, Select as UiSelect, type SelectOption, T } from "@/ui";
import { tx, useTx } from "@/platform/i18n";
import { choosePath } from "@/platform/choosePath";
import { isTauri } from "@/platform/ipc";
import { highlightIndices } from "../model/pages";
import { HEX_COLOR } from "../model/schema";
import { useLabelMatch, useSearchQuery, useSetting } from "./context";
@@ -303,6 +305,8 @@ export interface GlobListEditorProps {
emptyText?: string;
/** Accessible name of the inline editor. */
itemLabel?: string;
/** Entries are paths: + opens this chooser (Edit still takes typing). */
browse?: { directory: boolean; title: string };
}
/** Editable list of glob patterns (+ / − / edit toolbar, inline editing); also plain string lists. */
@@ -312,6 +316,7 @@ export function GlobListEditor({
placeholder = "**/pattern",
emptyText = "No patterns",
itemLabel = "Pattern",
browse,
...aria
}: GlobListEditorProps) {
const [selected, setSelected] = useState<number | null>(null);
@@ -340,6 +345,19 @@ export function GlobListEditor({
setEditing(null);
};
const add = async () => {
// Outside the desktop app there is no chooser: type the path instead.
if (!browse || !isTauri()) {
setEditing({ index: value.length, text: "" });
return;
}
const picked = await choosePath({ ...browse, title: tx(browse.title) });
if (!picked) return;
const next = [...new Set([...value, picked])];
onChange(next);
setSelected(next.indexOf(picked));
};
const remove = () => {
if (selected === null) return;
const next = value.filter((_, i) => i !== selected);
@@ -380,12 +398,7 @@ export function GlobListEditor({
return (
<div className={styles.globEditor}>
<div className={styles.listToolbar} role="toolbar" aria-controls={listId}>
<IconButton
icon="plus"
title="Add"
size="small"
onClick={() => setEditing({ index: value.length, text: "" })}
/>
<IconButton icon="plus" title="Add" size="small" onClick={() => void add()} />
<IconButton icon="minus" title="Remove" size="small" disabled={selected === null} onClick={remove} />
<IconButton
icon="edit"
+1
Переглянути файл
@@ -221,6 +221,7 @@ export function PhpPage() {
emptyText="No include paths"
itemLabel="Include path"
aria-label="Include paths"
browse={{ directory: true, title: "Choose Include Path" }}
/>
</Row>
<Row
+62 -6
Переглянути файл
@@ -3,7 +3,7 @@
* mappings, excluded remote paths) and the transfer options. Consumed by the
* deployment feature and `ide-remote` (automatic upload, remote delete).
*/
import { useEffect, useId, useState, type KeyboardEvent } from "react";
import { useEffect, useId, useState, type KeyboardEvent, type MouseEvent as ReactMouseEvent } from "react";
import clsx from "clsx";
import { call, commands, IpcError, isTauri, type FsConnection, type RemoteEntry } from "@/platform/ipc";
import { useTx, tx, txTemplate } from "@/platform/i18n";
@@ -30,6 +30,7 @@ import {
Spinner,
T,
Tabs,
type MenuItem,
} from "@/ui";
import { GlobListEditor, Row } from "../components/Form";
import { SshConfigSelect, useSshConfigs } from "../components/SshConfigSelect";
@@ -769,6 +770,26 @@ function DeploymentServersEditor() {
setGroups([...groupList, group]);
setSelected({ kind: "group", id: group.id });
};
const removeTarget = (target: Selection) => {
if (!target) return;
if (target.kind === "group") {
const group = groupList.find((g) => g.id === target.id);
if (!group) return;
const index = groupList.indexOf(group);
const rest = groupList.filter((g) => g.id !== group.id);
setGroups(rest);
const next = rest[Math.min(index, rest.length - 1)] ?? null;
setSelected(next ? { kind: "group", id: next.id } : list[0] ? { kind: "server", id: list[0].id } : null);
return;
}
const server = list.find((s) => s.id === target.id);
if (!server) return;
const index = list.indexOf(server);
const rest = list.filter((s) => s.id !== server.id);
commit(rest);
const next = rest[Math.min(index, rest.length - 1)] ?? null;
setSelected(next ? { kind: "server", id: next.id } : null);
};
const remove = () => {
if (currentGroup) {
const index = groupList.indexOf(currentGroup);
@@ -786,6 +807,34 @@ function DeploymentServersEditor() {
setSelected(next ? { kind: "server", id: next.id } : null);
};
const isSelected = (kind: "server" | "group", id: string) => selected?.kind === kind && selected.id === id;
const addItems: MenuItem[] = [
{ label: "Server", icon: "web", run: () => add() },
{ label: "Server Group", icon: "folder", run: addGroup },
];
// Right-click on a row works on that row (it is selected first); on the empty list it only adds.
const rowMenu = (e: ReactMouseEvent, target: Selection) => {
e.preventDefault();
e.stopPropagation();
setSelected(target);
const server = target?.kind === "server" ? list.find((s) => s.id === target.id) : undefined;
showContextMenu(e, [
{ label: "Add", icon: "plus", submenu: addItems },
...(server
? [
{ label: "Duplicate", icon: "copy", run: () => add(server) } as MenuItem,
{
label: "Use as Default",
icon: "check",
disabled: server.id === effectiveDefault,
run: () => setDefaultServer(server.id),
} as MenuItem,
]
: []),
{ kind: "separator" },
// `remove` acts on the selection, which the state update above has not applied yet.
{ label: "Remove", icon: "minus", run: () => removeTarget(target) },
]);
};
return (
<div className={styles.layout}>
@@ -797,10 +846,7 @@ function DeploymentServersEditor() {
size="small"
onClick={(e) => {
const r = e.currentTarget.getBoundingClientRect();
showContextMenu({ x: r.left, y: r.bottom }, [
{ label: "Server", icon: "web", run: () => add() },
{ label: "Server Group", icon: "folder", run: addGroup },
]);
showContextMenu({ x: r.left, y: r.bottom }, addItems);
}}
/>
<IconButton icon="minus" title="Remove" size="small" disabled={!current && !currentGroup} onClick={remove} />
@@ -819,7 +865,15 @@ function DeploymentServersEditor() {
onClick={() => current && setDefaultServer(current.id)}
/>
</div>
<div className={styles.serverList} role="listbox" aria-label={tx("Deployment servers")}>
<div
className={styles.serverList}
role="listbox"
aria-label={tx("Deployment servers")}
onContextMenu={(e) => {
e.preventDefault();
showContextMenu(e, [{ label: "Add", icon: "plus", submenu: addItems }]);
}}
>
{list.length === 0 && groupList.length === 0 && (
<div className={styles.empty}>
<T>No servers. Click + to add one.</T>
@@ -832,6 +886,7 @@ function DeploymentServersEditor() {
aria-selected={isSelected("group", g.id)}
className={clsx(styles.serverRow, isSelected("group", g.id) && styles.serverSelected)}
onMouseDown={() => setSelected({ kind: "group", id: g.id })}
onContextMenu={(e) => rowMenu(e, { kind: "group", id: g.id })}
>
<Icon name="folder" />
<span className={styles.serverName}>{g.name || g.id}</span>
@@ -845,6 +900,7 @@ function DeploymentServersEditor() {
aria-selected={isSelected("server", s.id)}
className={clsx(styles.serverRow, isSelected("server", s.id) && styles.serverSelected)}
onMouseDown={() => setSelected({ kind: "server", id: s.id })}
onContextMenu={(e) => rowMenu(e, { kind: "server", id: s.id })}
>
<Icon name="web" />
<span className={clsx(styles.serverName, s.id === effectiveDefault && styles.default)}>
+2 -1
Переглянути файл
@@ -2381,5 +2381,6 @@
"Commit Message Generation": "Commit Message Generation",
"Instructions for Generate Commit Message with Agent": "Instructions for Generate Commit Message with Agent",
"Added to the agent's prompt, e.g. a commit format, issue key prefixes or the language to write in.": "Added to the agent's prompt, e.g. a commit format, issue key prefixes or the language to write in.",
"Use Conventional Commits (feat:, fix:, …) and start with the issue key if the branch has one.": "Use Conventional Commits (feat:, fix:, …) and start with the issue key if the branch has one."
"Use Conventional Commits (feat:, fix:, …) and start with the issue key if the branch has one.": "Use Conventional Commits (feat:, fix:, …) and start with the issue key if the branch has one.",
"Choose Include Path": "Choose Include Path"
}
+2 -1
Переглянути файл
@@ -8759,5 +8759,6 @@
"Commit Message Generation": "提交信息生成",
"Instructions for Generate Commit Message with Agent": "用 Agent 生成提交信息时的要求",
"Added to the agent's prompt, e.g. a commit format, issue key prefixes or the language to write in.": "会加到 Agent 的提示词里,例如提交格式、问题编号前缀或使用的语言。",
"Use Conventional Commits (feat:, fix:, …) and start with the issue key if the branch has one.": "使用 Conventional Commits(feat:、fix: 等),分支带问题编号时以它开头。"
"Use Conventional Commits (feat:, fix:, …) and start with the issue key if the branch has one.": "使用 Conventional Commits(feat:、fix: 等),分支带问题编号时以它开头。",
"Choose Include Path": "选择包含路径"
}
+2
Переглянути файл
@@ -180,6 +180,7 @@ const ICONS = {
"file-godot": "openidea/fileTypes/godot",
"file-gdshader": "openidea/fileTypes/gdshader",
"file-asciidoc": "openidea/fileTypes/asciidoc",
"file-typst": "openidea/fileTypes/typst",
"file-d": "openidea/fileTypes/d",
"file-gherkin": "openidea/fileTypes/gherkin",
"file-prisma": "openidea/fileTypes/prisma",
@@ -1160,6 +1161,7 @@ const EXT_ICONS = table({
"file-godot": "tscn tres godot import",
"file-gdshader": "gdshader gdshaderinc",
"file-asciidoc": "adoc asciidoc",
"file-typst": "typ",
"file-d": "d di",
"file-gherkin": "feature",
"file-prisma": "prisma",
+3
Переглянути файл
@@ -0,0 +1,3 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<g stroke-linejoin="round"><path d="M14 4C14 2.89543 13.1046 2 12 2H4C2.89543 2 2 2.89543 2 4V12C2 13.1046 2.89543 14 4 14H12C13.1046 14 14 13.1046 14 12V4Z" fill="#239DAD"/><path d="M7 4V10C7 11.1046 7.89543 12 9 12H10.5" stroke="#2B2D30" stroke-linecap="round"/><path d="M5 6.5H10.5" stroke="#2B2D30" stroke-linecap="round"/></g>
</svg>

Після

Ширина:  |  Висота:  |  Розмір: 435 B

+3
Переглянути файл
@@ -0,0 +1,3 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<g stroke-linejoin="round"><path d="M14 4C14 2.89543 13.1046 2 12 2H4C2.89543 2 2 2.89543 2 4V12C2 13.1046 2.89543 14 4 14H12C13.1046 14 14 13.1046 14 12V4Z" fill="#4DB8C7"/><path d="M7 4V10C7 11.1046 7.89543 12 9 12H10.5" stroke="#2B2D30" stroke-linecap="round"/><path d="M5 6.5H10.5" stroke="#2B2D30" stroke-linecap="round"/></g>
</svg>

Після

Ширина:  |  Висота:  |  Розмір: 435 B