use std::collections::HashMap;
use comrak::{
Arena,
nodes::{AstNode, NodeValue, Sourcepos},
};
#[derive(Debug)]
pub(in crate::markdown) struct Defined(HashMap<(usize, usize), usize>);
impl Defined {
pub(in crate::markdown) fn of<'b>(root: &'b AstNode<'b>, lines: &[&str]) -> Self {
let mut found = HashMap::new();
for node in root.descendants() {
let k = count(node, lines);
if k > 0 {
let start = node.data().sourcepos.start;
found.insert((start.line, start.column), k);
}
}
Self(found)
}
fn lines_of<'b>(&self, block: &'b AstNode<'b>) -> usize {
let start = block.data().sourcepos.start;
self.0
.get(&(start.line, start.column))
.copied()
.unwrap_or(0)
}
}
const REACH: usize = 4;
fn count<'b>(block: &'b AstNode<'b>, lines: &[&str]) -> usize {
let ast = block.data();
let sp = ast.sourcepos;
let last = match &ast.value {
NodeValue::Paragraph if !super::precedes_table(block) => sp.end.line,
NodeValue::Heading(h) if h.setext => sp.end.line.saturating_sub(1),
_ => return 0,
};
let first = super::line_at(lines, sp.start.line)
.get(sp.start.column.saturating_sub(1)..)
.unwrap_or("");
if !(first.starts_with('[') && (first.contains("]:") || !first.contains(']'))) {
return 0;
}
let lead = |l: &str| l.len() - l.trim_start_matches(' ').len();
let first_lead = lead(super::line_at(lines, sp.start.line));
let written: Vec<&str> = (sp.start.line..=last)
.map(|n| {
let src = super::line_at(lines, n);
&src[lead(src).min(first_lead)..]
})
.collect();
let mut found = 0;
for j in 1..written.len() {
if only_definitions(&written[..j].join("\n")) {
found = j;
} else if j > found + REACH {
break;
}
}
found
}
fn only_definitions(text: &str) -> bool {
let arena = Arena::new();
let root = comrak::parse_document(&arena, text, &super::options());
root.descendants().all(|n| {
matches!(
n.data().value,
NodeValue::Document
| NodeValue::BlockQuote
| NodeValue::List(_)
| NodeValue::Item(_)
| NodeValue::TaskItem(_)
| NodeValue::FootnoteDefinition(_)
)
})
}
#[derive(Debug, Clone, Copy)]
enum Container {
Quote,
Indent(usize),
Task,
}
fn containers<'b>(block: &'b AstNode<'b>) -> Vec<Container> {
let mut out: Vec<Container> = block
.ancestors()
.skip(1)
.filter_map(|a| match &a.data().value {
NodeValue::BlockQuote => Some(Container::Quote),
NodeValue::Item(list) => Some(Container::Indent(list.marker_offset + list.padding)),
NodeValue::FootnoteDefinition(_) => Some(Container::Indent(4)),
NodeValue::TaskItem(_) => Some(Container::Task),
_ => None,
})
.collect();
out.reverse();
out
}
fn indent(src: &str, sp: Sourcepos, n: usize, containers: &[Container]) -> usize {
if n == sp.start.line {
return sp.start.column.saturating_sub(1);
}
let bytes = src.as_bytes();
let spaces = |at: usize| {
bytes[at.min(bytes.len())..]
.iter()
.take_while(|b| matches!(b, b' ' | b'\t'))
.count()
};
let mut at = 0;
for &c in containers {
let ws = spaces(at);
match c {
Container::Quote if ws <= 3 && bytes.get(at + ws) == Some(&b'>') => {
at += ws + 1;
if matches!(bytes.get(at), Some(b' ' | b'\t')) {
at += 1;
}
}
Container::Indent(need) if ws >= need => at += need,
Container::Task => at += ws,
_ => return at,
}
}
at + spaces(at)
}
pub(super) fn block_pos<'b>(
block: &'b AstNode<'b>,
lines: &[&str],
defined: &Defined,
) -> Sourcepos {
let mut sp = block.data().sourcepos;
let k = defined.lines_of(block);
if k > 0 {
let start = sp.start.line + k;
let src = super::line_at(lines, start);
sp.start.column = indent(src, sp, start, &containers(block)) + 1;
sp.start.line = start;
}
sp
}
pub(super) fn inline_pos<'b>(
node: &'b AstNode<'b>,
lines: &[&str],
defined: &Defined,
) -> Sourcepos {
let mut sp = node.data().sourcepos;
let Some(block) = node
.ancestors()
.find(|a| matches!(a.data().value, NodeValue::Paragraph | NodeValue::Heading(_)))
else {
return sp;
};
let k = defined.lines_of(block);
if k == 0 {
return sp;
}
let at = block.data().sourcepos;
let around = containers(block);
let indent_of = |n: usize| indent(super::line_at(lines, n), at, n, &around);
let moved = |line: usize, col: usize| {
if col == 0 {
0
} else {
(col + indent_of(line + k)).saturating_sub(indent_of(line))
}
};
sp.start.column = moved(sp.start.line, sp.start.column);
sp.end.column = moved(sp.end.line, sp.end.column);
sp.start.line += k;
sp.end.line += k;
sp
}