use comrak::nodes::{AstNode, NodeValue, Sourcepos};
use super::definitions::{self, Defined};
fn as_written(src: &[u8], from: usize, col: usize) -> usize {
let (mut at, mut read) = (from, from);
let mut after_backslash = false;
while at < src.len() {
let byte = src[at];
let dropped = !after_backslash && byte == b'\\' && src.get(at + 1) == Some(&b'|');
after_backslash = !after_backslash && byte == b'\\';
if !dropped {
if read == col {
return at;
}
read += 1;
}
at += 1;
}
at + col.saturating_sub(read)
}
pub(super) fn row_pos<'b>(node: &'b AstNode<'b>, mut sp: Sourcepos, lines: &[&str]) -> Sourcepos {
let row = node
.ancestors()
.skip(1)
.find(|a| matches!(a.data().value, NodeValue::TableRow(false)));
let Some((row, table)) = row.zip(row.and_then(|r| r.parent())) else {
return sp;
};
let src = line_at(lines, row.data().sourcepos.start.line);
let to = src.len() - src.trim_start_matches([' ', '\t', '>']).len() + 1;
let from = table.data().sourcepos.start.column;
let moved = |col: usize| {
if col == 0 {
0
} else {
(col + to).saturating_sub(from)
}
};
sp.start.column = moved(sp.start.column);
sp.end.column = moved(sp.end.column);
sp
}
fn unescaped_from<'b>(node: &'b AstNode<'b>, lines: &[&str]) -> Option<usize> {
for a in node.ancestors() {
let ast = a.data();
match ast.value {
NodeValue::TableCell => {
return Some(
row_pos(a, ast.sourcepos, lines)
.start
.column
.saturating_sub(1),
);
}
NodeValue::Paragraph => return precedes_table(a).then_some(0),
_ => {}
}
}
None
}
pub(super) fn precedes_table<'b>(paragraph: &'b AstNode<'b>) -> bool {
let end = paragraph.data().sourcepos.end.line;
paragraph.next_sibling().is_some_and(|t| {
let t = t.data();
matches!(t.value, NodeValue::Table(_)) && t.sourcepos.start.line == end + 1
})
}
pub(in crate::markdown) fn written_pos<'b>(
node: &'b AstNode<'b>,
lines: &[&str],
defined: &Defined,
) -> Sourcepos {
let sp = definitions::inline_pos(node, lines, defined);
let mut sp = row_pos(node, sp, lines);
if let Some(from) = unescaped_from(node, lines) {
let moved = |n: usize, col: usize| {
let src = line_at(lines, n);
if src.contains("\\|") {
as_written(src.as_bytes(), from, col)
} else {
col
}
};
if sp.start.column > 0 {
sp.start.column = moved(sp.start.line, sp.start.column - 1) + 1;
}
if sp.end.column > from {
sp.end.column = moved(sp.end.line, sp.end.column - 1) + 1;
}
}
sp
}
pub(super) fn line_at<'a>(lines: &[&'a str], n: usize) -> &'a str {
n.checked_sub(1)
.and_then(|i| lines.get(i))
.copied()
.unwrap_or("")
}