use std::ops::Range;
use comrak::{
Arena,
nodes::{AstNode, NodeValue},
};
use super::{CodeBlock, parse};
pub(super) fn lines(text: &str) -> Vec<Range<usize>> {
each_line(text).collect()
}
pub(super) fn each_line(text: &str) -> impl Iterator<Item = Range<usize>> + '_ {
let bytes = text.as_bytes();
let mut start = 0;
let mut i = 0;
let mut done = false;
std::iter::from_fn(move || {
while i < bytes.len() {
let ending = match bytes[i] {
b'\r' if bytes.get(i + 1) == Some(&b'\n') => 2,
b'\n' | b'\r' => 1,
_ => 0,
};
i += ending.max(1);
if ending > 0 {
let line = start..i - ending;
start = i;
return Some(line);
}
}
(!std::mem::replace(&mut done, true)).then_some(start..bytes.len())
})
}
fn content_lines(content: &str) -> usize {
each_line(content).count() - usize::from(content.is_empty() || content.ends_with(['\n', '\r']))
}
pub(super) fn span(first: usize, end: usize, fenced: bool, content: &str) -> (usize, usize) {
let kept = content_lines(content.trim_end_matches([' ', '\t', '\n', '\r']));
if !fenced {
return (first, first + kept.saturating_sub(1));
}
let closed = end > first + content_lines(content);
(first, if closed { end } else { first + kept })
}
pub(super) fn code_blocks<'a>(
root: &'a AstNode<'a>,
lines: &[Range<usize>],
) -> Vec<(usize, usize, CodeBlock)> {
let past = lines.last().map_or(0, |l| l.end);
let line = |n: usize| n.checked_sub(1).and_then(|i| lines.get(i));
root.descendants()
.filter_map(|node| {
let ast = node.data();
let NodeValue::CodeBlock(code) = &ast.value else {
return None;
};
let sp = ast.sourcepos;
let (first, last) = span(sp.start.line, sp.end.line, code.fenced, &code.literal);
let start = line(first).map_or(past, |l| l.start);
let end = line(last).map_or(past, |l| l.end);
let block = CodeBlock {
bytes: start..end,
fenced: code.fenced,
};
Some((first, last, block))
})
.collect()
}
pub(super) fn fenced(text: &str) -> Vec<Range<usize>> {
if !text.contains("```") && !text.contains("~~~") {
return Vec::new();
}
let arena = Arena::new();
let root = comrak::parse_document(&arena, text, &parse::options());
code_blocks(root, &lines(text))
.into_iter()
.filter(|(_, _, b)| b.fenced)
.map(|(_, _, b)| b.bytes)
.collect()
}
#[cfg(test)]
mod tests;