craft-captions: WebVTT cue-text arrow escape is reversible

Ported from storytold/filmcraft#4437. A literal --> in cue text came back as
--> after a write and parse; the writer now adds one amp; level and the reader
removes exactly one.
This commit is contained in:
NetterSilver
2026-11-11 23:14:27 +00:00
committed by Dylan M. Taylor
parent b994b31bbe
commit aa490f4ed0
+59 -2
View File
@@ -52,7 +52,53 @@ pub fn split_voice(text: &str) -> (Option<String>, String) {
/// as a timing line to anything scanning the block, so it is written `--&gt;`. Other entities
/// (`&amp;`, `&lt;`, …) are cue markup and stay verbatim, as `parse` has always kept them.
fn unescape_text(text: &str) -> String {
text.replace("--&gt;", "-->")
rewrite_arrows(text, false)
}
/// Apply [`write`]'s cue-text escape. `-->` becomes `--&gt;`, and a literal `--&gt;` (or the same
/// with more `&amp;` in front of `gt;`) gains one `&amp;`, so the escape is reversible.
fn escape_text(text: &str) -> String {
rewrite_arrows(text, true)
}
/// Treat `--&` + `amp;`×k + `gt;` as level k, and `-->` as level -1. Escaping raises the level by
/// one, unescaping lowers it by one; anything else is copied unchanged.
fn rewrite_arrows(text: &str, escape: bool) -> String {
let mut out = String::with_capacity(text.len());
let mut rest = text;
while let Some(c) = rest.chars().next() {
if let Some(after) = rest.strip_prefix("--") {
if escape && after.starts_with('>') {
out.push_str("--&gt;");
rest = &after[1..];
continue;
}
let mut tail = after.strip_prefix('&').unwrap_or("\0");
let mut k = 0usize;
while let Some(t) = tail.strip_prefix("amp;") {
tail = t;
k += 1;
}
if let Some(t) = tail.strip_prefix("gt;") {
if escape {
out.push_str("--&");
out.push_str(&"amp;".repeat(k + 1));
out.push_str("gt;");
} else if k == 0 {
out.push_str("-->");
} else {
out.push_str("--&");
out.push_str(&"amp;".repeat(k - 1));
out.push_str("gt;");
}
rest = t;
continue;
}
}
out.push(c);
rest = &rest[c.len_utf8()..];
}
out
}
pub fn parse(text: &str) -> Result<Document> {
@@ -146,7 +192,7 @@ pub fn write(doc: &Document) -> String {
}
text.push_str(&c.text);
for l in text.lines().filter(|l| !l.trim().is_empty()) {
out.push_str(&l.replace("-->", "--&gt;"));
out.push_str(&escape_text(l));
out.push('\n');
}
out.push('\n');
@@ -267,6 +313,17 @@ mod tests {
assert_eq!(write(&back), w, "stable from there on");
}
/// A literal `--&gt;` in cue text must not turn into `-->` on a round trip.
#[test]
fn a_literal_escaped_arrow_survives_a_round_trip() {
for text in ["a --&gt; b", "a --> b", "--&amp;gt;", "---&gt;-->", "x --&amp;amp;gt; y"] {
let mut d = Document::default();
d.cues.push(Cue { start: Tick(0), end: Tick(1000 * TICKS_PER_MS), text: text.into(), ..Cue::default() });
let back = parse(&write(&d)).unwrap();
assert_eq!(back.cues[0].text, text);
}
}
/// Only the writer's own `-->` escape is reversed: cue markup keeps its entities verbatim,
/// as `parse` has always done.
#[test]