summaryrefslogtreecommitdiff
path: root/library/src
diff options
context:
space:
mode:
authorMartin Haug <mhaug@live.de>2022-12-29 11:49:01 +0100
committerMartin Haug <mhaug@live.de>2022-12-29 11:49:01 +0100
commitbc535f7b7169d9e0ef26faca108518f4005cc76c (patch)
tree029b76a80215243420d48e0f54e5fdcc8d2869a2 /library/src
parent94b90761ebbdf33686e82feb5a89f98d049c5b65 (diff)
`read` function
Diffstat (limited to 'library/src')
-rw-r--r--library/src/compute/data.rs39
-rw-r--r--library/src/lib.rs1
2 files changed, 39 insertions, 1 deletions
diff --git a/library/src/compute/data.rs b/library/src/compute/data.rs
index a018c09a..a519e8e6 100644
--- a/library/src/compute/data.rs
+++ b/library/src/compute/data.rs
@@ -4,6 +4,40 @@ use typst::diag::{format_xml_like_error, FileError};
use crate::prelude::*;
+/// # Read file
+/// Read plain text from a file.
+///
+/// The file will be read and returned as a string.
+///
+/// ## Example
+/// ```
+/// #let text = read("data.html")
+///
+/// An HTML file could look like this:
+/// #raw(text, lang: "html")
+/// ```
+///
+/// ## Parameters
+/// - path: EcoString (positional, required)
+/// Path to a file.
+///
+/// - returns: EcoString
+///
+/// ## Category
+/// data-loading
+#[func]
+pub fn read(vm: &Vm, args: &mut Args) -> SourceResult<Value> {
+ let Spanned { v: path, span } = args.expect::<Spanned<EcoString>>("path to file")?;
+
+ let path = vm.locate(&path).at(span)?;
+ let data = vm.world().file(&path).at(span)?;
+
+ let text = String::from_utf8(data.to_vec())
+ .map_err(|_| "file is not valid utf-8")
+ .at(span)?;
+ Ok(Value::Str(text.into()))
+}
+
/// # CSV
/// Read structured data from a CSV file.
///
@@ -184,7 +218,10 @@ fn convert_json(value: serde_json::Value) -> Value {
/// Format the user-facing JSON error message.
fn format_json_error(error: serde_json::Error) -> String {
assert!(error.is_syntax() || error.is_eof());
- format!("failed to parse json file: syntax error in line {}", error.line())
+ format!(
+ "failed to parse json file: syntax error in line {}",
+ error.line()
+ )
}
/// # XML
diff --git a/library/src/lib.rs b/library/src/lib.rs
index a4c6fc30..e345bbee 100644
--- a/library/src/lib.rs
+++ b/library/src/lib.rs
@@ -124,6 +124,7 @@ fn scope() -> Scope {
std.def_func::<compute::EvenFunc>("even");
std.def_func::<compute::OddFunc>("odd");
std.def_func::<compute::ModFunc>("mod");
+ std.def_func::<compute::ReadFunc>("read");
std.def_func::<compute::CsvFunc>("csv");
std.def_func::<compute::JsonFunc>("json");
std.def_func::<compute::XmlFunc>("xml");