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 <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-11-29 13:23:45 +08:00
1 джерело 5b486f1588
коміт 9ee8f67e9f
22 files changed
+288 -14

No files matched your search

+18
Переглянути файл
@@ -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();
+2
Переглянути файл
@@ -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 | — | — | — |
+4
Переглянути файл
@@ -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.
+2
Переглянути файл
@@ -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`, … | 是 | — | — | — |
+4
Переглянути файл
@@ -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 配置的项目中运行。
+16
Переглянути файл
@@ -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"
+6
Переглянути файл
@@ -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"
+1
Переглянути файл
@@ -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",
Створено
+3
Переглянути файл
@@ -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
+123
Переглянути файл
@@ -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("<a href=\"{{ url_for('home') }}\">{% if user %}{{ user.name|upper }}{% endif %}</a>{# 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 # <b>x</b>\n}", text);
expect(out).toEqual(["{{:tok-punctuation", "port:tok-variableName", "}}:tok-punctuation"]);
});
it("closes tags only in HTML templates", () => {
expect(type("<div|", ">")).toBe("<div>|</div>");
expect(type("#include <vector|", ">", text)).toBe("#include <vector>|");
});
it("makes `{% %}` of `%` between braces", () => {
expect(type("<p>{|}</p>", "%")).toBe("<p>{%|%}</p>");
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 %}\n <p>x</p>\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("<p>a</p>", html)).toBe("{# <p>a</p> #}");
expect(commented("listen 80;", text)).toBe("{# listen 80; #}");
});
it("renames the closing tag while the opening one is typed", () => {
const doc = '{% if a %}<div class="x">y</div>{% endif %}';
const at = doc.indexOf(" class");
const s = completedSyntaxState(
EditorState.create({ doc, selection: EditorSelection.cursor(at), extensions: [html, linkedTags] }),
);
const v = new EditorView({ state: s });
v.dispatch({
changes: { from: at, insert: "s" },
selection: EditorSelection.cursor(at + 1),
userEvent: "input.type",
});
expect(v.state.doc.toString()).toBe('{% if a %}<divs class="x">y</divs>{% endif %}');
});
});
+43
Переглянути файл
@@ -0,0 +1,43 @@
/**
* Jinja2 templates: `@codemirror/lang-jinja` (template tags, variables and
* comments; block folding and indentation; completion of tags, filters and
* tests) over plain text, or over HTML for `.html.j2` and the like, with
* `{# #}` comments in the markup too.
*/
import { LanguageSupport, StreamLanguage } from "@codemirror/language";
import { jinja as jinjaSupport } from "@codemirror/lang-jinja";
import { htmlLanguage } from "@codemirror/lang-html";
const JINJA_COMMENT = { block: { open: "{#", close: "#}" } };
// The text between the template tags of a config file, YAML or source: no syntax of its own.
const plainText = new LanguageSupport(
StreamLanguage.define({
name: "jinja-text",
token(stream) {
stream.skipToEnd();
return null;
},
}),
);
/** A Jinja2 template of any text (Ansible's `nginx.conf.j2`, `values.yaml.j2`). */
export function jinja(): LanguageSupport {
const support = jinjaSupport({ base: plainText });
return new LanguageSupport(support.language, [
support.support,
plainText.language.data.of({ commentTokens: JINJA_COMMENT }),
support.language.data.of({ commentTokens: JINJA_COMMENT }),
]);
}
/** A Jinja2 HTML template (`page.html.j2`, Flask's `base.html.jinja`). */
export function jinjaHtml(): LanguageSupport {
const support = jinjaSupport(); // HTML is the default base
return new LanguageSupport(support.language, [
support.support,
// Markup is commented out with a template comment, which Jinja drops from the page.
htmlLanguage.data.of({ commentTokens: JINJA_COMMENT }),
support.language.data.of({ commentTokens: JINJA_COMMENT }),
]);
}
+3
Переглянути файл
@@ -259,6 +259,9 @@ const OWN_MODES = [
extensions: ["djhtml"],
load: () => import("./django").then((m) => m.django()),
}),
// No extensions: a `.j2` file typed as another language (Override File Type) drops the mode.
LanguageDescription.of({ name: "Jinja", load: () => import("./jinja").then((m) => m.jinja()) }),
LanguageDescription.of({ name: "Jinja HTML", load: () => import("./jinja").then((m) => m.jinjaHtml()) }),
LanguageDescription.of({
name: "Go Template",
alias: ["gotmpl", "tmpl"],
+1
Переглянути файл
@@ -611,6 +611,7 @@ const LINKED_TAG_LANGUAGES = new Set([
"vue",
"jsp",
"django-html",
"jinja-html",
"astro",
"typescriptreact",
"javascriptreact",
+2 -2
Переглянути файл
@@ -16,10 +16,10 @@ import { docOf } from "./lsp";
const INSPECT_DELAY = 500;
/**
* Dialects the grammar doesn't follow: the database support checks SQL, and Django templates
* Dialects the grammar doesn't follow: the database support checks SQL, and Django and Jinja templates
* borrow the HTML grammar, which reads `{% if a > b %}` as broken markup.
*/
const SKIPPED = new Set(["sql", "plaintext", "django-html", "helm-template"]);
const SKIPPED = new Set(["sql", "plaintext", "django-html", "jinja-html", "helm-template"]);
const RUNNING: ReadonlySet<ServerStatus> = new Set<ServerStatus>(["starting", "ready", "busy"]);
let checked: Promise<ReadonlySet<string>> | null = null;
+3
Переглянути файл
@@ -260,6 +260,9 @@ describe("run config → launch config", () => {
expect(isJinjaTemplate(p), p).toBe(true);
for (const p of ["/p/static/index.html", "/p/templates.py", "/p/templates/style.css", "/p/app.py"])
expect(isJinjaTemplate(p), p).toBe(false);
// A file whose Override File Type is Jinja2 Template.
expect(isJinjaTemplate("/p/static/index.html", "jinja")).toBe(true);
expect(isJinjaTemplate("/p/static/index.html", "jinja-html")).toBe(true);
});
it("debugpy: uv / poetry run the debuggee in the project's environment", () => {
+21 -2
Переглянути файл
@@ -5,10 +5,13 @@ import { useBreakpoints } from "../breakpoints/store";
const ipc = vi.hoisted(() => ({
languages: vi.fn(async () => [{ id: "python", debuggable: true }]),
// Django Templates by the backend's detection (a `templates` folder of a `manage.py` project).
// Django Templates by the backend's detection (a `templates` folder of a `manage.py` project), and
// files whose Override File Type is a template language.
docLanguage: vi.fn(async (path: string) => ({
status: "ok" as const,
data: { language: path.startsWith("/shop/") && path.endsWith(".html") ? "django-html" : "html" },
data: {
language: OVERRIDES[path] ?? (path.startsWith("/shop/") && path.endsWith(".html") ? "django-html" : "html"),
},
})),
}));
@@ -17,6 +20,12 @@ vi.mock("@/platform/ipc", async (original) => {
return { ...real, isTauri: () => true, commands: { ...real.commands, ...ipc } };
});
const OVERRIDES: Record<string, string> = {
"/flask/static/page.html": "jinja-html",
"/flask/static/robots.txt": "jinja",
"/shop/mail/welcome.j2": "django-html",
};
afterEach(() => useBreakpoints.setState({ byFile: {} }));
const withBreakpoints = (byFile: Record<string, boolean>) =>
@@ -37,6 +46,16 @@ it("tells Django templates from Jinja2 ones by the file's language", async () =>
expect(ipc.docLanguage).not.toHaveBeenCalledWith("/shop/views.py", null);
});
it("goes by the language a file is typed as", async () => {
withBreakpoints({ "/flask/static/page.html": true });
expect(await templateBreakpoints()).toEqual({ django: false, jinja: true });
withBreakpoints({ "/flask/static/robots.txt": true });
expect(await templateBreakpoints()).toEqual({ django: false, jinja: true });
// A `.j2` file typed as a Django Template is Django's, not Jinja2's.
withBreakpoints({ "/shop/mail/welcome.j2": true });
expect(await templateBreakpoints()).toEqual({ django: true, jinja: false });
});
it("accepts breakpoints in templates without a debugger of their own", async () => {
canPlaceBreakpoint("python", "/a.py");
await vi.waitFor(() => expect(canPlaceBreakpoint("text", "/notes.txt")).toBe(false));
+11 -6
Переглянути файл
@@ -23,19 +23,24 @@ function load() {
.finally(() => (loading = false));
}
/** Jinja2's own extensions: no language of theirs yet, but debugpy stops in them (`jinja: true`). */
const JINJA_EXTENSION = /\.(jinja2?|j2)$/i;
/** A Jinja2 template for debugpy: a `.jinja` / `.j2` file, or markup or text in a `templates` folder. */
export const isJinjaTemplate = (path: string) =>
JINJA_EXTENSION.test(path) || /[\\/]templates[\\/].*\.(html?|xml|txt)$/i.test(path);
/**
* A Jinja2 template for debugpy: a Jinja2 Template file (also by extension, should File Types give
* it to another language), or markup or text in a `templates` folder.
*/
export const isJinjaTemplate = (path: string, language?: string | null) =>
language === "jinja" ||
language === "jinja-html" ||
JINJA_EXTENSION.test(path) ||
/[\\/]templates[\\/].*\.(html?|xml|txt)$/i.test(path);
/** Whether a new breakpoint may be placed in a file of `language`. */
export function canPlaceBreakpoint(language: string, path = ""): boolean {
if (classFileBreakpointReason(path)) return false;
// Templates have no adapter of their own: a Python Debug configuration stops in them (debugpy
// `django` / `jinja`). Django's doesn't declare debugpy, or it would shadow Python's `[debugger]`.
if (workflowSettings().debugger.breakpointsAnyFile || language === "django-html" || isJinjaTemplate(path)) {
if (workflowSettings().debugger.breakpointsAnyFile || language === "django-html" || isJinjaTemplate(path, language)) {
return true;
}
load();
@@ -70,6 +75,6 @@ export async function templateBreakpoints(): Promise<TemplateBreakpoints> {
const languages = await Promise.all(paths.map(languageOf));
return {
django: languages.includes("django-html"),
jinja: paths.some((path, i) => languages[i] !== "django-html" && isJinjaTemplate(path)),
jinja: paths.some((path, i) => languages[i] !== "django-html" && isJinjaTemplate(path, languages[i])),
};
}
+4
Переглянути файл
@@ -25,6 +25,10 @@ describe("emmet context", () => {
expect(syntaxAt("django-html", "{% if user")).toBeNull();
expect(syntaxAt("django-html", "{{ value|date")).toBeNull();
expect(syntaxAt("django-html", "{# note")).toBeNull();
expect(syntaxAt("jinja-html", "{% block content %}\n ul>li")).toEqual({ type: "markup", syntax: "html" });
expect(syntaxAt("jinja-html", "{{ value|upper")).toBeNull();
// Not in a config file or source: `listen` + Tab in an nginx.conf.j2 stays text.
expect(syntaxAt("jinja", "server {\n listen")).toBeNull();
expect(syntaxAt("django-html", '<a href="{% url "home" %}">x</a>\nnav')).toEqual({
type: "markup",
syntax: "html",
+7 -3
Переглянути файл
@@ -27,7 +27,7 @@ export interface EmmetSyntax {
}
/** Languages with markup expansion; `<style>` / `<script>` regions are handled. */
const MARKUP_LANGUAGES = new Set(["html", "vue", "svelte", "django-html"]);
const MARKUP_LANGUAGES = new Set(["html", "vue", "svelte", "django-html", "jinja-html"]);
const STYLESHEET_LANGUAGES: Record<string, string> = { css: "css", scss: "scss", less: "less", sass: "sass" };
/** Languages with JSX expansion (`.card` → `<div className="card">`); the context comes from the syntax tree. */
export const JSX_LANGUAGES = new Set(["typescriptreact", "javascriptreact"]);
@@ -71,8 +71,12 @@ export function syntaxAt(language: string, before: string): EmmetSyntax | null {
if (css) return stylesheetContext(text) ? { type: "stylesheet", syntax: css } : null;
if (!MARKUP_LANGUAGES.has(language)) return null;
if (lastMatch(text, /<!--/g) > lastMatch(text, /-->/g)) return null;
// Not inside a Django tag, variable or comment (`{% if user|`).
if (language === "django-html" && lastMatch(text, /\{[%{#]/g) > lastMatch(text, /[%}#]\}/g)) return null;
// Not inside a Django or Jinja tag, variable or comment (`{% if user|`).
if (
(language === "django-html" || language === "jinja-html") &&
lastMatch(text, /\{[%{#]/g) > lastMatch(text, /[%}#]\}/g)
)
return null;
if (openRegion(text, "script")) return null;
const style = openRegion(text, "style");
if (style) {
+1
Переглянути файл
@@ -23,6 +23,7 @@ const cases = [
["JSP", "<% if (ready) { %><p><%= value %></p><% } %>"],
["Angular Template", "@if (ready) {\n <p>{{ value }}</p>\n}"],
["Django Template", "{% if ready %}\n <p>{{ value|lower }}</p>\n{% endif %}"],
["Jinja", "{% if ready %}\n <p>{{ value|lower }}</p>\n{% endif %}"],
["Helm Template", "{{- range .Values.apps }}\napiVersion: v1\nmetadata:\n name: {{ .name | quote }}\n{{- end }}"],
];
+5
Переглянути файл
@@ -165,6 +165,11 @@ describe("fileIconName", () => {
["api.ts", "file-ts"],
["types.d.ts", "file-ts"],
["App.TSX", "file-tsx"],
// Jinja2 templates: the icon of what they render, HTML when the name doesn't tell.
["base.jinja", "file-html"],
["page.html.j2", "file-html"],
["nginx.conf.j2", "file-config"],
["values.yaml.jinja2", "file-yaml"],
["package.json", "file-npm"],
["package-lock.json", "file-lock"],
["yarn.lock", "file-lock"],
+8 -1
Переглянути файл
@@ -1190,7 +1190,7 @@ const EXT_ICONS = table({
"file-text": "txt text",
"file-log": "log",
"file-csv": "csv tsv",
"file-html": "html htm shtml html.tmpl djhtml",
"file-html": "html htm shtml html.tmpl djhtml jinja jinja2 j2",
"file-xhtml": "xhtml",
"file-css": "css pcss postcss",
"file-less": "less",
@@ -1270,6 +1270,8 @@ const EXT_ICONS = table({
/** Source files for languages without a file-type icon. */
const CODE_EXT = new Set(["nim", "wit", "wat", "sol", "v", "sv"]);
const JINJA_EXT = new Set(["jinja", "jinja2", "j2"]);
const GENERIC_ICONS: ReadonlySet<IconName> = new Set(["file-text", "file-unknown", "file-code"]);
let iconOverride: ((fileName: string) => IconName | null) | null = null;
@@ -1334,6 +1336,11 @@ export function fileIconName(fileName: string, path: string | null = null): Icon
const dot = lower.lastIndexOf(".");
if (dot <= 0) return "file-text";
const ext = lower.slice(dot + 1);
// A Jinja2 template has the icon of what it renders (`nginx.conf.j2`); HTML when the name doesn't tell.
if (JINJA_EXT.has(ext)) {
const inner = fileIconName(fileName.slice(0, dot));
if (!GENERIC_ICONS.has(inner)) return inner;
}
const prev = lower.lastIndexOf(".", dot - 1);
const ext2 = prev > 0 ? lower.slice(prev + 1) : undefined;
const icon = (ext2 && EXT_ICONS[ext2]) || EXT_ICONS[ext];