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