typst_library/loading/
read.rs

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