cm6-lezer-lit-html
v0.2.1
Published
CodeMirror 6 mixed parser: highlight lit-html tagged template literals (html`...`) using Lezer parseMixed.
Readme
cm6-lezer-lit-html
A small CodeMirror 6 helper that uses Lezer’s mixed parsing (parseMixed) to parse/highlight lit-html tagged template literals like:
import {html} from "lit";
const view = html`
<button @click=${() => console.log("hi")}>
Hello <span>${name}</span>
</button>
`;Under the hood it keeps the normal JavaScript/TypeScript parse tree, and overlays an HTML parse tree on top of the template string content (excluding ${...} interpolations), using parseMixed.
Install
npm i cm6-lezer-lit-htmlUsage
JavaScript
import {EditorView, basicSetup} from "codemirror";
import {litJavaScript} from "cm6-lezer-lit-html";
new EditorView({
parent: document.body,
doc: 'const t = html`<div class="x">${y}</div>`',
extensions: [basicSetup, litJavaScript()]
});TypeScript
import {litTypeScript} from "cm6-lezer-lit-html";
extensions: [basicSetup, litTypeScript()]Customization
You can customize which tags are treated as templates and/or the HTML parser used:
import {litHtmlWrap} from "cm6-lezer-lit-html";
import {javascriptLanguage} from "@codemirror/lang-javascript";
import {htmlLanguage} from "@codemirror/lang-html";
const myLitLanguage = javascriptLanguage.configure({
wrap: litHtmlWrap({
tags: ["html", "svg", "myTag"],
htmlParser: htmlLanguage.parser
})
});Lit-specific attribute nodes
By default, the HTML parser used inside templates is further wrapped to mount
Lit-specific nodes on top of HTML AttributeName nodes when they start with
Lit binding prefixes:
LitEventAttributefor@click/@eventLitPropertyAttributefor.value/.propLitBooleanAttributefor?disabled/?boolLitSpreadAttributefor...spread(if you use this pattern)
These nodes appear in the syntax tree (via Lezer mixed parsing) so you can query/style them separately.
You can turn this off with:
litHtmlWrap({litAttributeNodes: false})Notes / limitations
- The overlay ranges are computed from the JavaScript parser’s template string children (it looks for interpolation nodes—usually named
Interpolation). If you use a very old@lezer/javascriptversion that doesn’t produce interpolation nodes, you may need to adjust thetemplateStringOverlayRangeslogic. - This package focuses on lit-html style template literals. It doesn’t attempt to validate that the template is “valid lit” (it just checks the tag name).
License
MIT
