Custom Formatters
Write your own formatter when the built-in ones don't produce the output you need. Common reasons:
- wrap output with custom HTML
- emit Markdown, LaTeX, or a structured AST
- add annotations, data attributes, or extra classes
- feed Lumis tokens into an existing rendering pipeline
Rust
Implement the Formatter trait.
use lumis::{
formatters::Formatter,
formatters::html::{open_pre_tag, open_code_tag, closing_tags, span_inline},
highlight::highlight_iter,
languages::Language,
themes,
};
use std::io::{self, Write};
struct MinimalHtmlFormatter {
language: Language,
theme: Option<themes::Theme>,
}
impl Formatter for MinimalHtmlFormatter {
fn format(&self, source: &str, output: &mut dyn Write) -> io::Result<()> {
open_pre_tag(output, None, self.theme.as_ref())?;
open_code_tag(output, &self.language)?;
highlight_iter(source, self.language, self.theme.clone(), |text, language, _range, scope, _style| {
write!(output, "{}", span_inline(text, Some(language), scope, self.theme.as_ref(), false, false))
})
.map_err(io::Error::other)?;
closing_tags(output)?;
Ok(())
}
}
JavaScript
Pass an object with language and format(source). Inside format(), use the sync free functions highlightIter() or highlightEvents() imported from @lumis-sh/lumis.
import {createHighlighter, highlightIter} from '@lumis-sh/lumis'
import type {Formatter} from '@lumis-sh/lumis/formatters'
import {openPreTag, openCodeTag, closingTags, spanInline} from '@lumis-sh/lumis/formatters/html'
import rust from '@lumis-sh/lumis/langs/rust'
import dracula from '@lumis-sh/themes/dracula'
const hl = await createHighlighter({languages: [rust]})
const formatter: Formatter = {
language: rust,
format(source) {
const parts: string[] = []
parts.push(openPreTag({preClass: 'docs-demo', theme: dracula}))
parts.push(openCodeTag(this.language))
highlightIter(source, this.language, dracula, (text, language, _range, scope, _style) => {
if (scope) {
parts.push(spanInline(text, {language, scope, theme: dracula}))
} else {
parts.push(text)
}
})
parts.push(closingTags())
return parts.join('')
},
}
const html = hl.highlight('fn main() {}', formatter)
Available helpers
| Runtime | Module | Reference |
|---|---|---|
| JavaScript | @lumis-sh/lumis/formatters/html | source |
| JavaScript | @lumis-sh/lumis/formatters/ansi | source |
| Rust | lumis::formatters::html | docs.rs |
| Rust | lumis::formatters::ansi | docs.rs |
Tip
Copy the built-in formatter closest to what you want, then strip out what you don't need.