From 9ee8f67e9f1f76de877d2b8f4e6462495fa237dc Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Sun, 29 Nov 2026 14:23:45 +0900 Subject: [PATCH] feat(languages): Jinja2 Template language for .jinja, .jinja2 and .j2 files (#6645) .jinja, .jinja2 and .j2 files opened as Plain Text. They now open as Jinja2 templates, with the extension before them deciding the content between the tags: Jinja2 HTML (.html.j2, .html.jinja, .htm.*) gets the HTML language server, Emmet, tag closing and linked tags like Django templates; any other name (nginx.conf.j2, values.yaml.j2, base.jinja) is a Jinja2 Template over plain text without HTML tooling. Both use @codemirror/lang-jinja (now a direct dependency, the same 6.0.1 already in the lockfile): highlighting, folding and indentation of block statements, completion of tags, filters and tests, and tag matching. The file icon follows the extension before .j2, and breakpoints in a file typed as a Jinja language turn on debugpy's jinja support. Closes #6644 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- crates/ide-language/src/registry.rs | 18 +++ docs/en/languages/index.mdx | 2 + docs/en/languages/python.mdx | 4 + docs/zh/languages/index.mdx | 2 + docs/zh/languages/python.mdx | 4 + languages/jinja-html.toml | 16 +++ languages/jinja.toml | 6 + package.json | 1 + pnpm-lock.yaml | 3 + src/editor/core/cm/jinja.test.ts | 123 ++++++++++++++++++ src/editor/core/cm/jinja.ts | 43 ++++++ src/editor/core/cm/languages.ts | 3 + src/editor/core/cm/prefs.ts | 1 + src/editor/lsp/syntaxErrors.ts | 4 +- .../debugger/__tests__/launch.test.ts | 3 + .../__tests__/templateBreakpoints.test.ts | 23 +++- .../debugger/breakpoints/languages.ts | 17 ++- .../templates/__tests__/emmet.test.ts | 4 + src/features/templates/emmet/model.ts | 10 +- src/test/syntax.test.ts | 1 + src/ui/icons.test.tsx | 5 + src/ui/icons.tsx | 9 +- 22 files changed, 288 insertions(+), 14 deletions(-) create mode 100644 languages/jinja-html.toml create mode 100644 languages/jinja.toml create mode 100644 src/editor/core/cm/jinja.test.ts create mode 100644 src/editor/core/cm/jinja.ts diff --git a/crates/ide-language/src/registry.rs b/crates/ide-language/src/registry.rs index f66505dfd..f6b9a459e 100644 --- a/crates/ide-language/src/registry.rs +++ b/crates/ide-language/src/registry.rs @@ -50,6 +50,8 @@ const BUILTIN: &[(&str, &str)] = &[ ("ignore", include_str!("../../../languages/ignore.toml")), ("ini", include_str!("../../../languages/ini.toml")), ("java", include_str!("../../../languages/java.toml")), + ("jinja", include_str!("../../../languages/jinja.toml")), + ("jinja-html", include_str!("../../../languages/jinja-html.toml")), ("javascript", include_str!("../../../languages/javascript.toml")), ("javascriptreact", include_str!("../../../languages/javascriptreact.toml")), ("json", include_str!("../../../languages/json.toml")), @@ -506,6 +508,7 @@ mod tests { "Java", "JavaScript", "Jinja", + "Jinja HTML", "JSON", "JSX", "LESS", @@ -1011,6 +1014,21 @@ mod tests { assert!(reg.is_framework_marker(&root.join("src/manage.py"))); } + #[test] + fn jinja_templates_are_html_only_by_inner_extension() { + let reg = reg(); + let detect = |file: &str| reg.detect(Path::new(file), None).as_str().to_owned(); + assert_eq!(detect("templates/base.jinja"), "jinja"); + assert_eq!(detect("roles/web/templates/nginx.conf.J2"), "jinja"); + assert_eq!(detect("templates/values.yaml.j2"), "jinja"); + assert_eq!(detect("templates/page.html.jinja2"), "jinja-html"); + assert_eq!(detect("templates/page.HTML.j2"), "jinja-html"); + assert_eq!(detect("templates/mail.htm.jinja"), "jinja-html"); + // The HTML server only serves the HTML ones. + let servers = |id: &str| reg.get(&LanguageId::new(id)).unwrap().language_servers.len(); + assert_eq!((servers("jinja"), servers("jinja-html")), (0, 1)); + } + #[test] fn helm_charts_make_yaml_and_notes_in_templates_folders_helm_templates() { let reg = reg(); diff --git a/docs/en/languages/index.mdx b/docs/en/languages/index.mdx index 33928ad72..909aff666 100644 --- a/docs/en/languages/index.mdx +++ b/docs/en/languages/index.mdx @@ -132,6 +132,8 @@ The table lists every built-in language definition. Server and debugger names in | Java | `java` | `.java` | Yes | Yes | **jdtls** → **java-analyzer** → **kmp-lsp** | **java-debug** | | JavaScript | `javascript` | `.js`, `.mjs`, `.cjs` | Yes | Yes | **vtsls** → **typescript-language-server** + **oxlint** + **biome** | **js-debug** | | JavaScript JSX | `javascriptreact` | `.jsx` | Yes | Yes | **vtsls** → **typescript-language-server** + **oxlint** + **biome** | **js-debug** | +| Jinja2 Template | `jinja` | `.jinja`, `.jinja2`, `.j2` | Yes | — | — | — | +| Jinja2 HTML | `jinja-html` | `.html.j2`, `.html.jinja`, `.html.jinja2` | Yes | Yes | **vscode-html-language-server** | — | | JSON | `json` | `.json`, `.geojson`, `.topojson`, `.webmanifest`, `.har`, … | Yes | Yes | **vscode-json-language-server** + **biome** | — | | JSON with Comments | `jsonc` | `.jsonc`, `.code-workspace`, `.code-snippets` | Yes | Yes | **vscode-json-language-server** + **biome** | — | | JSP | `jsp` | `.jsp`, `.jspx`, `.jspf`, `.jsph`, `.tag`, … | Yes | — | — | — | diff --git a/docs/en/languages/python.mdx b/docs/en/languages/python.mdx index 5e007435a..535304425 100644 --- a/docs/en/languages/python.mdx +++ b/docs/en/languages/python.mdx @@ -179,6 +179,10 @@ With **Django Template LSP** (`djlsp`, installed from **Settings › Languages & An HTML file elsewhere with Django tags shows a banner that switches it to Django Template or keeps it as HTML; either choice is the file's **Override File Type**. +### Jinja2 templates + +`.jinja`, `.jinja2` and `.j2` files open as Jinja2 templates. The extension before them decides what is between the tags: `page.html.j2`, `base.html.jinja` and the other `.html.*` / `.htm.*` names are **Jinja2 HTML** files, any other name (`nginx.conf.j2`, `values.yaml.jinja2`, `base.jinja`) is a **Jinja2 Template** of plain text. Tags, expressions, filters and comments are highlighted, block statements (`{% block %}`, `{% if %}`, `{% for %}`, `{% macro %}` and the others) fold and indent their content, and Jinja's tags, filters and tests complete. Typing `%` between braces makes `{% %}`. **Comment with Line Comment** and **Comment with Block Comment** use `{# … #}`. In Jinja2 HTMLs the markup is highlighted too, tags close and rename in pairs, and the HTML language server and Emmet work between the template tags. A Python debug configuration stops at breakpoints in both. To open another file as a Jinja2 template, such as a `base.jinja` that holds HTML, use its **Override File Type**. + ## Limitations - Only one type checker runs at a time. Ruff runs only in projects with a Ruff configuration. diff --git a/docs/zh/languages/index.mdx b/docs/zh/languages/index.mdx index 4c35c7fe7..b1c85a3dc 100644 --- a/docs/zh/languages/index.mdx +++ b/docs/zh/languages/index.mdx @@ -127,6 +127,8 @@ IDE 安装工具从不需要 `sudo`。工具装在本地数据目录下 IDE 自 | Java | `java` | `.java` | 是 | 是 | **jdtls** → **java-analyzer** → **kmp-lsp** | **java-debug** | | JavaScript | `javascript` | `.js`, `.mjs`, `.cjs` | 是 | 是 | **vtsls** → **typescript-language-server** + **oxlint** + **biome** | **js-debug** | | JavaScript JSX | `javascriptreact` | `.jsx` | 是 | 是 | **vtsls** → **typescript-language-server** + **oxlint** + **biome** | **js-debug** | +| Jinja2 Template | `jinja` | `.jinja`, `.jinja2`, `.j2` | 是 | — | — | — | +| Jinja2 HTML | `jinja-html` | `.html.j2`、`.html.jinja`、`.html.jinja2` | 是 | 是 | **vscode-html-language-server** | — | | JSON | `json` | `.json`, `.geojson`, `.topojson`, `.webmanifest`, `.har`, … | 是 | 是 | **vscode-json-language-server** + **biome** | — | | JSON with Comments | `jsonc` | `.jsonc`, `.code-workspace`, `.code-snippets` | 是 | 是 | **vscode-json-language-server** + **biome** | — | | JSP | `jsp` | `.jsp`, `.jspx`, `.jspf`, `.jsph`, `.tag`, … | 是 | — | — | — | diff --git a/docs/zh/languages/python.mdx b/docs/zh/languages/python.mdx index ce289e8b5..bcd0a874e 100644 --- a/docs/zh/languages/python.mdx +++ b/docs/zh/languages/python.mdx @@ -179,6 +179,10 @@ Django 项目(上层目录有 `manage.py`)中 `templates` 目录里的 HTML 其他位置含有 Django 标签的 HTML 文件会显示一个横幅,可以切换为 Django Template 或保留为 HTML;两种选择都会成为该文件的 **覆盖文件类型**。 +### Jinja2 模板 + +`.jinja`、`.jinja2` 和 `.j2` 文件以 Jinja2 模板打开,标签之间是什么由前面的扩展名决定:`page.html.j2`、`base.html.jinja` 以及其他 `.html.*` / `.htm.*` 文件是 **Jinja2 HTML**,其他文件(`nginx.conf.j2`、`values.yaml.jinja2`、`base.jinja`)是纯文本的 **Jinja2 Template**。标签、表达式、过滤器和注释会高亮,块语句(`{% block %}`、`{% if %}`、`{% for %}`、`{% macro %}` 等)可以折叠并缩进内容,Jinja 的标签、过滤器和测试可以补全。在花括号之间输入 `%` 会变成 `{% %}`。**使用行注释** 和 **使用块注释** 都用 `{# … #}`。在 Jinja2 HTML 中,标记也会高亮,标签成对闭合、成对重命名,HTML 语言服务器和 Emmet 在模板标签之间照常工作。两种模板中的断点都会让 Python 调试配置暂停。要把其他文件当作 Jinja2 模板打开(例如内容是 HTML 的 `base.jinja`),使用该文件的 **覆盖文件类型**。 + ## 限制 - 同一时间只运行一个类型检查器。Ruff 只在有 Ruff 配置的项目中运行。 diff --git a/languages/jinja-html.toml b/languages/jinja-html.toml new file mode 100644 index 000000000..335633e0e --- /dev/null +++ b/languages/jinja-html.toml @@ -0,0 +1,16 @@ +id = "jinja-html" +name = "Jinja2 HTML" +extensions = ["html.jinja", "htm.jinja", "html.jinja2", "htm.jinja2", "html.j2", "htm.j2"] +block-comment = ["{#", "#}"] +indent = { tab-size = 2, insert-spaces = true } +ui-mode = "Jinja HTML" +tree-sitter = "html" + +# The markup between the template tags: completion and hover of tags and +# attributes. No formatter: HTML formatters reflow template tags. +[[language-servers]] +name = "vscode-html-language-server" +command = "vscode-html-language-server" +args = ["--stdio"] +initialization-options = { embeddedLanguages = { css = true, javascript = true } } +install-hint = "npm i -g vscode-langservers-extracted" diff --git a/languages/jinja.toml b/languages/jinja.toml new file mode 100644 index 000000000..45035f787 --- /dev/null +++ b/languages/jinja.toml @@ -0,0 +1,6 @@ +id = "jinja" +name = "Jinja2 Template" +extensions = ["jinja", "jinja2", "j2"] +block-comment = ["{#", "#}"] +indent = { tab-size = 2, insert-spaces = true } +ui-mode = "Jinja" diff --git a/package.json b/package.json index ff8437521..a484b76e3 100644 --- a/package.json +++ b/package.json @@ -52,6 +52,7 @@ "@codemirror/lang-html": "^6.4.12", "@codemirror/lang-java": "^6.0.2", "@codemirror/lang-javascript": "^6.2.5", + "@codemirror/lang-jinja": "^6.0.1", "@codemirror/lang-less": "^6.0.2", "@codemirror/lang-markdown": "^6.5.2", "@codemirror/lang-sass": "^6.0.2", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 863cf9b17..0255a1503 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -31,6 +31,9 @@ importers: '@codemirror/lang-javascript': specifier: ^6.2.5 version: 6.2.5 + '@codemirror/lang-jinja': + specifier: ^6.0.1 + version: 6.0.1 '@codemirror/lang-less': specifier: ^6.0.2 version: 6.0.2 diff --git a/src/editor/core/cm/jinja.test.ts b/src/editor/core/cm/jinja.test.ts new file mode 100644 index 000000000..2140953ae --- /dev/null +++ b/src/editor/core/cm/jinja.test.ts @@ -0,0 +1,123 @@ +import { describe, expect, it } from "vitest"; +import { EditorSelection, EditorState } from "@codemirror/state"; +import { EditorView } from "@codemirror/view"; +import { foldable, indentUnit, matchBrackets, type LanguageSupport } from "@codemirror/language"; +import { classHighlighter, highlightTree } from "@lezer/highlight"; +import { completedSyntaxState, completedSyntaxTree } from "@/test/syntax"; +import { commentLine } from "./comments"; +import { linkedTags } from "./linkedTags"; +import { findLanguageDescription, loadSupport } from "./languages"; +import { jinja, jinjaHtml } from "./jinja"; + +const html = jinjaHtml(); +const text = jinja(); + +function state(doc: string, support: LanguageSupport = html, at = 0): EditorState { + return completedSyntaxState( + EditorState.create({ doc, selection: EditorSelection.cursor(at), extensions: [support, indentUnit.of(" ")] }), + ); +} + +/** `text:class` of the styled tokens of `doc`, markup included. */ +function tokens(doc: string, support: LanguageSupport = html): string[] { + const out: string[] = []; + highlightTree(completedSyntaxTree(state(doc, support)), classHighlighter, (from, to, cls) => + out.push(`${doc.slice(from, to)}:${cls}`), + ); + return out; +} + +/** Types `ch` at `|` of `doc` through the real input handlers; the result with `|` at the caret. */ +function type(doc: string, ch: string, support: LanguageSupport = html): string { + const at = doc.indexOf("|"); + const v = new EditorView({ state: state(doc.replace("|", ""), support, at) }); + const insert = () => v.state.update(v.state.replaceSelection(ch), { userEvent: "input.type" }); + if (!v.state.facet(EditorView.inputHandler).some((h) => h(v, at, at, ch, insert))) v.dispatch(insert()); + const head = v.state.selection.main.head; + const out = v.state.doc.toString(); + v.destroy(); + return out.slice(0, head) + "|" + out.slice(head); +} + +function commented(doc: string, support: LanguageSupport): string { + const v = new EditorView({ state: state(doc, support) }); + v.dispatch({ selection: EditorSelection.range(0, v.state.doc.length) }); + commentLine(v); + return v.state.doc.toString(); +} + +describe("Jinja2 templates", () => { + it("are the modes of the backend's two Jinja languages", async () => { + expect(findLanguageDescription("Jinja", "/p/nginx.conf.j2")?.name).toBe("Jinja"); + expect(findLanguageDescription("Jinja HTML", "/p/page.html.j2")?.name).toBe("Jinja HTML"); + expect((await loadSupport(findLanguageDescription("Jinja HTML", "/p/a.html.j2")!))?.language.name).toBe("jinja"); + }); + + it("highlights the template layer and the markup around it", () => { + const out = tokens("{% if user %}{{ user.name|upper }}{% endif %}{# note #}"); + expect(out).toEqual( + expect.arrayContaining([ + "a:tok-typeName", + "href:tok-propertyName", + "if:tok-keyword", + "user:tok-variableName", + "name:tok-propertyName", + "upper:tok-variableName2", + " note :tok-comment", + ]), + ); + }); + + it("reads other templates as text with template tags", () => { + const out = tokens("server {\n listen {{ port }};\n # x\n}", text); + expect(out).toEqual(["{{:tok-punctuation", "port:tok-variableName", "}}:tok-punctuation"]); + }); + + it("closes tags only in HTML templates", () => { + expect(type("
{|}
", "%")).toBe("{%|%}
"); + expect(type("listen {|};", "%", text)).toBe("listen {%|%};"); + }); + + it("matches the braces of a tag", () => { + const doc = "{% if a %}x{% endif %}"; + expect(matchBrackets(state(doc, text), 0, 1)).toMatchObject({ + matched: true, + start: { from: 0, to: 2 }, + end: { from: 8, to: 10 }, + }); + }); + + it("folds a block statement's content", () => { + const doc = "{% block content %}\nx
\n{% endblock %}"; + for (const support of [html, text]) + expect(foldable(state(doc, support), 0, doc.indexOf("\n"))).toEqual({ + from: doc.indexOf("%}") + 2, + to: doc.indexOf("{% endblock"), + }); + }); + + it("comments lines out with {# #}", () => { + expect(commented("a
", html)).toBe("{#a
#}"); + expect(commented("listen 80;", text)).toBe("{# listen 80; #}"); + }); + + it("renames the closing tag while the opening one is typed", () => { + const doc = '{% if a %}