How do you show syntax highlighting in a displayed code snippet?

I’ve found that highlight.js has syntax highlighting for displayed code snippets but I could not find documentation for how to use it in conjunction with elm.

What do I do in order highlight displayed code like an IDE does with elm via 3rd party code or built in?

I don’t know the API of highlight.js, but maybe you could wrap it in a custom element: Custom Elements · An Introduction to Elm

I think you can simply load highlight.js as usual in your index.html, then all <pre><code> will be highlighted:

Another way is to load highlight.js in your index.html and use elm-explorations/markdown:

Here is an example using javascript (the default version includes 34 languages):
https://ellie-app.com/7mbxTyMHXkqa1

Note that this will embed markedjs which is included in elm-explorations/markdown, so there is a significant impact on assets size if you don’t already embed it. elm-explorations/markdown is also experimental and might not be available in future Elm versions.

That relies on changing DOM, which is not recommended as that can cause all kinds of problems with Elm’s virtual DOM.

Ah right, I’m sorry. I think it’s safe though to use it through elm-explorations/markdown, as this is how the package website works. Also see https://package.elm-lang.org/packages/elm-explorations/markdown/latest/#code-blocks.

I have edited my example. This does not use the theme background color though, likely because elm-explorations/markdown calls the highlighter on the content only.

Or try https://package.elm-lang.org/packages/pablohirafuji/elm-syntax-highlight/latest/ if your language is supported. I never used it but it looks nice, and no javascript needed.

3 Likes

I’ve used highlightJS with Elm in the past and it works fines as long as you don’t have to alter the node tree where the highlightJS elements are after you rendered it the first time. IIRC JS libraries like highlightJS (which alter the DOM by themselves) don’t play well with Elm’s Virtual DOM. Due to this, in my experiment, I could properly highlight code blocks, but after tried to alter the node tree (e.g., collapse a part of the code) everything got messed up

Have you tried https://package.elm-lang.org/packages/pablohirafuji/elm-syntax-highlight/latest/

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.