#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum OpenEol {
#[default]
Lf,
Crlf,
}
impl OpenEol {
pub const fn as_str(self) -> &'static str {
match self {
OpenEol::Lf => "\n",
OpenEol::Crlf => "\r\n",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CloseEol {
None,
Lf,
Crlf,
}
impl CloseEol {
pub const fn as_str(self) -> &'static str {
match self {
CloseEol::None => "",
CloseEol::Lf => "\n",
CloseEol::Crlf => "\r\n",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct NoteShape {
pub bom: bool,
pub open_eol: OpenEol,
pub close_eol: CloseEol,
pub close_sep: bool,
}
#[derive(Debug, Clone, Copy, Default)]
pub struct NewShapeOptions {
pub eol: OpenEol,
pub bom: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Split<'a> {
pub yaml: Option<&'a str>,
pub yaml_range: std::ops::Range<usize>,
pub body: &'a str,
pub body_start: usize,
pub shape: NoteShape,
pub unterminated: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct LenientSplit<'a> {
pub yaml: &'a str,
pub body: &'a str,
}
const BOM: &str = "\u{feff}";
pub fn new_shape(opts: NewShapeOptions) -> NoteShape {
let close_eol = match opts.eol {
OpenEol::Lf => CloseEol::Lf,
OpenEol::Crlf => CloseEol::Crlf,
};
NoteShape {
bom: opts.bom,
open_eol: opts.eol,
close_eol,
close_sep: true,
}
}
pub fn split(src: &str) -> Split<'_> {
let (bom, rest, offset) = match src.strip_prefix(BOM) {
Some(rest) => (true, rest, BOM.len()),
None => (false, src, 0),
};
let no_frontmatter = |unterminated: bool| Split {
yaml: None,
yaml_range: 0..0,
body: rest,
body_start: offset,
shape: NoteShape {
bom,
open_eol: OpenEol::Lf,
close_eol: CloseEol::Lf,
close_sep: true,
},
unterminated,
};
let (after_marker, marker_len, open_eol) = if let Some(r) = rest.strip_prefix("---\n") {
(r, 4, OpenEol::Lf)
} else if let Some(r) = rest.strip_prefix("---\r\n") {
(r, 5, OpenEol::Crlf)
} else {
return no_frontmatter(false);
};
let yaml_start = offset + marker_len;
for (fence, len, close_eol) in [
("---\n", 4usize, CloseEol::Lf),
("---\r\n", 5, CloseEol::Crlf),
] {
if let Some(r) = after_marker.strip_prefix(fence) {
return Split {
yaml: Some(""),
yaml_range: yaml_start..yaml_start,
body: r,
body_start: yaml_start + len,
shape: NoteShape {
bom,
open_eol,
close_eol,
close_sep: false,
},
unterminated: false,
};
}
}
if after_marker == "---" {
return Split {
yaml: Some(""),
yaml_range: yaml_start..yaml_start,
body: "",
body_start: src.len(),
shape: NoteShape {
bom,
open_eol,
close_eol: CloseEol::None,
close_sep: false,
},
unterminated: false,
};
}
let bytes = after_marker.as_bytes();
let mut search_start = 0usize;
loop {
let Some(found) = after_marker[search_start..].find("\n---") else {
return no_frontmatter(true);
};
let dashes_start = search_start + found + 1;
let after_dashes = dashes_start + 3;
let (yaml_len, body_rel, close_eol) = match bytes.get(after_dashes).copied() {
None => (dashes_start - 1, after_marker.len(), CloseEol::None),
Some(b'\n') => (dashes_start - 1, after_dashes + 1, CloseEol::Lf),
Some(b'\r') if bytes.get(after_dashes + 1) == Some(&b'\n') => {
(dashes_start - 1, after_dashes + 2, CloseEol::Crlf)
}
_ => {
search_start = after_dashes;
continue;
}
};
return Split {
yaml: Some(&after_marker[..yaml_len]),
yaml_range: yaml_start..yaml_start + yaml_len,
body: &after_marker[body_rel..],
body_start: yaml_start + body_rel,
shape: NoteShape {
bom,
open_eol,
close_eol,
close_sep: true,
},
unterminated: false,
};
}
}
pub fn compose(frontmatter: Option<&str>, body: &str, shape: NoteShape) -> String {
let mut out = String::new();
if shape.bom {
out.push_str(BOM);
}
let Some(yaml) = frontmatter else {
out.push_str(body);
return out;
};
out.push_str("---");
out.push_str(shape.open_eol.as_str());
out.push_str(yaml);
if shape.close_sep || !yaml.is_empty() {
out.push('\n');
}
out.push_str("---");
if shape.close_eol == CloseEol::None && !body.is_empty() {
out.push_str(shape.open_eol.as_str());
} else {
out.push_str(shape.close_eol.as_str());
}
out.push_str(body);
out
}
pub fn split_lenient(content: &str) -> Option<LenientSplit<'_>> {
let start = content.strip_prefix(BOM).unwrap_or(content).trim_start();
let (open, rest) = start.split_once('\n')?;
if open.trim_end() != "---" {
return None;
}
let mut offset = 0;
for line in rest.split_inclusive('\n') {
if line.trim_end() == "---" {
let raw = &rest[..offset];
let yaml = raw.strip_suffix('\n').unwrap_or(raw);
let yaml = yaml.strip_suffix('\r').unwrap_or(yaml);
return Some(LenientSplit {
yaml,
body: &rest[offset + line.len()..],
});
}
offset += line.len();
}
None
}
#[cfg(test)]
mod tests {
use super::*;
fn lenient(content: &str) -> Option<(&str, &str)> {
split_lenient(content).map(|ls| (ls.yaml, ls.body))
}
#[test]
fn splits_a_plain_note() {
let s = split("---\ntitle: hi\n---\nbody\n");
assert_eq!(s.yaml, Some("title: hi"));
assert_eq!(s.body, "body\n");
assert!(!s.shape.bom);
assert!(!s.unterminated);
}
#[test]
fn a_note_with_no_frontmatter_is_all_body() {
let s = split("no fence here");
assert_eq!(s.yaml, None);
assert_eq!(s.body, "no fence here");
assert!(!s.unterminated);
}
#[test]
fn an_unterminated_block_is_all_body() {
let s = split("---\ntitle: hi\nstill going\n");
assert_eq!(s.yaml, None);
assert_eq!(s.body, "---\ntitle: hi\nstill going\n");
assert!(s.unterminated);
}
#[test]
fn a_fence_followed_by_other_text_does_not_close_the_block() {
let src = "---\na: 1\n---x\nb: 2\n---\nbody\n";
let s = split(src);
assert_eq!(s.yaml, Some("a: 1\n---x\nb: 2"));
assert_eq!(s.body, "body\n");
assert!(!s.unterminated);
assert_eq!(compose(s.yaml, s.body, s.shape), src);
let s = split("---\na: 1\n---x\n");
assert_eq!(s.yaml, None);
assert_eq!(s.body, "---\na: 1\n---x\n");
assert!(s.unterminated);
let s = split("---\na\n---\rb\n");
assert_eq!(s.yaml, None);
assert!(s.unterminated);
}
#[test]
fn crlf_keeps_the_carriage_return_on_the_yaml_side() {
let s = split("---\r\ntitle: hi\r\n---\r\nbody\r\n");
assert_eq!(s.yaml, Some("title: hi\r"));
assert_eq!(s.body, "body\r\n");
assert_eq!(s.shape.open_eol, OpenEol::Crlf);
assert_eq!(s.shape.close_eol, CloseEol::Crlf);
}
#[test]
fn a_bom_is_tolerated_and_remembered() {
let s = split("\u{feff}---\ntitle: hi\n---\nbody\n");
assert_eq!(s.yaml, Some("title: hi"));
assert_eq!(s.body, "body\n");
assert!(s.shape.bom);
}
#[test]
fn yaml_range_indexes_the_original_source() {
let src = "\u{feff}---\ntitle: hi\n---\nbody\n";
let s = split(src);
assert_eq!(&src[s.yaml_range.clone()], "title: hi");
assert_eq!(&src[s.body_start..], "body\n");
}
#[test]
fn empty_frontmatter_is_recognised() {
let s = split("---\n---\nbody\n");
assert_eq!(s.yaml, Some(""));
assert_eq!(s.body, "body\n");
assert!(!s.shape.close_sep);
}
#[test]
fn a_body_containing_a_fence_does_not_confuse_the_split() {
let s = split("---\na: 1\n---\nintro\n\n---\n\noutro\n");
assert_eq!(s.yaml, Some("a: 1"));
assert_eq!(s.body, "intro\n\n---\n\noutro\n");
}
#[test]
fn new_shape_defaults_to_lf_fences() {
let shape = new_shape(NewShapeOptions::default());
assert_eq!(shape.open_eol, OpenEol::Lf);
assert_eq!(shape.close_eol, CloseEol::Lf);
assert!(shape.close_sep);
assert!(!shape.bom);
assert_eq!(
compose(Some("title: A"), "# A\n", shape),
"---\ntitle: A\n---\n# A\n"
);
}
#[test]
fn new_shape_honours_crlf_and_bom() {
let shape = new_shape(NewShapeOptions {
eol: OpenEol::Crlf,
bom: true,
});
assert_eq!(shape.open_eol, OpenEol::Crlf);
assert_eq!(shape.close_eol, CloseEol::Crlf);
assert_eq!(
compose(Some("a: 1\r"), "b\r\n", shape),
"\u{feff}---\r\na: 1\r\n---\r\nb\r\n"
);
}
#[test]
fn compose_round_trips_a_split() {
for src in [
"---\na: 1\n---\nbody\n",
"\u{feff}---\na: 1\n---\nbody\n",
"just a body\n",
"\u{feff}just a body\n", "---\n---\nbody\n", "---\n\n---\nbody\n", "---\n\n\n---\nbody\n", "---\na: 1\n\n---\nbody\n", ] {
let s = split(src);
let out = compose(s.yaml, s.body, s.shape);
assert_eq!(out, src, "round trip failed for {src:?}");
}
}
#[test]
fn a_file_ending_at_the_closing_fence_round_trips() {
for src in ["---\na: 1\n---", "---\na: 1\n---\n", "---\r\na: 1\r\n---"] {
let s = split(src);
assert_eq!(compose(s.yaml, s.body, s.shape), src, "for {src:?}");
}
}
#[test]
fn yaml_written_into_an_empty_block_gets_its_own_line() {
for (src, yaml, want) in [
("---\n---\nbody\n", "title: x", "---\ntitle: x\n---\nbody\n"),
(
"---\r\n---\r\nbody\r\n",
"title: x\r",
"---\r\ntitle: x\r\n---\r\nbody\r\n",
),
] {
let s = split(src);
let out = compose(Some(yaml), s.body, s.shape);
assert_eq!(out, want, "for {src:?}");
assert_eq!(split(&out).yaml, Some(yaml), "for {src:?}");
}
}
#[test]
fn a_body_added_after_a_closing_fence_at_the_end_gets_its_own_line() {
for (src, yaml, body, want) in [
(
"---\ntitle: x\n---",
"title: x",
"new\n",
"---\ntitle: x\n---\nnew\n",
),
(
"---\r\ntitle: x\r\n---",
"title: x\r",
"new\r\n",
"---\r\ntitle: x\r\n---\r\nnew\r\n",
),
("---\n---", "", "new\n", "---\n---\nnew\n"),
] {
let s = split(src);
let out = compose(Some(yaml), body, s.shape);
assert_eq!(out, want, "for {src:?}");
let back = split(&out);
assert_eq!((back.yaml, back.body), (Some(yaml), body), "for {src:?}");
}
}
#[test]
fn a_bom_without_frontmatter_is_framing_not_body() {
let s = split("\u{feff}just prose\n");
assert!(s.shape.bom);
assert_eq!(s.yaml, None);
assert_eq!(s.body, "just prose\n", "the BOM stays out of the body");
assert_eq!(compose(s.yaml, s.body, s.shape), "\u{feff}just prose\n");
}
#[test]
fn lenient_tolerates_leading_whitespace_and_fence_padding() {
assert_eq!(
lenient(" ---\ntitle: x\n---\nbody\n"),
Some(("title: x", "body\n"))
);
assert_eq!(
lenient("--- \ntitle: x\n--- \nbody\n"),
Some(("title: x", "body\n"))
);
assert_eq!(lenient("\u{feff}\n\n---\na: 1\n---\n"), Some(("a: 1", "")));
assert_eq!(
lenient("---\r\na: 1\r\n---\r\nbody\r\n"),
Some(("a: 1", "body\r\n"))
);
assert_eq!(lenient("---\n---\nbody\n"), Some(("", "body\n")));
}
#[test]
fn lenient_returns_none_without_a_block() {
assert_eq!(lenient("no frontmatter\n"), None);
assert_eq!(lenient("---\nunterminated\n"), None);
assert_eq!(lenient(""), None);
}
#[test]
fn lenient_still_needs_a_bare_fence_to_close() {
assert_eq!(
lenient("---\na: 1\n---below\nb: 2\n---\nbody\n"),
Some(("a: 1\n---below\nb: 2", "body\n"))
);
}
}