From 7e5277eaa6cc59bd14b5dba968e1758093c75b7b Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Tue, 17 Nov 2026 22:44:13 +0800 Subject: [PATCH] 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 --- crates/ide-language/src/registry.rs | 2 + crates/ide-tools/src/registry.rs | 22 ++ docs/en/languages/index.mdx | 1 + docs/zh/languages/index.mdx | 1 + languages/typst.toml | 14 + src/editor/core/cm/languages.test.ts | 54 ++++ src/editor/core/cm/languages.ts | 5 + src/editor/core/cm/typst.ts | 321 +++++++++++++++++++++++ src/ui/icons.tsx | 2 + src/ui/openidea/fileTypes/typst.svg | 3 + src/ui/openidea/fileTypes/typst_dark.svg | 3 + 11 files changed, 428 insertions(+) create mode 100644 languages/typst.toml create mode 100644 src/editor/core/cm/typst.ts create mode 100644 src/ui/openidea/fileTypes/typst.svg create mode 100644 src/ui/openidea/fileTypes/typst_dark.svg diff --git a/crates/ide-language/src/registry.rs b/crates/ide-language/src/registry.rs index 82f42fb29..236e27cd6 100644 --- a/crates/ide-language/src/registry.rs +++ b/crates/ide-language/src/registry.rs @@ -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", diff --git a/crates/ide-tools/src/registry.rs b/crates/ide-tools/src/registry.rs index 2a3829043..adcebe23e 100644 --- a/crates/ide-tools/src/registry.rs +++ b/crates/ide-tools/src/registry.rs @@ -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", diff --git a/docs/en/languages/index.mdx b/docs/en/languages/index.mdx index d514db656..c43bc68fe 100644 --- a/docs/en/languages/index.mdx +++ b/docs/en/languages/index.mdx @@ -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** | — | diff --git a/docs/zh/languages/index.mdx b/docs/zh/languages/index.mdx index 2ad1cc9f3..50859eb9f 100644 --- a/docs/zh/languages/index.mdx +++ b/docs/zh/languages/index.mdx @@ -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** | — | diff --git a/languages/typst.toml b/languages/typst.toml new file mode 100644 index 000000000..abb7c3a7a --- /dev/null +++ b/languages/typst.toml @@ -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)" diff --git a/src/editor/core/cm/languages.test.ts b/src/editor/core/cm/languages.test.ts index 6100b0b79..9e9ef4c23 100644 --- a/src/editor/core/cm/languages.test.ts +++ b/src/editor/core/cm/languages.test.ts @@ -438,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 ", + "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", + ":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"); + }); }); diff --git a/src/editor/core/cm/languages.ts b/src/editor/core/cm/languages.ts index 8a10d1111..dfff75aeb 100644 --- a/src/editor/core/cm/languages.ts +++ b/src/editor/core/cm/languages.ts @@ -114,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"], diff --git a/src/editor/core/cm/typst.ts b/src/editor/core/cm/typst.ts new file mode 100644 index 000000000..52d0eb53a --- /dev/null +++ b/src/editor/core/cm/typst.ts @@ -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 = { + 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: ["(", "[", "{", '"', "$"] }, + }, +}; diff --git a/src/ui/icons.tsx b/src/ui/icons.tsx index ad60d39cb..5826151e5 100644 --- a/src/ui/icons.tsx +++ b/src/ui/icons.tsx @@ -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", diff --git a/src/ui/openidea/fileTypes/typst.svg b/src/ui/openidea/fileTypes/typst.svg new file mode 100644 index 000000000..d865d4ec1 --- /dev/null +++ b/src/ui/openidea/fileTypes/typst.svg @@ -0,0 +1,3 @@ + + + diff --git a/src/ui/openidea/fileTypes/typst_dark.svg b/src/ui/openidea/fileTypes/typst_dark.svg new file mode 100644 index 000000000..fb87cfa67 --- /dev/null +++ b/src/ui/openidea/fileTypes/typst_dark.svg @@ -0,0 +1,3 @@ + + +