typst_library/loading/
read.rs

1use ecow::EcoString;
2use typst_syntax::Spanned;
3
4use crate::diag::{LoadedWithin, SourceResult};
5use crate::engine::Engine;
6use crate::foundations::{Cast, func};
7use crate::loading::{DataSource, Load, Readable};
8
9/// Reads plain text or data from a file.
10///
11/// By default, the file will be read as UTF-8 and returned as a [string]($str).
12///
13/// If you specify `{encoding: none}`, this returns raw [bytes] instead.
14///
15/// # Example
16/// ```example
17/// An example for a HTML file: \
18/// #let text = read("example.html")
19/// #raw(text, lang: "html")
20///
21/// Raw bytes:
22/// #read("tiger.jpg", encoding: none)
23/// ```
24#[func]
25pub fn read(
26    engine: &mut Engine,
27    /// Path to a file.
28    ///
29    /// For more details, see the [Paths section]($syntax/#paths).
30    path: Spanned<EcoString>,
31    /// The encoding to read the file with.
32    ///
33    /// If set to `{none}`, this function returns raw bytes.
34    #[named]
35    #[default(Some(Encoding::Utf8))]
36    encoding: Option<Encoding>,
37) -> SourceResult<Readable> {
38    let loaded = path.map(DataSource::Path).load(engine.world)?;
39    Ok(match encoding {
40        None => Readable::Bytes(loaded.data),
41        Some(Encoding::Utf8) => Readable::Str(loaded.data.to_str().within(&loaded)?),
42    })
43}
44
45/// An encoding of a file.
46#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Cast)]
47pub enum Encoding {
48    /// The Unicode UTF-8 encoding.
49    Utf8,
50}