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
This commit is contained in:
l0ng-ai
2026-11-17 22:44:13 +08:00
committed by GitHub
parent 2278cf6e8f
commit 7e5277eaa6
11 changed files with 428 additions and 0 deletions
+2
View File
@@ -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",
+22
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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)"
+54
View File
@@ -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 <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");
});
});
+5
View File
@@ -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"],
+321
View File
@@ -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: ["(", "[", "{", '"', "$"] },
},
};
+2
View File
@@ -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
View File
@@ -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>

After

Width:  |  Height:  |  Size: 435 B

+3
View File
@@ -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>

After

Width:  |  Height:  |  Size: 435 B