Skip to main content

typst_template/
world.rs

1//! The Typst [`World`] split into a reusable base and per-generation concrete
2//! worlds.
3
4use std::collections::HashMap;
5use std::path::{Path, PathBuf};
6use std::sync::Arc;
7use std::{fmt, fs};
8
9use typst::diag::{FileError, FileResult, SourceResult, Warned};
10use typst::foundations::{Bytes, Datetime, Dict, Duration, Str};
11use typst::syntax::{FileId, RootedPath, Source, VirtualPath, VirtualRoot};
12use typst::text::{Font, FontBook};
13use typst::utils::LazyHash;
14use typst::{Library, LibraryExt, World};
15use typst_kit::fonts::{self, FontStore};
16use typst_layout::PagedDocument;
17use typst_pdf::{PdfOptions, pdf};
18
19use crate::value::{ToDict, ToValue};
20
21/// A long-lived, cheaply cloneable Typst world.
22///
23/// Holds the project root and the loaded font set. Build a `WorldBase` once and
24/// derive a [`ConcreteWorld`] from it for each document via
25/// [`concrete`](Self::concrete). Cloning shares the fonts through an [`Arc`].
26#[derive(Clone)]
27#[must_use]
28pub struct WorldBase {
29    inner: Arc<WorldBaseInner>,
30}
31
32struct WorldBaseInner {
33    root: PathBuf,
34    fonts: FontStore,
35}
36
37impl fmt::Debug for WorldBase {
38    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39        f.debug_struct("WorldBase")
40            .field("root", &self.inner.root)
41            .finish_non_exhaustive()
42    }
43}
44
45/// Builder for a [`WorldBase`].
46///
47/// By default both system and embedded fonts are searched; add extra font
48/// directories with [`font_path`](Self::font_path).
49#[derive(Debug, Clone)]
50#[must_use]
51pub struct WorldBaseConfig {
52    root: PathBuf,
53    font_paths: Vec<PathBuf>,
54    system_fonts: bool,
55    embedded_fonts: bool,
56}
57
58impl WorldBaseConfig {
59    /// Starts a config rooted at `root`. Real files are resolved relative to it.
60    pub fn new(root: impl Into<PathBuf>) -> Self {
61        Self { root: root.into(), font_paths: Vec::new(), system_fonts: true, embedded_fonts: true }
62    }
63
64    /// Adds a directory to search for fonts (searched recursively).
65    pub fn font_path(mut self, path: impl Into<PathBuf>) -> Self {
66        self.font_paths.push(path.into());
67        self
68    }
69
70    /// Adds several font directories.
71    pub fn font_paths<P: Into<PathBuf>>(mut self, paths: impl IntoIterator<Item = P>) -> Self {
72        self.font_paths.extend(paths.into_iter().map(Into::into));
73        self
74    }
75
76    /// Whether to include fonts installed on the system (default `true`).
77    pub fn system_fonts(mut self, include: bool) -> Self {
78        self.system_fonts = include;
79        self
80    }
81
82    /// Whether to include the fonts embedded in `typst-assets` (default `true`).
83    pub fn embedded_fonts(mut self, include: bool) -> Self {
84        self.embedded_fonts = include;
85        self
86    }
87
88    /// Builds the base, searching for fonts now.
89    pub fn build(self) -> WorldBase {
90        // Priority follows load order: font paths, then system, then embedded.
91        let mut store = FontStore::new();
92        for path in &self.font_paths {
93            store.extend(fonts::scan(path));
94        }
95        if self.system_fonts {
96            store.extend(fonts::system());
97        }
98        if self.embedded_fonts {
99            store.extend(fonts::embedded());
100        }
101        let inner = WorldBaseInner { root: self.root, fonts: store };
102        WorldBase { inner: Arc::new(inner) }
103    }
104}
105
106impl WorldBase {
107    /// Builds a base rooted at `root` with the default font configuration.
108    ///
109    /// Use [`WorldBaseConfig`] for finer control.
110    pub fn new(root: impl Into<PathBuf>) -> Self {
111        WorldBaseConfig::new(root).build()
112    }
113
114    /// Starts building a [`ConcreteWorld`] whose main file is `main` (a path
115    /// relative to the root, or a virtual path added with
116    /// [`file`](ConcreteWorldBuilder::file)).
117    pub fn concrete(&self, main: impl AsRef<Path>) -> ConcreteWorldBuilder {
118        ConcreteWorldBuilder {
119            base: self.clone(),
120            main: file_id(main),
121            inputs: Dict::new(),
122            files: HashMap::new(),
123            today: Today::default(),
124        }
125    }
126}
127
128impl WorldBaseInner {
129    fn load_file(&self, id: FileId) -> FileResult<Vec<u8>> {
130        let path = id
131            .vpath()
132            .realize(&self.root)
133            .map_err(|_| FileError::AccessDenied)?;
134        // TODO: Cache reads in the base and re-validate against mtime on the
135        // next request. See TODO.md ("Disk file read cache").
136        fs::read(&path).map_err(|err| match err.kind() {
137            std::io::ErrorKind::NotFound => FileError::NotFound(path),
138            std::io::ErrorKind::PermissionDenied => FileError::AccessDenied,
139            std::io::ErrorKind::IsADirectory => FileError::IsDirectory,
140            _ => FileError::Other(Some(format!("{err}").into())),
141        })
142    }
143}
144
145/// Builder for a [`ConcreteWorld`].
146#[derive(Clone)]
147#[must_use]
148pub struct ConcreteWorldBuilder {
149    base: WorldBase,
150    main: FileId,
151    inputs: Dict,
152    files: HashMap<FileId, Bytes>,
153    today: Today,
154}
155
156impl fmt::Debug for ConcreteWorldBuilder {
157    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
158        f.debug_struct("ConcreteWorldBuilder")
159            .field("main", &self.main)
160            .field("inputs", &self.inputs)
161            .finish_non_exhaustive()
162    }
163}
164
165impl ConcreteWorldBuilder {
166    /// Sets the whole `sys.inputs` dictionary, replacing any earlier inputs.
167    pub fn inputs(mut self, inputs: impl ToDict) -> Self {
168        self.inputs = inputs.into_dict();
169        self
170    }
171
172    /// Adds a single `sys.inputs` entry.
173    pub fn input(mut self, key: impl Into<Str>, value: impl ToValue) -> Self {
174        self.inputs.insert(key.into(), value.into_value());
175        self
176    }
177
178    /// Adds a virtual in-memory file at `path`, visible to the document instead
179    /// of any real file at that path.
180    pub fn file(mut self, path: impl AsRef<Path>, content: impl Into<Vec<u8>>) -> Self {
181        self.files.insert(file_id(path), Bytes::new(content.into()));
182        self
183    }
184
185    /// Pins `datetime.today()` to a fixed value.
186    ///
187    /// Answers only offset-less (`auto`) requests; `datetime.today(offset: N)`
188    /// returns nothing.
189    pub fn today(mut self, today: Datetime) -> Self {
190        self.today = Today::Fixed(today);
191        self
192    }
193
194    /// Makes `datetime.today()` read the system clock, treating "local" as the
195    /// operating system's time zone.
196    ///
197    /// With the `time` backend, "local" falls back to UTC when the OS offset is
198    /// unavailable (e.g. in a multithreaded process); use
199    /// [`today_system_in`](Self::today_system_in) for a specific zone.
200    #[cfg(any(feature = "chrono", feature = "time"))]
201    #[cfg_attr(docsrs, doc(cfg(any(feature = "chrono", feature = "time"))))]
202    pub fn today_system(mut self) -> Self {
203        self.today = Today::SystemLocal;
204        self
205    }
206
207    /// Makes `datetime.today()` read the system clock, treating "local" as the
208    /// given named time zone (DST-aware).
209    ///
210    /// Accepts a [`chrono_tz::Tz`](crate::chrono_tz::Tz) (feature `chrono-tz`)
211    /// or a `&'static` [`time_tz::Tz`](crate::time_tz::Tz) (feature `time-tz`)
212    /// via [`Into<Zone>`](Zone).
213    #[cfg(any(feature = "chrono-tz", feature = "time-tz"))]
214    #[cfg_attr(docsrs, doc(cfg(any(feature = "chrono-tz", feature = "time-tz"))))]
215    pub fn today_system_in(mut self, zone: impl Into<Zone>) -> Self {
216        self.today = Today::SystemZone(zone.into());
217        self
218    }
219
220    /// Makes `datetime.today()` return nothing.
221    pub fn today_disabled(mut self) -> Self {
222        self.today = Today::Disabled;
223        self
224    }
225
226    /// Builds the concrete world.
227    pub fn build(self) -> ConcreteWorld {
228        let library = Library::builder().with_inputs(self.inputs).build();
229        ConcreteWorld {
230            base: self.base.inner,
231            library: LazyHash::new(library),
232            files: self.files,
233            main: self.main,
234            today: self.today,
235        }
236    }
237}
238
239/// A single-document world: a [`WorldBase`] plus this generation's inputs and
240/// virtual files.
241///
242/// Build one via [`WorldBase::concrete`], then call
243/// [`render_pdf`](Self::render_pdf).
244#[must_use]
245pub struct ConcreteWorld {
246    base: Arc<WorldBaseInner>,
247    library: LazyHash<Library>,
248    files: HashMap<FileId, Bytes>,
249    main: FileId,
250    today: Today,
251}
252
253impl fmt::Debug for ConcreteWorld {
254    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
255        f.debug_struct("ConcreteWorld")
256            .field("main", &self.main)
257            .finish_non_exhaustive()
258    }
259}
260
261impl ConcreteWorld {
262    /// Adds (or replaces) a virtual in-memory file after construction.
263    pub fn add_file(&mut self, path: impl AsRef<Path>, content: impl Into<Vec<u8>>) {
264        self.files.insert(file_id(path), Bytes::new(content.into()));
265    }
266
267    /// Compiles the document, returning the paged document (or errors) together
268    /// with any warnings.
269    pub fn compile(&self) -> Warned<SourceResult<PagedDocument>> {
270        typst::compile(self)
271    }
272
273    /// Compiles and exports to PDF, returning the bytes (or errors) together
274    /// with any compile warnings.
275    pub fn render_pdf(&self, options: &PdfOptions) -> Warned<SourceResult<Vec<u8>>> {
276        let Warned { output, warnings } = self.compile();
277        let output = output.and_then(|document| pdf(&document, options));
278        Warned { output, warnings }
279    }
280
281    /// Like [`render_pdf`](Self::render_pdf) with [`PdfOptions::default`].
282    pub fn render_pdf_default(&self) -> Warned<SourceResult<Vec<u8>>> {
283        self.render_pdf(&PdfOptions::default())
284    }
285
286    fn read(&self, id: FileId) -> FileResult<Bytes> {
287        match self.files.get(&id) {
288            Some(bytes) => Ok(bytes.clone()),
289            None => Ok(Bytes::new(self.base.load_file(id)?)),
290        }
291    }
292}
293
294impl World for ConcreteWorld {
295    fn library(&self) -> &LazyHash<Library> {
296        &self.library
297    }
298
299    fn book(&self) -> &LazyHash<FontBook> {
300        self.base.fonts.book()
301    }
302
303    fn main(&self) -> FileId {
304        self.main
305    }
306
307    fn source(&self, id: FileId) -> FileResult<Source> {
308        let bytes = self.read(id)?;
309        let text = std::str::from_utf8(&bytes).map_err(|_| FileError::InvalidUtf8)?;
310        Ok(Source::new(id, text.to_owned()))
311    }
312
313    fn file(&self, id: FileId) -> FileResult<Bytes> {
314        self.read(id)
315    }
316
317    fn font(&self, index: usize) -> Option<Font> {
318        self.base.fonts.font(index)
319    }
320
321    fn today(&self, offset: Option<Duration>) -> Option<Datetime> {
322        // typst treats an integer `datetime.today` offset as hours, but a caller
323        // may pass a finer duration (e.g. UTC+5:30), so carry full seconds.
324        self.today.resolve(offset.map(|d| d.seconds() as i64))
325    }
326}
327
328/// How the world answers `datetime.today()`.
329#[derive(Clone)]
330enum Today {
331    /// `datetime.today()` returns nothing.
332    Disabled,
333    /// A fixed value; answers only offset-less requests.
334    Fixed(Datetime),
335    /// The system clock, with "local" meaning the operating system's time zone.
336    #[cfg(any(feature = "chrono", feature = "time"))]
337    SystemLocal,
338    /// The system clock, with "local" meaning a named time zone.
339    #[cfg(any(feature = "chrono-tz", feature = "time-tz"))]
340    SystemZone(Zone),
341}
342
343/// Defaults to the system clock when a `chrono`/`time` feature is enabled,
344/// otherwise leaves `datetime.today()` disabled.
345impl Default for Today {
346    fn default() -> Self {
347        #[cfg(any(feature = "chrono", feature = "time"))]
348        {
349            Today::SystemLocal
350        }
351        #[cfg(not(any(feature = "chrono", feature = "time")))]
352        {
353            Today::Disabled
354        }
355    }
356}
357
358impl Today {
359    fn resolve(&self, offset_secs: Option<i64>) -> Option<Datetime> {
360        match self {
361            Today::Disabled => None,
362            // A fixed value answers only offset-less requests.
363            Today::Fixed(today) => match offset_secs {
364                None => Some(*today),
365                Some(_) => None,
366            },
367            #[cfg(any(feature = "chrono", feature = "time"))]
368            Today::SystemLocal => match offset_secs {
369                Some(secs) => offset_now(secs),
370                None => local_now(),
371            },
372            #[cfg(any(feature = "chrono-tz", feature = "time-tz"))]
373            // An explicit offset overrides the configured zone.
374            Today::SystemZone(zone) => match offset_secs {
375                Some(secs) => offset_now(secs),
376                None => zone.now(),
377            },
378        }
379    }
380}
381
382/// A named time zone for [`today_system_in`](ConcreteWorldBuilder::today_system_in).
383///
384/// Build one with `.into()` from a [`chrono_tz::Tz`](crate::chrono_tz::Tz)
385/// (feature `chrono-tz`) or a `&'static` [`time_tz::Tz`](crate::time_tz::Tz)
386/// (feature `time-tz`). Both features may be enabled at once.
387#[cfg(any(feature = "chrono-tz", feature = "time-tz"))]
388#[derive(Clone)]
389pub struct Zone(ZoneRepr);
390
391#[cfg(any(feature = "chrono-tz", feature = "time-tz"))]
392impl fmt::Debug for Zone {
393    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
394        f.debug_struct("Zone").finish_non_exhaustive()
395    }
396}
397
398#[cfg(any(feature = "chrono-tz", feature = "time-tz"))]
399#[derive(Clone)]
400enum ZoneRepr {
401    #[cfg(feature = "chrono-tz")]
402    Chrono(chrono_tz::Tz),
403    #[cfg(feature = "time-tz")]
404    Time(&'static time_tz::Tz),
405}
406
407#[cfg(feature = "chrono-tz")]
408impl From<chrono_tz::Tz> for Zone {
409    fn from(tz: chrono_tz::Tz) -> Self {
410        Zone(ZoneRepr::Chrono(tz))
411    }
412}
413
414#[cfg(feature = "time-tz")]
415impl From<&'static time_tz::Tz> for Zone {
416    fn from(tz: &'static time_tz::Tz) -> Self {
417        Zone(ZoneRepr::Time(tz))
418    }
419}
420
421#[cfg(any(feature = "chrono-tz", feature = "time-tz"))]
422impl Zone {
423    fn now(&self) -> Option<Datetime> {
424        match &self.0 {
425            #[cfg(feature = "chrono-tz")]
426            ZoneRepr::Chrono(tz) => {
427                use chrono::{Datelike, Timelike, Utc};
428                let now = Utc::now().with_timezone(tz);
429                crate::convert::datetime(
430                    now.year(),
431                    now.month() as u8,
432                    now.day() as u8,
433                    now.hour() as u8,
434                    now.minute() as u8,
435                    now.second() as u8,
436                )
437            }
438            #[cfg(feature = "time-tz")]
439            ZoneRepr::Time(tz) => {
440                use time::OffsetDateTime;
441                use time_tz::OffsetDateTimeExt;
442                let now = OffsetDateTime::now_utc().to_timezone(*tz);
443                crate::convert::datetime(
444                    now.year(),
445                    u8::from(now.month()),
446                    now.day(),
447                    now.hour(),
448                    now.minute(),
449                    now.second(),
450                )
451            }
452        }
453    }
454}
455
456/// The current time in the OS-local time zone, via `chrono`.
457#[cfg(feature = "chrono")]
458fn local_now() -> Option<Datetime> {
459    use chrono::{Datelike, Local, Timelike};
460    let now = Local::now().naive_local();
461    crate::convert::datetime(
462        now.year(),
463        now.month() as u8,
464        now.day() as u8,
465        now.hour() as u8,
466        now.minute() as u8,
467        now.second() as u8,
468    )
469}
470
471/// The current time via `time`. Falls back to UTC when the OS-local offset is
472/// unavailable (e.g. in a multithreaded process); use
473/// [`today_system_in`](ConcreteWorldBuilder::today_system_in) for a specific
474/// zone.
475#[cfg(all(feature = "time", not(feature = "chrono")))]
476fn local_now() -> Option<Datetime> {
477    use time::OffsetDateTime;
478    let now = OffsetDateTime::now_local().unwrap_or_else(|_| OffsetDateTime::now_utc());
479    crate::convert::datetime(now.year(), u8::from(now.month()), now.day(), now.hour(), now.minute(), now.second())
480}
481
482/// The current time at a fixed UTC offset (in seconds). Uses `chrono` if
483/// enabled, otherwise `time`. Returns `None` if the offset is too large to apply.
484#[cfg(feature = "chrono")]
485fn offset_now(secs: i64) -> Option<Datetime> {
486    use chrono::{Datelike, Duration, Timelike, Utc};
487    let now = Utc::now()
488        .checked_add_signed(Duration::try_seconds(secs)?)?
489        .naive_utc();
490    crate::convert::datetime(
491        now.year(),
492        now.month() as u8,
493        now.day() as u8,
494        now.hour() as u8,
495        now.minute() as u8,
496        now.second() as u8,
497    )
498}
499
500#[cfg(all(feature = "time", not(feature = "chrono")))]
501fn offset_now(secs: i64) -> Option<Datetime> {
502    use time::OffsetDateTime;
503    let now = OffsetDateTime::now_utc().checked_add(time::Duration::seconds(secs))?;
504    crate::convert::datetime(now.year(), u8::from(now.month()), now.day(), now.hour(), now.minute(), now.second())
505}
506
507// Builds a project-root-relative file id. Typst virtual paths are
508// `/`-separated; accept the platform separator too (so `PathBuf`s built on
509// Windows work) and resolve `.`/`..` so a stray `..` clamps at the root instead
510// of erroring.
511fn file_id(path: impl AsRef<Path>) -> FileId {
512    let raw = path.as_ref().to_string_lossy();
513    let mut segments: Vec<&str> = Vec::new();
514    for segment in raw.split(['/', '\\']) {
515        match segment {
516            "" | "." => {}
517            ".." => {
518                segments.pop();
519            }
520            normal => segments.push(normal),
521        }
522    }
523    // Only normal segments remain, so this cannot escape the root or hit a
524    // backslash — the two ways `VirtualPath::new` can fail.
525    let vpath = VirtualPath::new(segments.join("/")).expect("normalized path is a valid vpath");
526    FileId::new(RootedPath::new(VirtualRoot::Project, vpath))
527}