Introducing Microlighter
I have developed a compact client-side syntax highlighter that leverages the CSS Custom Highlights API named Microlighter. Before diving into its features, I briefly explain the motivation behind its creation. On my Jekyll blog, I encountered an issue with broken syntax highlighting. Over the years, I have experimented with various syntax highlighters such as Highlight.js, PrismJS, Rouge, and Shiki.
Each option had its trade-offs in terms of client-side or server-side implementation. Seeking an alternative, I decided to explore Bramus's technique of syntax highlighting using the CSS Custom Highlights API. Although there are limitations with the CSS ::highlight() pseudo-class—such as no italics, bold, or font swapping—it provides a clean way to express highlighting tokens via CSS.
By utilizing the Highlight API, I can avoid any DOM mutations and keep the library lightweight, with a focus on scanning code blocks using regex patterns and updating CSS.highlights.set(category, textRanges) to highlight the code blocks. My site doesn't require extensive syntax highlighting, and most posts contain short code samples.
Moreover, I frequently switch between different programming languages within a single post, making it challenging to manage regex patterns for multiple languages. To address this complexity, I decided to utilize Textmate's existing collections of language patterns, similar to those used by VS Code. To simplify the process further, I flattened down the granular token categories from Textmate into a more user-friendly set, making it easier to style the highlighted code.
Furthermore, I merged the light and dark themes into a single theme using the light-dark() function, as they are often considered as separate entities. Lastly, I aimed to keep the syntax highlighter's primary function focused on inferring the language and highlighting the code accordingly. All additional features, like line numbers, are separated into a web component to enable better separation of concerns and easier maintenance.
To use Microlighter, you can start with the self-initializing minified bundle or choose between the ESM version for custom development or the web component for added features. The web component's classes are easily extendable, allowing you to customize it according to your needs. You can explore one of the pre-supplied themes or create your own by following the basic structure outlined in the Microlighter documentation.
Written by urgent.news from Lobsters's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.