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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 639adb6625 feat(freemarker): parse templates with an HTML layer, script and style languages, and completion
FreeMarker files were highlighted by a stream mode over the legacy XML mode,
so markup had no HTML completion and `<script>` / `<style>` content was plain
text. A Lezer grammar now parses the template layer (directives, user-defined
directive calls, interpolations, comments, `noparse`), with the first
directive fixing the angle or square tag syntax, and the text between them is
mounted as one HTML document, as in Django templates: markup nests across
directives, attributes with `${…}` stay attributes, and script and style
content gets JavaScript and CSS highlighting and completion.

Block directives fold, indent, match their end tags and get their end tag
when the start tag is finished; completion offers directives after `<#`, the
open blocks' end tags after `</`, and built-ins after `?`. Comment Block uses
`<#-- -->` (`[#-- --]` in the square syntax) outside scripts and styles.

Fixes #6906
2026-12-01 03:43:46 +08:00
11 змінених файлів з 1056 додано та 158 видалено

No files matched your search

+1
Переглянути файл
@@ -15,6 +15,7 @@
"src/editor/core/cm/jsp/parser*.ts",
"src/editor/core/cm/astro/parser*.ts",
"src/editor/core/cm/django/parser*.ts",
"src/editor/core/cm/freemarker/parser*.ts",
"plugins/themes.md",
"pnpm-lock.yaml",
"**/*.toml",
+1
Переглянути файл
@@ -10,6 +10,7 @@ const config: KnipConfig = {
"!src/editor/core/cm/jsp/parser.terms.ts",
"!src/editor/core/cm/astro/parser.terms.ts",
"!src/editor/core/cm/django/parser.terms.ts",
"!src/editor/core/cm/freemarker/parser.terms.ts",
"scripts/**/*.ts",
"perf/**/*.ts",
"evals/**/*.ts",
+1
Переглянути файл
@@ -23,6 +23,7 @@
"gen:angular-grammar": "lezer-generator src/editor/core/cm/angular/angular.grammar --typeScript -o src/editor/core/cm/angular/parser.ts",
"gen:jsp-grammar": "lezer-generator src/editor/core/cm/jsp/jsp.grammar --typeScript -o src/editor/core/cm/jsp/parser.ts",
"gen:django-grammar": "lezer-generator src/editor/core/cm/django/django.grammar --typeScript -o src/editor/core/cm/django/parser.ts",
"gen:freemarker-grammar": "lezer-generator src/editor/core/cm/freemarker/freemarker.grammar --typeScript -o src/editor/core/cm/freemarker/parser.ts",
"gen:astro-grammar": "lezer-generator src/editor/core/cm/astro/astro.grammar --typeScript -o src/editor/core/cm/astro/parser.ts",
"gen:theme-docs": "node scripts/theme/gen-docs.ts",
"gen:plugin-catalog": "node scripts/gen-plugin-catalog.ts",
-154
Переглянути файл
@@ -1,154 +0,0 @@
/**
* FreeMarker editor mode: HTML outside the template syntax, FreeMarker inside
* directives (`<#if …>`, `<@macro …/>`), interpolations (`${…}`) and comments.
* The first directive fixes the tag syntax, angle (`<#if>`) or square (`[#if]`),
* as FreeMarker itself does; `[=…]` interpolations count only in square syntax.
*/
import { LanguageSupport, StreamLanguage, StringStream, type StreamParser } from "@codemirror/language";
import { tags } from "@lezer/highlight";
type State<H> = {
html: H;
mode: "comment" | "directive" | "interpolation" | null;
/** Tag syntax: `null` until the first directive, then square or not. */
square: boolean | null;
/** What ends the current comment, directive or interpolation. */
close: string;
/** Brackets open inside the expression; the closer counts only at 0. */
depth: number;
/** The directive's name comes next. */
name: "#" | "@" | null;
};
// `(?=…)` lookahead only: WebKit lacks lookbehind.
const OPENER = /<#--|\[#--|<\/?[#@](?=[A-Za-z_])|\[\/?[#@](?=[A-Za-z_])|\$\{|\[=/g;
const KEYWORDS = new Set(["as", "in", "using", "gt", "gte", "lt", "lte"]);
function nextOpener(line: string, from: number, square: boolean | null): RegExpExecArray | null {
OPENER.lastIndex = from;
for (let m = OPENER.exec(line); m; m = OPENER.exec(line)) {
const text = m[0];
if (text === "${") return m;
if (text === "[=" ? square === true : square === null || square === (text[0] === "[")) return m;
}
return null;
}
function tokenComment<H>(stream: StringStream, state: State<H>): string {
const end = stream.string.indexOf(state.close, stream.pos);
stream.pos = end < 0 ? stream.string.length : end + state.close.length;
if (end >= 0) state.mode = null;
return "comment";
}
function tokenExpression<H>(stream: StringStream, state: State<H>): string | null {
if (stream.eatSpace()) return null;
if (state.depth === 0 && stream.match(state.close)) {
state.mode = null;
return "ftlDelimiter";
}
if (state.depth === 0 && state.mode === "directive" && stream.match("/" + state.close)) {
state.mode = null;
return "ftlDelimiter";
}
if (stream.match(/^r?"(?:[^"\\]|\\.)*"?/) || stream.match(/^r?'(?:[^'\\]|\\.)*'?/)) return "string";
if (stream.match(/^\d+(?:\.\d+)?/)) return "number";
if (stream.match("??")) return "operator";
if (stream.match(/^\?[A-Za-z_]\w*/)) return "ftlBuiltin";
if (stream.match(/^\.[A-Za-z_]\w*/)) return "propertyName";
if (stream.match(/^[A-Za-z_$][\w$]*/)) {
const word = stream.current();
if (word === "true" || word === "false") return "bool";
return KEYWORDS.has(word) ? "keyword" : "variableName";
}
const ch = stream.next()!;
if ("([{".includes(ch)) {
state.depth++;
return "bracket";
}
if (")]}".includes(ch)) {
state.depth = Math.max(0, state.depth - 1);
return "bracket";
}
if (ch === "." && stream.match(/^\.[<!*]?/)) return "operator";
return "+-*/%!=<>&|:,;.".includes(ch) ? "operator" : null;
}
function freemarkerParser<H>(html: StreamParser<H>): StreamParser<State<H>> {
const copy = (state: H): H =>
html.copyState
? html.copyState(state)
: (Object.fromEntries(
Object.entries(state as object).map(([k, v]) => [k, Array.isArray(v) ? v.slice() : v]),
) as H);
/** Runs the HTML mode on `stream` cut at `end`, then advances `stream` to where it stopped. */
const tokenHtml = (stream: StringStream, end: number, state: H): string | null => {
const sub = new StringStream(stream.string.slice(0, end), 4, stream.indentUnit);
sub.pos = stream.pos;
sub.start = stream.start;
const style = html.token(sub, state);
stream.pos = Math.max(sub.pos, stream.pos + (sub.pos === stream.pos ? 1 : 0));
return style;
};
return {
name: "freemarker",
languageData: { ...html.languageData, commentTokens: { block: { open: "<#--", close: "-->" } } },
tokenTable: {
...html.tokenTable,
ftlDelimiter: tags.special(tags.brace),
ftlBuiltin: tags.standard(tags.function(tags.variableName)),
ftlMacro: tags.function(tags.variableName),
},
startState: (indentUnit) => ({
html: html.startState!(indentUnit),
mode: null,
square: null,
close: "",
depth: 0,
name: null,
}),
copyState: (s) => ({ ...s, html: copy(s.html) }),
blankLine: (s, unit) => (s.mode ? undefined : html.blankLine?.(s.html, unit)),
indent: (s, text, cx) => (s.mode ? null : (html.indent?.(s.html, text, cx) ?? null)),
token(stream, state) {
if (state.mode === "comment") return tokenComment(stream, state);
if (state.name) {
const sigil = state.name;
state.name = null;
if (stream.match(/^[A-Za-z_][\w.:-]*/)) return sigil === "#" ? "keyword" : "ftlMacro";
}
if (state.mode) return tokenExpression(stream, state);
const open = nextOpener(stream.string, stream.pos, state.square);
if (open?.index !== stream.pos) {
return tokenHtml(stream, open ? open.index : stream.string.length, state.html);
}
const text = open[0];
stream.pos += text.length;
const square = text[0] === "[";
state.depth = 0;
if (text.endsWith("--")) {
state.mode = "comment";
state.close = square ? "--]" : "-->";
return tokenComment(stream, state);
}
if (text === "${" || text === "[=") {
state.mode = "interpolation";
state.close = text === "${" ? "}" : "]";
return "ftlDelimiter";
}
state.square ??= square;
state.mode = "directive";
state.close = square ? "]" : ">";
state.name = text.endsWith("@") ? "@" : "#";
return "ftlDelimiter";
},
};
}
export async function freemarker(): Promise<LanguageSupport> {
const { html } = await import("@codemirror/legacy-modes/mode/xml");
return new LanguageSupport(StreamLanguage.define(freemarkerParser(html)));
}
+101
Переглянути файл
@@ -0,0 +1,101 @@
// FreeMarker templates: the template layer. Directives (`<#if …>`), user-defined
// directive calls (`<@badge …/>`), interpolations (`${…}`) and comments are parsed
// here; the text between them is HTML, mounted by `./index.ts`. The first directive
// fixes the tag syntax, angle (`<#if>`) or square (`[#if]`), as FreeMarker does.
// Block directives nest (`<#if>…<#elseif>…<#else>…</#if>`); others stand alone.
// Regenerate with `pnpm gen:freemarker-grammar`.
@context blocks from "./tokens"
@top Template { node* }
node {
Text |
Comment |
Interpolation |
Tag |
Element |
RawElement |
StrayEndTag
}
// A block directive or user-defined directive call, its middle tags
// (`elseif`, `else`, `recover`, `case`…) and its end tag.
Element { OpenTag node* (MidTag node*)* EndTag }
// `<#noparse>…</#noparse>`, `<#comment>…</#comment>`: the content is not parsed.
RawElement { RawTag RawBody? EndTag }
@skip { space } {
OpenTag { OpenTagStart tagName argument* TagEnd }
RawTag { RawTagStart tagName argument* TagEnd }
MidTag { MidTagStart tagName argument* (TagEnd | SelfCloseEnd) }
EndTag { EndTagStart tagName? TagEnd }
// An end tag without its start tag, or of a directive that may or may not be a block (`</#sep>`).
StrayEndTag { StrayEndTagStart tagName? TagEnd }
Tag { TagStart tagName argument* (TagEnd | SelfCloseEnd) }
Interpolation { InterpolationStart argument* InterpolationEnd }
argument {
VariableName |
Member { "." PropertyName } |
BuiltIn { "?" BuiltInName } |
String |
Number |
Operator |
CompareOp |
kw<"as"> | kw<"in"> | kw<"using"> |
kw<"gt"> | kw<"gte"> | kw<"lt"> | kw<"lte"> |
@specialize[@name=BooleanLiteral]<identifier, "true" | "false"> |
ParenGroup { "(" argument* ")" } |
BracketGroup { "[" argument* "]" } |
HashGroup { "{" argument* "}" }
}
}
tagName { DirectiveName | MacroName }
VariableName { identifier }
PropertyName { identifier }
BuiltInName { identifier }
kw<term> { @specialize[@name={term}]<identifier, term> }
// Tried in this order, before the tokens below.
@external tokens comment from "./tokens" { Comment }
@external tokens rawBody from "./tokens" { RawBody }
@external tokens text from "./tokens" { Text }
@external tokens tagStart from "./tokens" {
OpenTagStart, RawTagStart, MidTagStart, EndTagStart, StrayEndTagStart, TagStart, InterpolationStart
}
@external tokens tagName from "./tokens" { DirectiveName, MacroName }
@external tokens tagEnd from "./tokens" { TagEnd, SelfCloseEnd, InterpolationEnd }
@tokens {
space { $[ \t\n\r]+ }
identifier { $[a-zA-Z_$\u{a1}-\u{10ffff}] $[a-zA-Z0-9_$\u{a1}-\u{10ffff}]* }
Number { @digit+ ("." @digit+)? }
String {
"r"? '"' (!["\\] | "\\" _)* '"'? |
"r"? "'" (!['\\] | "\\" _)* "'"?
}
Operator {
"+" | "-" | "*" | "/" | "%" | "!" | "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "++" | "--" |
"&&" | "||" | "&" | "|" | "??" | ".." | "..<" | "..!" | "..*" | "," | ":" | ";" | "->"
}
CompareOp { "==" | "!=" | "<" | "<=" | ">=" | ">" }
@precedence { String, identifier }
"." "?" "(" ")" "[" "]" "{" "}"
}
@detectDelim
+202
Переглянути файл
@@ -0,0 +1,202 @@
import { describe, expect, it } from "vitest";
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { EditorSelection, EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { CompletionContext, type CompletionResult, type CompletionSource } from "@codemirror/autocomplete";
import { foldable, getIndentation, indentUnit, matchBrackets } from "@codemirror/language";
import { buildParserFile } from "@lezer/generator";
import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight";
import { completedSyntaxState, completedSyntaxTree } from "@/test/syntax";
import { commentBlock } from "../comments";
import { freemarker, freemarkerLanguage } from "./index";
const highlighter = tagHighlighter([
{ tag: t.special(t.brace), class: "delim" },
{ tag: t.blockComment, class: "comment" },
{ tag: t.keyword, class: "keyword" },
{ tag: t.variableName, class: "var" },
{ tag: t.propertyName, class: "prop" },
{ tag: t.attributeName, class: "attr" },
{ tag: t.string, class: "str" },
{ tag: t.tagName, class: "tag" },
]);
function state(doc: string, selection?: number): EditorState {
return completedSyntaxState(
EditorState.create({
doc,
selection: selection == undefined ? undefined : EditorSelection.cursor(selection),
extensions: [freemarker(), indentUnit.of(" ")],
}),
);
}
/** `text:class` of the styled tokens of `doc`, HTML and embedded languages included. */
function tokens(doc: string): string[] {
const out: string[] = [];
highlightTree(completedSyntaxTree(state(doc)), highlighter, (from, to, cls) =>
out.push(`${doc.slice(from, to)}:${cls}`),
);
return out;
}
/** The error nodes of `doc`'s template layer, with the text they start. */
function errors(doc: string): string[] {
const out: string[] = [];
freemarkerLanguage.parser.parse(doc).iterate({
enter: (node) => void (node.type.isError && out.push(doc.slice(node.from, node.from + 12))),
});
return out;
}
const outline = (doc: string) => freemarkerLanguage.parser.parse(doc).toString();
/** A view on `doc` with `|` marking the caret. */
function view(marked: string): EditorView {
const at = marked.indexOf("|");
return new EditorView({ state: state(marked.slice(0, at) + marked.slice(at + 1), at) });
}
/** Types `text` at the caret through the input handlers, like a keystroke. */
function type(v: EditorView, text: string): string {
const { from, to } = v.state.selection.main;
const handled = v.state.facet(EditorView.inputHandler).some((h) => h(v, from, to, text, () => v.state.update({})));
if (!handled)
v.dispatch({ changes: { from, to, insert: text }, selection: EditorSelection.cursor(from + text.length) });
const head = v.state.selection.main.head;
return v.state.sliceDoc(0, head) + "|" + v.state.sliceDoc(head);
}
/** The labels completion offers at the end of `doc`. */
function complete(doc: string): string[] | undefined {
const s = state(doc);
const sources = s.languageDataAt<CompletionSource>("autocomplete", doc.length);
const result = sources.map((src) => src(new CompletionContext(s, doc.length, true))).find(Boolean) as
| CompletionResult
| undefined;
return result?.options.map((o) => o.label);
}
describe("FreeMarker template layer", () => {
it("nests block directives with their middle tags and leaves other directives alone", () => {
expect(outline("<#if a>x<#elseif b>y<#else>z</#if><#assign n = 1>")).toBe(
"Template(Element(OpenTag(OpenTagStart,DirectiveName,VariableName,TagEnd),Text," +
"MidTag(MidTagStart,DirectiveName,VariableName,TagEnd),Text,MidTag(MidTagStart,DirectiveName,TagEnd),Text," +
"EndTag(EndTagStart,DirectiveName,TagEnd)),Tag(TagStart,DirectiveName,VariableName,Operator,Number,TagEnd))",
);
// `assign` without `=` captures its content; a call with content is a block, one without isn't.
expect(outline("<#assign x>v</#assign><@m/><@m>c</@m>")).toMatch(
/^Template\(Element\(.*\),Tag\(.*SelfCloseEnd\),Element\(.*\)\)$/,
);
});
it("doesn't parse the content of noparse and comment", () => {
expect(outline("<#noparse><#if>${x}</#noparse>")).toBe(
"Template(RawElement(RawTag(RawTagStart,DirectiveName,TagEnd),RawBody,EndTag(EndTagStart,DirectiveName,TagEnd)))",
);
});
it("parses common templates without errors", () => {
const doc = [
'<#ftl output_format="HTML">',
'<#import "/lib/ui.ftl" as ui>',
"<#macro row item><tr><td>${item.name}</td></tr></#macro>",
"<#function total xs><#local s = 0><#list xs as x><#local s += x.price></#list><#return s></#function>",
"<#list orders?filter(o -> o.paid) as order><@row item=order/><#sep>, </#sep><#else>none</#list>",
'<#switch kind><#case "a">A<#break><#default>B</#switch>',
"<#attempt>${risky}<#recover>failed</#attempt>",
"<#if (a > 1) && b?? && c?has_content>${a..<5}</#if>",
'<@ui.card title="x" items=[1, 2] opts={"k": true}>c</@ui.card>',
"<#list map as k, v>${k}=${v}</#list>",
].join("\n");
expect(errors(doc)).toEqual([]);
});
it("highlights script and style content as JavaScript and CSS", () => {
const out = tokens('<script>let a = "${x}";</script><style>p { color: red }</style>');
expect(out).toContain("let:keyword");
expect(out).toContain("x:var");
expect(out).toContain("color:prop");
});
it("nests markup across directives", () => {
const out = tokens('<#if a><div class="x"></#if><#if a></div></#if>');
expect(out.filter((t) => t == "div:tag")).toHaveLength(2);
expect(out).toContain("class:attr");
});
it("is generated from freemarker.grammar", () => {
const dir = import.meta.dirname;
const { parser, terms } = buildParserFile(readFileSync(resolve(dir, "freemarker.grammar"), "utf8"), {
fileName: "src/editor/core/cm/freemarker/freemarker.grammar",
moduleStyle: "es",
typeScript: true,
});
const lf = (s: string) => s.replace(/\r\n/g, "\n");
expect(lf(parser)).toBe(lf(readFileSync(resolve(dir, "parser.ts"), "utf8")));
expect(lf(terms)).toBe(lf(readFileSync(resolve(dir, "parser.terms.ts"), "utf8")));
});
});
describe("FreeMarker template editing", () => {
it("folds blocks", () => {
const doc = "<#list xs as x>\n <p>${x}</p>\n</#list>\n";
expect(foldable(state(doc), 0, doc.indexOf("\n"))).toEqual({ from: doc.indexOf(">") + 1, to: doc.indexOf("</#") });
});
it("indents a block's content and puts its middle and end tags back", () => {
const s = state("<#if a>\nx\n<#else>\ny\n</#if>");
const lineStart = (n: number) => s.doc.line(n).from;
expect(getIndentation(s, lineStart(2))).toBe(2);
expect(getIndentation(s, lineStart(3))).toBe(0);
expect(getIndentation(s, lineStart(4))).toBe(2);
expect(getIndentation(s, lineStart(5))).toBe(0);
});
it("matches a block directive with its end tag", () => {
const doc = "<#list xs as x>${x}</#list>";
const match = matchBrackets(state(doc), 3, 1);
expect(match?.matched).toBe(true);
expect(doc.slice(match!.end!.from, match!.end!.to)).toBe("list");
});
it("adds the end tag of a block directive when its > is typed", () => {
expect(type(view("<#if a|"), ">")).toBe("<#if a>|</#if>");
expect(type(view("<@card title=t|"), ">")).toBe("<@card title=t>|</@card>");
expect(type(view("[#ftl][#list xs as x|"), "]")).toBe("[#ftl][#list xs as x]|[/#list]");
// It has one already.
expect(type(view("<#if a|\n</#if>"), ">")).toBe("<#if a>|\n</#if>");
// Not a block, or closed by `/>`.
expect(type(view("<#include 'a.ftl'|"), ">")).toBe("<#include 'a.ftl'>|");
expect(type(view("<@card /|"), ">")).toBe("<@card />|");
// A capturing assign only without `=`.
expect(type(view("<#assign x|"), ">")).toBe("<#assign x>|</#assign>");
// Not in a script.
expect(type(view("<script>if (a <#b|</script>"), ">")).toBe("<script>if (a <#b>|</script>");
});
it("completes directives, the open blocks' end tags and built-ins", () => {
expect(complete("<p><#")).toContain("list");
expect(complete("<#list xs as x><@card><#if a></")).toEqual(["#if", "@card", "#list"]);
expect(complete("<#list xs as x><@card><#if a></#")).toEqual(["#if", "@card", "#list"]);
expect(complete("${name?")).toContain("upper_case");
expect(complete("<p>Why?")).not.toContain("upper_case");
});
it("comments with <#-- -->", () => {
const v = view("|<p>a</p>");
v.dispatch({ selection: EditorSelection.range(0, v.state.doc.length) });
commentBlock(v);
expect(v.state.doc.toString()).toBe("<#-- <p>a</p> -->");
const square = view("[#ftl]\n|<p>a</p>");
square.dispatch({ selection: EditorSelection.range(7, square.state.doc.length) });
commentBlock(square);
expect(square.state.doc.toString()).toBe("[#ftl]\n[#-- <p>a</p> --]");
// JavaScript keeps its own.
const script = view("<script>|a()</script>");
script.dispatch({ selection: EditorSelection.range(8, 11) });
commentBlock(script);
expect(script.state.doc.toString()).toBe("<script>/* a() */</script>");
});
});
+14 -4
Переглянути файл
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
import { EditorState } from "@codemirror/state";
import { completedSyntaxTree } from "@/test/syntax";
import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight";
import { findLanguageDescription, loadSupport } from "./languages";
import { findLanguageDescription, loadSupport } from "../languages";
const highlighter = tagHighlighter([
{ tag: t.keyword, class: "keyword" },
@@ -25,9 +25,19 @@ async function tokens(source: string) {
const support = await loadSupport(desc);
const state = EditorState.create({ doc: source, extensions: [support!] });
const result: { text: string; style: string }[] = [];
highlightTree(completedSyntaxTree(state), highlighter, (from, to, style) =>
result.push({ text: source.slice(from, to), style }),
);
let last = { to: -1, style: "" };
// One span per run of a style on a line, as the editor draws it.
highlightTree(completedSyntaxTree(state), highlighter, (from, to, style) => {
source
.slice(from, to)
.split("\n")
.forEach((text, i) => {
const prev = result.at(-1);
if (i == 0 && prev && last.to == from && last.style == style) prev.text += text;
else result.push({ text, style });
});
last = { to, style };
});
return result;
}
+320
Переглянути файл
@@ -0,0 +1,320 @@
/**
* FreeMarker templates: `freemarker.grammar` parses the template layer (directives,
* user-defined directive calls, interpolations, comments), and the text between its
* elements is one HTML document, an overlay as in Django and JSP templates, so markup
* split by a directive still nests, `href="${url}"` is an attribute with a hole, and
* `<script>` / `<style>` get JavaScript and CSS. Block directives fold, indent their
* content and match their end tags; finishing a block directive adds its end tag.
* Completion offers directives after `<#`, the open blocks' end tags after `</` and
* built-ins after `?`.
*/
import {
LRLanguage,
LanguageSupport,
bracketMatchingHandle,
foldNodeProp,
indentNodeProp,
syntaxTree,
type TreeIndentContext,
} from "@codemirror/language";
import { html } from "@codemirror/lang-html";
import type { Completion, CompletionContext, CompletionResult } from "@codemirror/autocomplete";
import { EditorSelection, EditorState, Prec, type Text } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { styleTags, tags as t } from "@lezer/highlight";
import { NodeProp, parseMixed, type SyntaxNode, type SyntaxNodeRef } from "@lezer/common";
import { VERSIONED_SCRIPT_TYPES } from "../htmlScripts";
import { parser } from "./parser";
import { BLOCK_DIRECTIVES, CAPTURING, DIRECTIVES, RAW_DIRECTIVES } from "./tokens";
const baseHTML = html({ selfClosingTags: true, nestedLanguages: VERSIONED_SCRIPT_TYPES });
const FTL_COMMENT = { block: { open: "<#--", close: "-->" } };
const SQUARE_COMMENT = { block: { open: "[#--", close: "--]" } };
const OPENERS = ["OpenTag", "RawTag"];
const startTagOf = (element: SyntaxNode) => element.firstChild;
const endTagOf = (element: SyntaxNode) => (element.lastChild?.name == "EndTag" ? element.lastChild : null);
const tagNameOf = (node: SyntaxNode) => node.getChild("DirectiveName") ?? node.getChild("MacroName");
/** The content of a block: from the end of its start tag to its end tag (or the end of the block). */
function foldBlock(element: SyntaxNode, state: EditorState) {
const start = startTagOf(element);
const end = endTagOf(element);
if (!start) return null;
// An end tag the parser inserted to recover is empty.
const to = end && end.to > end.from ? end.from : element.to;
return start.to < to && state.doc.lineAt(start.to).number < state.doc.lineAt(to).number
? { from: start.to, to }
: null;
}
const MIDDLE = new Set([...BLOCK_DIRECTIVES.values()].flat());
const CLOSING_LINE = /^\s*(?:<|\[)(?:\/[#@]|#([A-Za-z]+))/;
/** A block's content one unit in from its start tag's line; its middle and end tags at that line's indent. */
function indentBlock(cx: TreeIndentContext) {
const start = startTagOf(cx.node);
if (!start) return null;
const base = cx.lineIndent(start.from);
const m = CLOSING_LINE.exec(cx.textAfter);
return m && (!m[1] || MIDDLE.has(m[1])) ? base : base + cx.unit;
}
const templateParser = parser.configure({
props: [
styleTags({
"TagStart OpenTagStart RawTagStart MidTagStart EndTagStart StrayEndTagStart TagEnd SelfCloseEnd InterpolationStart InterpolationEnd":
t.special(t.brace),
DirectiveName: t.keyword,
MacroName: t.function(t.variableName),
"Comment RawBody": t.blockComment,
VariableName: t.variableName,
"PropertyName Member/.": t.propertyName,
"BuiltInName BuiltIn/?": t.standard(t.function(t.variableName)),
String: t.string,
Number: t.number,
BooleanLiteral: t.bool,
"Operator CompareOp": t.operator,
"as in using gt gte lt lte": t.keyword,
"( ) [ ] { }": t.bracket,
}),
foldNodeProp.add({ "Element RawElement": foldBlock }),
indentNodeProp.add({
Element: indentBlock,
// The raw content keeps its own indentation.
RawElement: () => null,
}),
NodeProp.closedBy.add({ "OpenTag RawTag": ["EndTag"] }),
NodeProp.openedBy.add({ EndTag: OPENERS }),
bracketMatchingHandle.add({ "OpenTag RawTag EndTag": tagNameOf }),
],
});
// HTML's document gives no indentation past its last text; there the block around it does.
const htmlBase = (baseHTML.language as LRLanguage).parser;
const htmlDocumentIndent = htmlBase.nodeSet.types.find((type) => type.name == "Document")?.prop(indentNodeProp);
const htmlParser = htmlBase.configure({
props: [indentNodeProp.add({ Document: (cx) => htmlDocumentIndent?.(cx) ?? cx.continue() })],
});
// The template text is one HTML document.
const htmlMixed = { parser: htmlParser, overlay: (node: SyntaxNodeRef) => node.name == "Text" };
export const freemarkerLanguage = LRLanguage.define({
name: "freemarker",
parser: templateParser.configure({ wrap: parseMixed((node) => (node.type.isTop ? htmlMixed : null)) }),
});
/** Where the template layer reaches: FreeMarker's own nodes, or the HTML outside `<script>` and `<style>`. */
function inTemplate(state: EditorState, pos: number): boolean {
return freemarkerLanguage.isActiveAt(state, pos, -1) || baseHTML.language.isActiveAt(state, pos, -1);
}
const squareSyntaxOf = new WeakMap<Text, boolean>();
/** The square tag syntax, when the template's first directive uses it. */
function squareSyntax(state: EditorState): boolean {
let square = squareSyntaxOf.get(state.doc);
if (square == undefined) {
const head = state.sliceDoc(0, Math.min(state.doc.length, 20_000));
square = /<\/?[#@][A-Za-z]|\[\/?[#@][A-Za-z]/.exec(head)?.[0][0] == "[";
squareSyntaxOf.set(state.doc, square);
}
return square;
}
/** The blocks open at `pos`, innermost first, as `#if` / `@badge`. */
function openBlocks(state: EditorState, pos: number): string[] {
const names: string[] = [];
for (let node: SyntaxNode | null = syntaxTree(state).resolve(pos, -1); node; node = node.parent) {
if (node.name != "Element" && node.name != "RawElement") continue;
const start = startTagOf(node);
const name = start && tagNameOf(start);
if (start && name && start.to <= pos) {
names.push(state.sliceDoc(start.from, name.from).replace(/^[<[]/, "") + state.sliceDoc(name.from, name.to));
}
}
return names;
}
/** Whether the block `name` opened before `pos` has no end tag after it, nested blocks counted. */
function unclosed(state: EditorState, sigil: string, name: string, pos: number): boolean {
const rest = state.sliceDoc(pos);
const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const re = new RegExp(`[<\\[](/)?${sigil}${escaped}(?![\\w.:-])`, "g");
let depth = 0;
for (let m; (m = re.exec(rest));) {
if (!m[1]) depth++;
else if (depth-- == 0) return false;
}
return true;
}
const TAG_BEFORE = /[<[]([#@])([A-Za-z_][\w.:-]*)(?:\s[^<>[\]]*)?$/;
/** Typing the `>` (`]`) of a block directive or a call with content adds its end tag after the caret. */
const closeBlock = EditorView.inputHandler.of((view, from, to, text) => {
const { state } = view;
if ((text != ">" && text != "]") || from != to || state.selection.ranges.length > 1 || state.readOnly) return false;
const square = squareSyntax(state);
if ((text == "]") != square) return false;
const line = state.doc.lineAt(from);
const before = state.sliceDoc(line.from, from);
const m = TAG_BEFORE.exec(before);
if (!m || before.endsWith("/") || (m[0][0] == "[") != square) return false;
const [, sigil, name] = m;
// `<#assign x>…</#assign>` captures its content; `<#assign x = 1>` doesn't.
const assigns = /(?:^|[^=!<>])=(?!=)/.test(before.slice(before.length - m[0].length + 2 + name!.length));
const block = BLOCK_DIRECTIVES.has(name!) || RAW_DIRECTIVES.has(name!) || (CAPTURING.has(name!) && !assigns);
if (sigil == "#" && !block) return false;
if (!inTemplate(state, from - m[0].length)) return false;
if (!unclosed(state, sigil!, name!, from)) return false;
const close = square ? `[/${sigil}${name}]` : `</${sigil}${name}>`;
view.dispatch({
changes: { from, insert: text + close },
selection: EditorSelection.cursor(from + 1),
userEvent: "input.type",
});
return true;
});
const DIRECTIVE_OPTIONS: Completion[] = DIRECTIVES.map((label) => ({ label, type: "keyword" }));
/** Built-ins most templates use, for completion after `?`. */
const BUILT_INS = [
"api",
"boolean",
"c",
"c_lower_case",
"cap_first",
"capitalize",
"chop_linebreaks",
"chunk",
"contains",
"counter",
"date",
"datetime",
"default",
"drop_while",
"ends_with",
"ensure_ends_with",
"ensure_starts_with",
"eval",
"eval_json",
"filter",
"first",
"groups",
"has_content",
"has_next",
"html",
"if_exists",
"index",
"index_of",
"interpret",
"is_boolean",
"is_date",
"is_even_item",
"is_first",
"is_hash",
"is_last",
"is_number",
"is_odd_item",
"is_sequence",
"is_string",
"item_cycle",
"item_parity",
"j_string",
"join",
"js_string",
"json_string",
"keep_after",
"keep_after_last",
"keep_before",
"keep_before_last",
"keys",
"last",
"last_index_of",
"left_pad",
"length",
"lower_case",
"map",
"matches",
"max",
"min",
"no_esc",
"number",
"number_to_date",
"number_to_datetime",
"remove_beginning",
"remove_ending",
"replace",
"reverse",
"right_pad",
"round",
"seq_contains",
"seq_index_of",
"size",
"sort",
"sort_by",
"split",
"starts_with",
"string",
"substring",
"switch",
"take_while",
"then",
"time",
"trim",
"truncate",
"uncap_first",
"upper_case",
"url",
"values",
"word_list",
"xhtml",
"xml",
].map((label): Completion => ({ label, type: "function" }));
/** `<#…`, `</#…` and `?…` inside the template layer. */
function templateCompletion(context: CompletionContext): CompletionResult | null {
const { state } = context;
const end = context.matchBefore(/[<[]\/(?:[#@][\w.:-]*)?$/);
if (end) {
const from = end.from + 2;
const options = openBlocks(state, from).map((block, i) => ({ label: block, type: "keyword", boost: 99 - i }));
return options.length ? { from, options, validFor: /^(?:[#@][\w.:-]*)?$/ } : null;
}
const directive = context.matchBefore(/[<[]#\w*$/);
if (directive) {
if ((directive.text[0] == "[") != squareSyntax(state)) return null;
const name = /\w*$/.exec(directive.text)![0];
return { from: directive.to - name.length, options: DIRECTIVE_OPTIONS, validFor: /^\w*$/ };
}
const builtIn = context.matchBefore(/\?\w*$/);
// The `?` is a built-in's, not text or a string's.
const mark = builtIn && syntaxTree(state).resolveInner(builtIn.from + 1, -1);
if (builtIn && mark && (mark.name == "BuiltIn" || mark.parent?.name == "BuiltIn")) {
return { from: builtIn.from + 1, options: BUILT_INS, validFor: /^\w*$/ };
}
return null;
}
export function freemarker(): LanguageSupport {
return new LanguageSupport(freemarkerLanguage, [
// Before HTML's, so the template's completions come first.
baseHTML.language.data.of({ autocomplete: templateCompletion }),
baseHTML.support,
// Markup is commented out with a template comment, which FreeMarker drops from the page.
baseHTML.language.data.of({ commentTokens: FTL_COMMENT }),
freemarkerLanguage.data.of({ autocomplete: templateCompletion, commentTokens: FTL_COMMENT }),
// In the square syntax, `[#-- --]`.
Prec.highest(
EditorState.languageData.of((state, pos) =>
squareSyntax(state) && inTemplate(state, pos) ? [{ commentTokens: SQUARE_COMMENT }] : [],
),
),
Prec.high(closeBlock),
]);
}
+42
Переглянути файл
@@ -0,0 +1,42 @@
// This file was generated by lezer-generator. You probably shouldn't edit it.
export const
Comment = 1,
RawBody = 2,
Text = 3,
OpenTagStart = 4,
RawTagStart = 5,
MidTagStart = 6,
EndTagStart = 7,
StrayEndTagStart = 8,
TagStart = 9,
InterpolationStart = 10,
DirectiveName = 11,
MacroName = 12,
TagEnd = 13,
SelfCloseEnd = 14,
InterpolationEnd = 15,
Template = 16,
Interpolation = 17,
VariableName = 18,
PropertyName = 21,
BuiltInName = 24,
String = 25,
Number = 26,
Operator = 27,
CompareOp = 28,
as = 29,
_in = 30,
using = 31,
gt = 32,
gte = 33,
lt = 34,
lte = 35,
BooleanLiteral = 36,
Tag = 46,
Element = 47,
OpenTag = 48,
MidTag = 49,
EndTag = 50,
RawElement = 51,
RawTag = 52,
StrayEndTag = 53
+24
Переглянути файл
@@ -0,0 +1,24 @@
// This file was generated by lezer-generator. You probably shouldn't edit it.
import {LRParser} from "@lezer/lr"
import {comment, rawBody, text, tagStart, tagName, tagEnd, blocks} from "./tokens"
const spec_identifier = {__proto__:null,as:58, in:60, using:62, gt:64, gte:66, lt:68, lte:70, true:72, false:72}
export const parser = LRParser.deserialize({
version: 14,
states: "*nQVO]OOO!xQ#SO'#CmO#PQ!rO'#D[O#PQ!rO'#D^O#XO]O'#D]O#PQ!rO'#DbO#cOYO'#DaO#kQ#dO'#DcOOO]'#Dj'#DjOOO]'#Dd'#DdQVO]OOOOQp'#Cn'#CnO#vQ!bO'#CoO#{Q!bO'#CrO$QQ!bO'#DTO$XQ!bO'#DWO$`Q!bO'#DZOOQp'#Dk'#DkOOQp'#De'#DeO$gQ#SO,59XOOO],59X,59XOOQp'#Dm'#DmO$nQ#SO,59vO$xQ#SO,59xO#PQ!rO'#D_O%PO]O'#DfO%ZOWO,59wO%cQ#dO'#D`OOO],59w,59wO#XO]O,59wO%nQ#SO,59|OOO],59{,59{O#fOWO,59{OOO],59},59}O%uQ#SO,59}OOO]-E7b-E7bOOQp'#Cq'#CqOOQp,59Z,59ZOOQp'#Ct'#CtOOQp,59^,59^OOQp,59o,59oO%zQ!bO,59oOOQp,59r,59rO&RQ!bO,59rOOQp,59u,59uO&YQ!bO,59uOOQp-E7c-E7cOOO]1G.s1G.sO&aQ#SO1G/bOOO]1G/b1G/bO&kQ#SO1G/dOOO]1G/d1G/dO&rQ#SO,59yO&|O]O,5:QOOOW-E7d-E7dOOO]1G/c1G/cOOO],59z,59zO'WQ#SO,59zO%ZOWO1G/cO']Q#SO1G/hOOOY1G/h1G/hOOO]1G/g1G/gOOO]1G/i1G/iOOQp1G/Z1G/ZOOQp1G/^1G/^OOQp1G/a1G/aOOO]7+$|7+$|OOO]7+%O7+%OO'dQ#SO1G/eOOO]1G/e1G/eOOO]1G/f1G/fOOO]7+$}7+$}OOOY7+%S7+%SOOO]7+%P7+%P",
stateData: "'q~O!]OS~OPWORWOSROTTOWVOXQOYPO~Od[Og]OiaOjaOkaOlaOmaOnaOoaOpaOqaOraOsaOtaOv^Oy_O|`O!`ZO~O_dO~PnOZeO[eO~OUhOVkO~PVOQpOVkO~OZeO[eO]qO~O!`tO~O!`vO~OuxO~PnOxzO~PnO{|O~PnO_!PO~PnO]!RO^!RO~PnO]!TO~PnOU!YXV!YX~PVOUhOVkO~OZeO[eO]!YO~O]!^O~PnO]!`O~Ou!aO~PnOx!bO~PnO{!cO~PnO]!dO^!dO~PnO]!eO~PnO]!gO^!gO~PnOU!YaV!Ya~PVO]!hO~O]!jO~PnO]!kO^!kO~PnOi!`~",
goto: "&V!bPPPPPPPPPPPPPPPPP!c!k!kP!}!kP#QPPPPPPPPPPPPPP!kPP!kPP!k!c!c#T#]#c!c#s!c#{$Z$}PPP%X%aP%s]WOSYim!VqaP^_`cfgny{}!Q!S!U!]!fRu[Rw]]SOSYim!VXiSjm![QlSQoUS!XjmQ!_pR!i![]UOSYim!VQYOQmSUsYm!VR!ViQcPQy^Q{_Q}``!Ocy{}!Q!S!]!fQ!QfQ!SgQ!]nR!f!UQjSS!Wj![R![m]XOSYim!VqbP^_`cfgny{}!Q!S!U!]!fQfQQgRQnTQrVQ!UhR!Zk",
nodeNames: "⚠ Comment RawBody Text OpenTagStart RawTagStart MidTagStart EndTagStart StrayEndTagStart TagStart InterpolationStart DirectiveName MacroName TagEnd SelfCloseEnd InterpolationEnd Template Interpolation VariableName Member . PropertyName BuiltIn ? BuiltInName String Number Operator CompareOp as in using gt gte lt lte BooleanLiteral ) ( ParenGroup ] [ BracketGroup } { HashGroup Tag Element OpenTag MidTag EndTag RawElement RawTag StrayEndTag",
maxTerm: 63,
context: blocks,
nodeProps: [
["openedBy", 37,"(",40,"[",43,"{"],
["closedBy", 38,")",41,"]",44,"}"]
],
skippedNodes: [0],
repeatNodeCount: 3,
tokenData: ",X~RvXY#iYZ#i]^#ipq#iqr#zrs$Xtu%yuv&nvw&{wx'Txy(pyz(uz{&n{|(z|}&v}!O)V!O!P)e!P!Q&n!Q![){![!]&v!]!^&v!^!_*f!_!`#z!`!a*f!a!b*n!c!}%y!}#O*v#P#Q*{#R#S%y#T#f%y#f#g+Q#g#o%y#o#p+u#p#q+z#q#r,S$g;'S%y;'S;=`&h<%lO%y~#nS!]~XY#iYZ#i]^#ipq#i~$PPk~!_!`$S~$XOl~~$^Vi~Or$Xrs$ss#O$X#O#P$x#P;'S$X;'S;=`%s<%lO$X~$xOi~~${RO;'S$X;'S;=`%U;=`O$X~%ZWi~Or$Xrs$ss#O$X#O#P$x#P;'S$X;'S;=`%s;=`<%l$X<%lO$X~%vP;=`<%l$X~&OW!`~tu%y!Q![%y!c!}%y#R#S%y#T#o%y$g;'S%y;'S;=`&h<%lO%y~&kP;=`<%l%y~&sPk~!_!`&v~&{Ok~~'QPk~vw&v~'YVi~Ow'Twx$sx#O'T#O#P'o#P;'S'T;'S;=`(j<%lO'T~'rRO;'S'T;'S;=`'{;=`O'T~(QWi~Ow'Twx$sx#O'T#O#P'o#P;'S'T;'S;=`(j;=`<%l'T<%lO'T~(mP;=`<%l'T~(uOv~~(zOu~~)PQk~{|&v!_!`&v~)[Rk~}!O&v!_!`&v!`!a&v~)jPd~!O!P)m~)rRk~qr&vz{&v!^!_&v~*QQj~!O!P*W!Q![){~*ZP!Q![*^~*cPj~!Q![*^~*kPl~!_!`$S~*sPg~!a!b&v~*{Oy~~+QOx~~+VY!`~rs$Xtu%ywx'T!Q![%y!c!}%y#R#S%y#T#o%y$g;'S%y;'S;=`&h<%lO%y~+zO|~~,PPk~#p#q&v~,XO{~",
tokenizers: [comment, rawBody, text, tagStart, tagName, tagEnd, 0],
topRules: {"Template":[0,16]},
specialized: [{term: 62, get: (value: keyof typeof spec_identifier) => spec_identifier[value] || -1}],
tokenPrec: 306
})
+350
Переглянути файл
@@ -0,0 +1,350 @@
/**
* External tokens of `freemarker.grammar`: the text between template elements, the
* comments, the raw content of `noparse`, the start of each tag, classified by its name
* against the blocks open around it, the tag's name and the delimiters that end tags
* and interpolations, which depend on the tag syntax.
*/
import { ContextTracker, ExternalTokenizer, type InputStream, type Stack } from "@lezer/lr";
import {
Comment,
DirectiveName,
Element,
EndTagStart,
InterpolationEnd,
InterpolationStart,
MacroName,
MidTagStart,
OpenTagStart,
RawBody,
RawElement,
RawTagStart,
SelfCloseEnd,
StrayEndTagStart,
TagEnd,
TagStart,
Text,
} from "./parser.terms";
const LT = 60,
GT = 62,
SLASH = 47,
HASH = 35,
AT = 64,
DOLLAR = 36,
EQ = 61,
BRACE_L = 123,
BRACE_R = 125,
BRACKET_L = 91,
BRACKET_R = 93,
PAREN_L = 40,
PAREN_R = 41,
DASH = 45,
QUOTE = 34,
APOS = 39,
BACKSLASH = 92,
BANG = 33;
/** Block directives, with the middle tags each one allows. */
export const BLOCK_DIRECTIVES: ReadonlyMap<string, readonly string[]> = new Map([
["attempt", ["recover"]],
["autoesc", []],
["compress", []],
["escape", []],
["function", []],
["if", ["elseif", "else"]],
["items", []],
["list", ["else"]],
["macro", []],
["noautoesc", []],
["noescape", []],
["outputformat", []],
["switch", ["case", "default", "on"]],
]);
/** `<#assign x>…</#assign>`: these capture their content when they have no `=`. */
export const CAPTURING: ReadonlySet<string> = new Set(["assign", "global", "local"]);
/** Directives whose content FreeMarker doesn't parse. */
export const RAW_DIRECTIVES: ReadonlySet<string> = new Set(["noparse", "comment"]);
/** Every built-in directive, for completion. */
export const DIRECTIVES = [
"assign",
"attempt",
"autoesc",
"break",
"case",
"compress",
"continue",
"default",
"else",
"elseif",
"escape",
"fallback",
"flush",
"ftl",
"function",
"global",
"if",
"import",
"include",
"items",
"list",
"local",
"lt",
"macro",
"nested",
"noautoesc",
"noescape",
"noparse",
"nt",
"on",
"outputformat",
"recover",
"recurse",
"return",
"rt",
"sep",
"setting",
"stop",
"switch",
"t",
"visit",
];
/** The blocks open around a position, innermost first, and the tag syntax (`null`: not fixed yet). */
class Context {
readonly hash: number;
constructor(
/** `#if`, `@badge`. */
readonly name: string | null,
readonly parent: Context | null,
readonly square: boolean | null,
) {
let hash = parent ? parent.hash : square === null ? 1 : square ? 2 : 3;
for (let i = 0; name && i < name.length; i++) hash = ((hash << 5) - hash + name.charCodeAt(i)) | 0;
this.hash = hash;
}
}
const TOP = new Context(null, null, null);
const isNameStart = (ch: number) => (ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122) || ch == 95;
const isName = (ch: number) => isNameStart(ch) || (ch >= 48 && ch <= 57);
/** User-defined directive names may be qualified (`lib.badge`) or carry `:` and `-`. */
const isMacroName = (ch: number) => isName(ch) || ch == 46 || ch == 58 || ch == DASH;
/** A tag opening `offset` code units ahead: its kind, sigil and name. */
interface TagHead {
/** Code units up to the name. */
length: number;
end: boolean;
sigil: "#" | "@";
name: string;
square: boolean;
}
function tagHead(input: InputStream, offset: number, square: boolean | null): TagHead | null {
const open = input.peek(offset);
if (open == LT ? square === true : open == BRACKET_L ? square === false : true) return null;
let i = offset + 1;
const end = input.peek(i) == SLASH;
if (end) i++;
const sigil = input.peek(i);
if (sigil != HASH && sigil != AT) return null;
i++;
let name = "";
const accept = sigil == HASH ? isName : isMacroName;
for (let ch; accept((ch = input.peek(i))); i++) {
if (!name && !isNameStart(ch)) break;
name += String.fromCharCode(ch);
}
// `<#--` is a comment, `</@>` ends the innermost call; anything else needs a name.
if (!name && !(end && sigil == AT)) return null;
return { length: i - offset - name.length, end, sigil: sigil == HASH ? "#" : "@", name, square: open == BRACKET_L };
}
const commentAt = (input: InputStream, offset: number, square: boolean | null) => {
const open = input.peek(offset);
return (
(open == LT ? square !== true : open == BRACKET_L && square !== false) &&
input.peek(offset + 1) == HASH &&
input.peek(offset + 2) == DASH &&
input.peek(offset + 3) == DASH
);
};
const interpolationAt = (input: InputStream, offset: number, square: boolean | null) => {
const ch = input.peek(offset);
return (
(ch == DOLLAR && input.peek(offset + 1) == BRACE_L) ||
(square === true && ch == BRACKET_L && input.peek(offset + 1) == EQ)
);
};
/** Whether a comment, a tag or an interpolation starts `offset` code units ahead. */
function elementStart(input: InputStream, offset: number, square: boolean | null): boolean {
const ch = input.peek(offset);
if (ch != LT && ch != BRACKET_L && ch != DOLLAR) return false;
return interpolationAt(input, offset, square) || commentAt(input, offset, square) || !!tagHead(input, offset, square);
}
/** How far a tag scan looks for the tag's end. */
const MAX_TAG = 4000;
/**
* The rest of a tag after its name: whether it ends with `/>` (`/]`) and whether it has an
* assignment `=` outside brackets, skipping strings and brackets.
*/
function tagTail(input: InputStream, offset: number, square: boolean): { selfClosing: boolean; assigns: boolean } {
const close = square ? BRACKET_R : GT;
let depth = 0;
let assigns = false;
for (let i = offset; i < offset + MAX_TAG; i++) {
const ch = input.peek(i);
if (ch < 0) break;
if (ch == QUOTE || ch == APOS) {
for (i++; ; i++) {
const c = input.peek(i);
if (c < 0 || c == ch) break;
if (c == BACKSLASH) i++;
}
continue;
}
if (ch == PAREN_L || ch == BRACE_L || ch == BRACKET_L) {
depth++;
continue;
}
if (depth > 0 && (ch == PAREN_R || ch == BRACE_R || ch == BRACKET_R)) {
depth--;
continue;
}
if (depth == 0 && ch == close) return { selfClosing: input.peek(i - 1) == SLASH, assigns };
if (depth == 0 && ch == EQ) {
const before = input.peek(i - 1);
const after = input.peek(i + 1);
if (after != EQ && before != EQ && before != BANG && before != LT && before != GT) assigns = true;
}
}
return { selfClosing: false, assigns };
}
export const blocks = new ContextTracker<Context>({
start: TOP,
shift(context, term, _stack, input) {
const opens = term == OpenTagStart || term == RawTagStart;
const tag = opens || term == MidTagStart || term == EndTagStart || term == StrayEndTagStart || term == TagStart;
if (!tag) return context;
const square = context.square ?? input.next == BRACKET_L;
if (!opens) return square === context.square ? context : fixSyntax(context, square);
const head = tagHead(input, 0, square);
const base = square === context.square ? context : fixSyntax(context, square);
return new Context(head ? head.sigil + head.name : null, base, square);
},
reduce(context, term) {
return (term == Element || term == RawElement) && context.parent ? context.parent : context;
},
hash: (context) => context.hash,
strict: false,
});
/** `context` with the tag syntax fixed, for the blocks around it too. */
function fixSyntax(context: Context, square: boolean): Context {
return context.parent
? new Context(context.name, fixSyntax(context.parent, square), square)
: new Context(null, null, square);
}
/** `<#-- … -->` (`[#-- … --]`), to the end of the document when unterminated. */
export const comment = new ExternalTokenizer((input, stack: Stack) => {
const context: Context = stack.context;
if (!commentAt(input, 0, context.square)) return;
const close = input.next == BRACKET_L ? BRACKET_R : GT;
input.advance(4);
for (let ch; (ch = input.next) >= 0;) {
if (ch == DASH && input.peek(1) == DASH && input.peek(2) == close) {
input.advance(3);
break;
}
input.advance();
}
input.acceptToken(Comment);
});
/** Template text: up to a tag, an interpolation or a comment. */
export const text = new ExternalTokenizer((input, stack: Stack) => {
const square = (stack.context as Context).square;
const start = input.pos;
while (input.next >= 0 && !elementStart(input, 0, square)) input.advance();
if (input.pos > start) input.acceptToken(Text);
});
/** The opening delimiter of a tag or an interpolation, a token telling what it is in the blocks open around it. */
export const tagStart = new ExternalTokenizer((input, stack: Stack) => {
const context: Context = stack.context;
if (interpolationAt(input, 0, context.square)) {
if (stack.canShift(InterpolationStart)) input.acceptToken(InterpolationStart, 2);
return;
}
const head = tagHead(input, 0, context.square);
if (!head) return;
const open = context.name;
const name = head.sigil + head.name;
let term = TagStart;
if (head.end) {
term =
open && (name == open || (head.sigil == "@" && !head.name && open.startsWith("@")))
? EndTagStart
: StrayEndTagStart;
} else if (head.sigil == "#" && RAW_DIRECTIVES.has(head.name)) {
term = RawTagStart;
} else if (open?.startsWith("#") && BLOCK_DIRECTIVES.get(open.slice(1))?.includes(head.name)) {
term = MidTagStart;
} else if (head.sigil == "@" || BLOCK_DIRECTIVES.has(head.name) || CAPTURING.has(head.name)) {
const tail = tagTail(input, head.length + head.name.length, head.square);
const block = !tail.selfClosing && (!CAPTURING.has(head.name) || !tail.assigns);
if (block) term = OpenTagStart;
}
if (!stack.canShift(term)) term = term == EndTagStart ? StrayEndTagStart : TagStart;
if (stack.canShift(term)) input.acceptToken(term, head.length);
});
/** A tag's name: a directive's (`if`) or a user-defined directive's (`lib.badge`). */
export const tagName = new ExternalTokenizer((input) => {
const sigil = input.peek(-1);
if (sigil != HASH && sigil != AT) return;
const accept = sigil == HASH ? isName : isMacroName;
if (!isNameStart(input.next)) return;
while (accept(input.next)) input.advance();
input.acceptToken(sigil == HASH ? DirectiveName : MacroName);
});
/** `>` / `/>` (`]` / `/]`) ending a tag, `}` (`]`) ending an interpolation. */
export const tagEnd = new ExternalTokenizer((input, stack: Stack) => {
const square = (stack.context as Context).square === true;
const close = square ? BRACKET_R : GT;
if (input.next == SLASH && input.peek(1) == close) {
if (stack.canShift(SelfCloseEnd)) input.acceptToken(SelfCloseEnd, 2);
return;
}
if (input.next == close && stack.canShift(TagEnd)) {
input.acceptToken(TagEnd, 1);
return;
}
if ((input.next == BRACE_R || (square && input.next == BRACKET_R)) && stack.canShift(InterpolationEnd)) {
input.acceptToken(InterpolationEnd, 1);
}
});
/** The content of `noparse` or `comment`: up to the end tag closing it. */
export const rawBody = new ExternalTokenizer((input, stack: Stack) => {
const context: Context = stack.context;
const name = context.name;
if (!name) return;
const start = input.pos;
for (; input.next >= 0; input.advance()) {
const head = (input.next == LT || input.next == BRACKET_L) && tagHead(input, 0, context.square);
if (head && head.end && head.sigil + head.name == name) break;
}
if (input.pos > start) input.acceptToken(RawBody);
});