Repository navigation
Closed
Labels
Description
When using typst embedded in custom code using the Rust API, it's already trivial to provide the main file from some non-filesystem source (e.g. include_str!()). This is great because it allows to produce a single binary containing everything needed w/o any auxiliary files.
However, doing the same with fonts is extremely cumbersome and requires extremely ugly code due to the use of private fields:
Details
static FONT_DATA: OnceLock<(
LazyHash<FontBook>,
Arc<Vec<FontSlot>>,
usize,
Arc<Vec<Font>>,
)> = OnceLock::new();
impl TypstWrapperWorld {
fn new(source: &str, inputs: Dict) -> Self {
let (book, fonts, custom_font_offset, custom_fonts) = FONT_DATA.get_or_init(|| {
let mut fonts = FontSearcher::new().include_system_fonts(false).search();
let mut offset = 0;
loop {
if fonts.book.info(offset).is_none() {
break;
}
offset += 1;
}
let mut custom_fonts = Vec::new();
for font in Font::iter(Bytes::new(include_bytes!(
"../typst/LiberationSans-Regular.ttf"
))) {
fonts.book.push(font.info().clone());
custom_fonts.push(font);
}
(
LazyHash::new(fonts.book),
Arc::new(fonts.fonts),
offset,
Arc::new(custom_fonts),
)
});
Self {
source: Source::detached(source),
library: LazyHash::new(Library::builder().with_inputs(inputs).build()),
book: book.clone(),
fonts: Arc::clone(fonts),
custom_font_offset: *custom_font_offset,
custom_fonts: Arc::clone(custom_fonts),
}
}
}
impl typst::World for TypstWrapperWorld {
fn font(&self, id: usize) -> Option<Font> {
if id >= self.custom_font_offset {
self.custom_fonts.get(id - self.custom_font_offset).cloned()
} else {
self.fonts[id].get()
}
}
// ...
}It would be nice if the FontSearcher (or probably more likely the Fonts object it produces) had an add_from_bytes function which adds the provided font (coming e.g. from include_bytes!()) to the collection.
I wouldn't mind sending a PR implementing this if you're open to this functionality.
Reacted by Rafael Villar Burke (Pachi), CrumblyLiquid, Bastien Voirin and Willi Eggeling
Activity
laurmaedje commentedon Dec 18, 2025
I'm open to this in principle. Not sure about the best API design off the top of my head.