use comrak::{Arena, nodes::NodeValue};
use super::parse::{options, strip_prefix};
#[derive(Debug, Clone, PartialEq, Eq)]
pub(in crate::markdown) struct LinkDef {
pub first: usize,
pub last: usize,
pub label: String,
pub dest: String,
}
#[derive(Debug, Default)]
pub(in crate::markdown) struct Read {
pub defs: Vec<LinkDef>,
pub other: Vec<usize>,
}
const REACH: usize = 8;
pub(crate) fn all_definitions(lines: &[&str]) -> bool {
let read = read(lines);
read.other.is_empty() && !read.defs.is_empty()
}
pub(in crate::markdown) fn read(lines: &[&str]) -> Read {
let mut out = Read::default();
let blank = |l: &str| strip_prefix(l).trim().is_empty();
let mut s = 0;
while s < lines.len() {
if blank(lines[s]) {
s += 1;
continue;
}
let end = (s..lines.len())
.find(|&i| blank(lines[i]))
.unwrap_or(lines.len());
read_run(&lines[s..end], s, &mut out);
s = end;
}
out
}
fn read_run(run: &[&str], base: usize, out: &mut Read) {
let mut s = 0;
while s < run.len() {
match definition_at(run, s) {
Some((end, label, dest)) => {
let last = (s..end)
.rev()
.find(|&i| !opening(run[i]).is_empty())
.unwrap_or(s);
out.defs.push(LinkDef {
first: base + s,
last: base + last,
label,
dest,
});
out.other.extend(base + last + 1..base + end);
s = end;
}
None if !opening(run[s]).is_empty() && !ends_its_block(run[s]) => {
out.other.extend(base + s..base + run.len());
return;
}
None => {
out.other.push(base + s);
s += 1;
}
}
}
}
fn definition_at(run: &[&str], s: usize) -> Option<(usize, String, String)> {
if !opening(run[s]).starts_with('[') {
return None;
}
let mut found = None;
for j in s + 1..=run.len() {
if only_definitions(&as_written(&run[s..j])) {
found = Some(j);
if j == run.len() || opening(run[j]).starts_with('[') {
break;
}
} else if found.is_some_and(|f| j >= f + REACH) {
break;
}
if j >= s + 4 * REACH {
break;
}
}
let end = found?;
let (label, dest) = label_and_destination(&run[s..end])?;
Some((end, label, dest))
}
const PROBE: &str = "tramlines-probe";
fn ends_its_block(line: &str) -> bool {
let text = format!("{}[{PROBE}]: /{PROBE}\n\n[{PROBE}]\n", as_written(&[line]));
let arena = Arena::new();
let root = comrak::parse_document(&arena, &text, &options());
root.descendants().any(
|n| matches!(&n.data().value, NodeValue::Link(link) if link.url == format!("/{PROBE}")),
)
}
fn as_written(lines: &[&str]) -> String {
let indent = |rest: &str, width: usize| {
let (mut col, mut cut) = (0, 0);
for (i, b) in rest.bytes().enumerate() {
col = match b {
b' ' => col + 1,
b'\t' => col + 4 - col % 4,
_ => break,
};
if col <= width {
cut = i + 1;
}
}
(cut, col)
};
let first = lines
.first()
.map_or(0, |l| indent(&l[quote_markers(l)..], usize::MAX).1);
let mut out = String::new();
for l in lines {
let quotes = quote_markers(l);
let (cut, _) = indent(&l[quotes..], first);
out.push_str(&l[..quotes]);
out.push_str(&l[quotes + cut..]);
out.push('\n');
}
out
}
fn quote_markers(line: &str) -> usize {
let mut at = 0;
loop {
let rest = &line[at..];
let spaces = rest.len() - rest.trim_start_matches(' ').len();
if spaces > 3 || !rest[spaces..].starts_with('>') {
return at;
}
at += spaces + 1;
if line[at..].starts_with(' ') {
at += 1;
}
}
}
pub(in crate::markdown) fn only_definitions(text: &str) -> bool {
let arena = Arena::new();
let root = comrak::parse_document(&arena, text, &options());
root.descendants().all(|n| {
matches!(
n.data().value,
NodeValue::Document
| NodeValue::BlockQuote
| NodeValue::List(_)
| NodeValue::Item(_)
| NodeValue::TaskItem(_)
| NodeValue::FootnoteDefinition(_)
)
})
}
fn opening(line: &str) -> &str {
let mut t = line.trim_start();
loop {
let rest = t.strip_prefix('>').or_else(|| list_marker(t)).or_else(|| {
["[ ]", "[x]", "[X]"]
.iter()
.find_map(|b| t.strip_prefix(b))
.filter(|r| r.starts_with([' ', '\t']))
});
match rest {
Some(rest) => t = rest.trim_start(),
None => return t,
}
}
}
fn list_marker(text: &str) -> Option<&str> {
let digits = text.len() - text.trim_start_matches(|c: char| c.is_ascii_digit()).len();
let rest = match digits {
0 => text.strip_prefix(['-', '*', '+'])?,
1..=9 => text[digits..].strip_prefix(['.', ')'])?,
_ => return None,
};
(rest.is_empty() || rest.starts_with([' ', '\t'])).then_some(rest)
}
fn label_and_destination(lines: &[&str]) -> Option<(String, String)> {
let mut texts = lines
.iter()
.enumerate()
.map(|(i, l)| if i == 0 { opening(l) } else { strip_prefix(l) });
let mut text = texts.next()?.strip_prefix('[')?;
let mut label = String::new();
let rest = loop {
let mut escaped = false;
let end = text.char_indices().find_map(|(i, c)| {
let close = c == ']' && !escaped;
escaped = c == '\\' && !escaped;
close.then_some(i)
});
if let Some(end) = end {
label.push_str(&text[..end]);
break &text[end + 1..];
}
label.push_str(text);
label.push(' ');
text = texts.next()?;
};
let blank: &[char] = &[' ', '\t'];
let rest = rest.strip_prefix(':')?.trim_matches(blank);
let dest = if rest.is_empty() {
texts.next()?.trim_matches(blank)
} else {
rest
};
let dest = match dest.strip_prefix('<') {
Some(inner) => {
let mut escaped = false;
let end = inner.char_indices().find_map(|(i, c)| {
let close = c == '>' && !escaped;
escaped = c == '\\' && !escaped;
close.then_some(i)
})?;
&dest[..end + 2]
}
None => dest.split(blank).next().filter(|d| !d.is_empty())?,
};
let footnote = label.starts_with('^');
let label = label.trim();
(!label.is_empty() && !footnote).then(|| (label.to_string(), dest.to_string()))
}
#[cfg(test)]
mod tests {
use super::*;
type Found = (usize, usize, String, String);
fn defs(text: &str) -> (Vec<Found>, Vec<usize>) {
let lines: Vec<&str> = text.lines().collect();
let read = read(&lines);
let defs = read
.defs
.into_iter()
.map(|d| (d.first, d.last, d.label, d.dest))
.collect();
(defs, read.other)
}
fn def(first: usize, last: usize, label: &str, dest: &str) -> Found {
(first, last, label.to_string(), dest.to_string())
}
#[test]
fn a_definition_takes_every_line_of_its_destination_and_its_title() {
for (text, last) in [
("[a]: /x", 0),
("[a]:\n/x", 1),
("[a]:\n /x", 1),
("[a]: /x\n\"t\"", 1),
("[a]: /x\n 'a\n long t'", 2),
("[a]:\n /x\n \"t\"", 2),
("[a]: /x \"a\nlong\nt\"", 2),
("> [a]:\n> /x", 1),
("> [a]:\n/x", 1),
("- [a]:\n /x", 1),
] {
assert_eq!(
defs(text),
(vec![def(0, last, "a", "/x")], vec![]),
"{text:?}"
);
}
}
#[test]
fn each_definition_of_a_run_reads_apart() {
assert_eq!(
defs("[a]: /x\n[b]:\n /y\n \"t\"\n\n[c d\ne]: /z"),
(
vec![
def(0, 0, "a", "/x"),
def(1, 3, "b", "/y"),
def(5, 6, "c d e", "/z")
],
vec![]
)
);
assert_eq!(
defs("[a]:\n[x]\n[b]: /y"),
(vec![def(0, 1, "a", "[x]"), def(2, 2, "b", "/y")], vec![])
);
assert_eq!(
defs("- [a]: /x\n-\n- [b]: /y"),
(vec![def(0, 0, "a", "/x"), def(2, 2, "b", "/y")], vec![1])
);
assert_eq!(
defs("[a]: <k.md>\n[b]: <k b.md> \"t\"\n> [c]: /z"),
(
vec![
def(0, 0, "a", "<k.md>"),
def(1, 1, "b", "<k b.md>"),
def(2, 2, "c", "/z")
],
vec![]
)
);
assert_eq!(
defs("\t[a]: /x\n\n- b\n\n\t[c]: /z\u{a0}w"),
(
vec![def(0, 0, "a", "/x"), def(4, 4, "c", "/z\u{a0}w")],
vec![2]
)
);
assert_eq!(
defs("> 1. - [a]: /x\n> [b]: /y"),
(vec![def(0, 0, "a", "/x"), def(1, 1, "b", "/y")], vec![])
);
assert_eq!(
defs("[a\\]b]: /x"),
(vec![def(0, 0, "a\\]b", "/x")], vec![])
);
}
#[test]
fn text_that_comrak_reads_as_no_definition_is_other_text() {
assert_eq!(
defs("[a]: /x\nnot a def"),
(vec![def(0, 0, "a", "/x")], vec![1])
);
assert_eq!(defs("[a]: /x \"t"), (vec![], vec![0]));
assert_eq!(defs("[a]:"), (vec![], vec![0]));
assert_eq!(defs("[a][b]: /x"), (vec![], vec![0]));
assert_eq!(defs("text"), (vec![], vec![0]));
assert_eq!(defs("[^n]: [a]: /x"), (vec![], vec![0]));
assert_eq!(defs("[ ^a]: /x"), (vec![def(0, 0, "^a", "/x")], vec![]));
for between in ["# H", "<!-- note -->", "***"] {
assert_eq!(
defs(&format!("[a]: /x\n{between}\n[b]: /y")),
(vec![def(0, 0, "a", "/x"), def(2, 2, "b", "/y")], vec![1]),
"{between}"
);
}
assert_eq!(
defs("[a]: /x\n<div>\n[b]: /y"),
(vec![def(0, 0, "a", "/x")], vec![1, 2])
);
assert_eq!(defs("[a]: /x \"t\n[b]: /y"), (vec![], vec![0, 1]));
assert_eq!(
defs("[a]: /x\n\"t\"\nmore"),
(vec![def(0, 1, "a", "/x")], vec![2])
);
}
}