// Front matter: the metadata block at the top of a page, layout or data file.
// Map an opening delimiter to the format that parses the block.
///|
fn front_matter_format(delimiter : StringView) -> String? {
match delimiter.to_owned() {
"---" => Some("yaml")
";;;" => Some("json")
"+++" => Some("toml")
_ => None
}
}
///|
/// Split a source file into front matter data and the remaining body.
///
/// `---` opens YAML, `;;;` opens JSON and `+++` opens TOML front matter; the
/// block ends at the next line holding the same delimiter. Anything else is
/// body text and the data is an empty object.
pub fn split_front_matter_with(
text : StringView,
formats : FormatRegistry,
) -> (Json, String) {
let all = @core.lines(text)
if all.length() == 0 {
return (Json::object(Map([])), text.to_owned())
}
let first = @core.trim(all[0])
let format = match front_matter_format(first) {
Some(name) => name
None => return (Json::object(Map([])), text.to_owned())
}
let mut end = -1
for i = 1; i < all.length(); i = i + 1 {
if @core.trim(all[i]) == first {
end = i
break
}
}
if end < 0 {
return (Json::object(Map([])), text.to_owned())
}
let header : Array[String] = []
for i = 1; i < end; i = i + 1 {
header.push(all[i])
}
let body_lines : Array[String] = []
for i = end + 1; i < all.length(); i = i + 1 {
body_lines.push(all[i])
}
let data = formats.parse(header.join("\n"), format)
(data, body_lines.join("\n"))
}
///|
/// Split front matter using the built-in format registry.
pub fn split_front_matter(text : StringView) -> (Json, String) {
split_front_matter_with(text, FormatRegistry::builtin())
}
///|
/// Detect a front matter block that opens but never closes.
pub fn has_unclosed_front_matter(text : StringView) -> Bool {
let all = @core.lines(text)
if all.length() == 0 {
return false
}
let first = @core.trim(all[0])
if front_matter_format(first) is None {
return false
}
for i = 1; i < all.length(); i = i + 1 {
if @core.trim(all[i]) == first {
return false
}
}
true
}