use std::ops::RangeInclusive;
use super::{Block, BlockDetail, BlockKind, Body};
pub fn fenced_lines(body: &Body, text: &str) -> Vec<RangeInclusive<usize>> {
fn walk(blocks: &[Block], fenced: &mut Vec<RangeInclusive<usize>>, code: &mut Vec<usize>) {
for b in blocks {
if b.kind == BlockKind::Code {
code.push(b.line);
if matches!(b.detail, BlockDetail::Code { fence, .. } if fence > 0) {
fenced.push(b.line..=b.end_line);
}
}
for u in &b.units {
walk(&u.nested, fenced, code);
}
}
}
let mut out = Vec::new();
let mut code = Vec::new();
walk(&body.blocks, &mut out, &mut code);
code.sort_unstable();
let quoted: Vec<&(usize, usize)> = body
.fenced
.iter()
.filter(|(start, _)| code.binary_search(start).is_err())
.collect();
if !quoted.is_empty() {
let lines: Vec<&str> = text.lines().collect();
out.extend(
quoted
.into_iter()
.filter(|&&(start, _)| {
start
.checked_sub(1)
.and_then(|i| lines.get(i))
.is_some_and(|line| opens_quoted_fence(line))
})
.map(|&(start, end)| start..=end),
);
out.sort_by_key(|r| *r.start());
}
out
}
fn opens_quoted_fence(line: &str) -> bool {
let mut rest = line;
loop {
let indent = rest.len() - rest.trim_start_matches(' ').len();
if indent > 3 {
return false;
}
let trimmed = &rest[indent..];
match trimmed.strip_prefix('>') {
Some(after) => rest = after.strip_prefix([' ', '\t']).unwrap_or(after),
None => return trimmed.starts_with("```") || trimmed.starts_with("~~~"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_quoted_fence_opens_after_the_marks_of_its_quotes() {
for line in [
"> ```",
">```",
">> ~~~rust",
" > ```",
">\t```",
"> > ```",
] {
assert!(opens_quoted_fence(line), "{line}");
}
for line in ["> ```", " > ```", "> text", ""] {
assert!(!opens_quoted_fence(line), "{line}");
}
}
}