lezer-template-plaintext
v0.1.0
Published
A Lezer grammar for parsing template plaintext
Maintainers
Readme
lezer-template-plaintext
A Lezer grammar for parsing template plaintext (plaintext with {{variable}} holes) with incremental parsing support and TypeScript definitions.
Install
npm i lezer-template-plaintextFeatures
- Parse free-form plaintext with
{{variable}}holes - Backslash escapes for
{,}, and\\both in text and inside variables - Incremental parsing ready for editors
Usage
Basic
import { parser } from "lezer-template-plaintext";
const tree = parser.parse(
"Hello \\{world\\} and {{name}}! \{\{ not a variable"
);
console.log(tree.toString());With CodeMirror
import {
parser,
templatePlaintextHighlighting,
} from "lezer-template-plaintext";
import { LRLanguage } from "@codemirror/language";
import { HighlightStyle, syntaxHighlighting } from "@codemirror/language";
const templatePlaintextLanguage = LRLanguage.define({
parser,
languageData: { name: "template-plaintext" },
});
const highlightStyle = HighlightStyle.define([templatePlaintextHighlighting]);
const extensions = [
templatePlaintextLanguage,
syntaxHighlighting(highlightStyle),
];Tree Navigation
import { parser } from "lezer-template-plaintext";
import * as terms from "lezer-template-plaintext";
const tree = parser.parse("Hi {{first}} {{last}}! \{escaped\}");
const cursor = tree.cursor();
do {
if (cursor.type.id === terms.Variable) {
console.log("Found variable at:", cursor.from, cursor.to);
}
} while (cursor.next());Error Handling
import { parser } from "lezer-template-plaintext";
function parseWithErrors(pattern: string) {
const tree = parser.parse(pattern);
const errors: { from: number; to: number; message: string }[] = [];
tree.iterate({
enter: (node) => {
if (node.type.isError) {
errors.push({
from: node.from,
to: node.to,
message: `Syntax error at ${node.from}-${node.to}`,
});
}
},
});
return { tree, errors };
}API
Exports
parser- Lezer parser instancetemplatePlaintextHighlighting- CodeMirror syntax highlighting- Grammar terms - Node type constants for tree navigation (e.g.
Variable)
Types
parser.parse(input: string, fragments?: TreeFragment[], ranges?: {from: number, to: number}[]): TreeDevelopment
git clone https://github.com/Sec-ant/lezer-template-plaintext
cd lezer-template-plaintext
pnpm install
pnpm build
pnpm testCommands:
pnpm test:run- Run all testspnpm test:ui- Interactive test UI
Contributing
- Fork the repository
- Create a feature branch
- Add tests in
tests/fixtures/ - Ensure tests pass
- Submit a pull request
License
MIT
