use super::block::CODE_INDENT;
use super::flavor::Flavor;
use super::inline;
use super::line::{Indent, Line};
use super::tree::{Block, FencedBlock};
use crate::node::{Code, Math, Node, Point, Position};
pub(super) struct Fence<'a> {
marker: u8,
length: usize,
info: &'a str,
}
impl<'a> Fence<'a> {
pub(super) fn open(rest: &'a str, flavor: Flavor) -> Option<Self> {
let math = flavor.has_math();
let marker = *rest
.as_bytes()
.first()
.filter(|b| matches!(b, b'`' | b'~') || (math && **b == b'$'))?;
let length = rest.bytes().take_while(|&b| b == marker).count();
let info = rest[length..].trim_matches([' ', '\t']);
let long_enough = length >= if marker == b'$' { 2 } else { 3 };
let info_ok = !(matches!(marker, b'`' | b'$') && info.as_bytes().contains(&marker));
(long_enough && info_ok).then_some(Self { marker, length, info })
}
pub(super) fn is_closed_by(&self, rest: &str) -> bool {
let length = rest.bytes().take_while(|&b| b == self.marker).count();
length >= self.length && rest[length..].trim_matches([' ', '\t']).is_empty()
}
}
pub(super) fn fenced_code(
lines: &[Line<'_>],
start: usize,
indent: usize,
fence: &Fence<'_>,
own_end: bool,
blocks: &mut Vec<Block>,
) -> usize {
let (lang, meta) = match fence.info.split_once([' ', '\t']) {
Some((lang, meta)) => (Some(lang), Some(meta.trim_start_matches([' ', '\t']))),
None => (Some(fence.info).filter(|s| !s.is_empty()), None),
};
let mut body = Vec::new();
let mut index = start + 1;
let mut end = None;
while let Some(line) = lines.get(index) {
let Indent {
columns,
bytes: line_indent,
} = line.indent();
if columns < line.code_indent() && fence.is_closed_by(&line.text[line_indent..]) {
end = Some(line.end());
index += 1;
break;
}
let content = line.skip_columns(lines[start].pad + indent);
body.push((content.pad, content.text, line.eol));
index += 1;
}
let closed = end.is_some();
let end = end.unwrap_or_else(|| match lines.last() {
Some(last) if !last.eol.is_empty() && reaches_line_end(last, body.is_empty(), own_end) => Point {
line: last.number + 1,
column: 1,
},
Some(last) => last.end(),
None => lines[start].end(),
});
let position = Some(Position {
start: lines[start].point(indent),
end,
});
let mut value = String::with_capacity(body.iter().map(|(pad, text, eol)| pad + text.len() + eol.len()).sum());
for (index, (pad, text, eol)) in body.iter().enumerate() {
value.extend(std::iter::repeat_n(' ', *pad));
value.push_str(text);
if index + 1 < body.len() {
value.push_str(eol);
}
}
let node = if fence.marker == b'$' {
Node::Math(Math { value, position })
} else {
Node::Code(Code {
value,
lang: lang.map(inline::unescape),
meta: meta.filter(|m| !m.is_empty()).map(inline::unescape),
fence: true,
position,
})
};
blocks.push(Block::Fenced(FencedBlock {
node,
closed,
lines: body.len(),
}));
index
}
fn reaches_line_end(last: &Line<'_>, empty: bool, own_end: bool) -> bool {
if empty {
last.eof && !own_end
} else {
last.eof || last.item_end
}
}
pub(super) fn indented_code(lines: &[Line<'_>], start: usize, blocks: &mut Vec<Block>) -> usize {
let mut last_code = start;
let mut index = start;
while let Some(line) = lines.get(index) {
if line.indent().columns >= CODE_INDENT {
last_code = index;
} else if !line.is_blank() {
break;
}
index += 1;
}
let mut parts = lines[start..=last_code]
.iter()
.map(|line| {
let content = line.skip_columns(CODE_INDENT);
(content.pad, content.text, line.eol)
})
.collect::<Vec<_>>();
while parts.len() > 1
&& parts
.last()
.is_some_and(|(_, text, _)| text.trim_matches([' ', '\t']).is_empty())
{
parts.pop();
}
let mut value = String::with_capacity(parts.iter().map(|(pad, text, eol)| pad + text.len() + eol.len()).sum());
for (index, (pad, text, eol)) in parts.iter().enumerate() {
value.extend(std::iter::repeat_n(' ', *pad));
value.push_str(text);
if index + 1 < parts.len() {
value.push_str(eol);
}
}
let position = Position {
start: lines[start].point(0),
end: lines[last_code].end(),
};
blocks.push(Block::Node(Node::Code(Code {
value,
lang: None,
meta: None,
fence: false,
position: Some(position),
})));
last_code + 1
}