[csswg-drafts] CSS syntax highlighting proposal (#9247)

dragoncoder047 has just created a new issue for https://github.com/w3c/csswg-drafts:

== CSS syntax highlighting proposal ==
This would be similar to the existing [CSS Painting API](https://developer.mozilla.org/en-US/docs/Web/API/CSS_Painting_API).

Basically any text-color-affecting property (idk the proper term) would be able to use a new `syntax()` function to define which syntax grammar for the text that gets highlighted, and the individual tokens could be styled using the `::token()` pseudo-element.

So for example:

```css
::token(comment) { color: gray }
::token(tag-name) { color: red } /* these are really bad colors */
::token(attr-name) { color: blue }
::token(attr-value) { color: green }
textarea.language-html { color: syntax(html, black) }
 /* black is the fallback color if the text is not in a token */
```

and bam, instant syntax-highlited textarea.

Browsers would have built-in `html`, `css`, and `js` grammars, obviously (utilizing the existing parsers -- side effect is the grammar evolves with the language standard!), and for everything else there could be a plugin-based approach like the CSS Paint API. Something like `CSS.syntaxHighlighting.addModule("path/to/worker.js")`. Haven't bothered to think about how the worker would be passed the string to highlight (differential/incremental edits? highlight the whole string every time?), provide tokens to the browser (state machine? something else?), etc.

I don't think defining a *grammar* as opposed to a *worker* would be a good idea because that would be prone to bias towards a particular grammar definition, because there are tons of different kinds ([PrismJS](https://prismjs.com/), [highlight.js](https://highlightjs.org/), [Rainbow](https://craig.is/making/rainbows), [Pygments](https://pygments.org/), [GeSHi](http://qbnz.com/highlighter/), [Tree-sitter](https://tree-sitter.github.io/tree-sitter/), [TextMate](https://macromates.com/manual/en/language_grammars), even Emacs modes, just to name a few...)

One other thing I think would be useful would be a way for the CSS engine to signal it doesn't have a particular grammar registered, and prompt auto-loading via Javascript:

```js
CSS.syntaxHighlighting.addEventListener("language-not-found", e => {
    CSS.syntaxHighlighting.addModule(`/path/to/grammars/${e.language}.js`);
});
```

@LeaVerou would probably be a good person to comment on this proposal (for obvious reasons).

Please view or discuss this issue at https://github.com/w3c/csswg-drafts/issues/9247 using your GitHub account


-- 
Sent via github-notify-ml as configured in https://github.com/w3c/github-notify-ml-config

Received on Saturday, 26 August 2023 13:27:00 UTC