use std::borrow::Cow;
use comrak::{Arena, nodes::NodeValue};
use super::{parse, reading};
pub(crate) fn atx_written(text: &str) -> Cow<'_, str> {
let run = text.trim_end_matches('#').len();
if run < text.len() && (run == 0 || text[..run].ends_with([' ', '\t'])) {
Cow::Owned(format!("{}\\{}", &text[..run], &text[run..]))
} else {
Cow::Borrowed(text)
}
}
pub(crate) fn heading_text_of(value: &str) -> String {
let mut out = String::with_capacity(value.len());
for (i, line) in value.trim().split(['\n', '\r']).enumerate() {
let line = line.trim();
if line.is_empty() {
continue;
}
if i > 0 && !out.is_empty() {
out.push(' ');
}
out.push_str(line);
}
out
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Unwritable {
Empty,
Starts(&'static str),
}
impl Unwritable {
pub(crate) fn said(self, subject: &str, text: &str, noun: &str) -> String {
match self {
Unwritable::Empty => format!("{subject} is empty, which no {noun} can hold"),
Unwritable::Starts(block) => format!(
"{subject} holds {}, which no {noun} can hold: on a line of its own it starts {block}",
crate::text::code(text)
),
}
}
}
pub(crate) fn unit_written<'a>(prefix: &str, text: &'a str) -> Result<Cow<'a, str>, Unwritable> {
let prefix = prefix.trim_start();
if text.is_empty() {
let item = prefix
.trim_end()
.trim_start_matches(|c: char| c.is_ascii_digit())
.ends_with(['-', '*', '+', '.', ')']);
return if item {
Ok(Cow::Borrowed(text))
} else {
Err(Unwritable::Empty)
};
}
let kind = blocks(prefix, "x");
let found = blocks(prefix, text);
if kinds(&found) == kinds(&kind) {
return Ok(Cow::Borrowed(text));
}
escapes(text)
.find(|escaped| kinds(&blocks(prefix, escaped)) == kinds(&kind))
.map(Cow::Owned)
.ok_or_else(|| {
let at = found.iter().zip(&kind).position(|(f, k)| f.0 != k.0);
let block = match at {
Some(i) => found.get(i).map_or("another block", |b| b.1),
None if found.len() < kind.len() => "a link reference definition",
None => found.last().map_or("another block", |b| b.1),
};
Unwritable::Starts(block)
})
}
pub(crate) fn escapes(text: &str) -> impl Iterator<Item = String> + '_ {
let meant = reading(text).text;
let colon = text.find("]:").map(|i| i + 1);
text.char_indices()
.filter(|(_, c)| c.is_ascii_punctuation() && *c != '\\')
.map(|(i, _)| i)
.take(CANDIDATES)
.chain(colon)
.map(|i| format!("{}\\{}", &text[..i], &text[i..]))
.filter(move |escaped| reading(escaped).text == meant)
}
const CANDIDATES: usize = 16;
type Kind = (std::mem::Discriminant<NodeValue>, &'static str);
fn kinds(blocks: &[Kind]) -> Vec<std::mem::Discriminant<NodeValue>> {
blocks.iter().map(|b| b.0).collect()
}
fn blocks(prefix: &str, text: &str) -> Vec<Kind> {
let arena = Arena::new();
let source = format!("x\n\n{prefix}{text}\n");
let root = comrak::parse_document(&arena, &source, &parse::options());
let item = std::mem::discriminant(&NodeValue::Item(comrak::nodes::NodeList::default()));
root.descendants()
.skip(2)
.filter(|n| n.data().value.block())
.map(|n| {
let value = &n.data().value;
let name = match value {
NodeValue::HtmlBlock(_) => "an HTML block",
NodeValue::Heading(_) => "a heading",
NodeValue::List(_) | NodeValue::Item(_) | NodeValue::TaskItem(_) => "a list",
NodeValue::BlockQuote => "a quote",
NodeValue::CodeBlock(_) => "a code block",
NodeValue::ThematicBreak(_) => "a thematic break",
NodeValue::Table(_) => "a table",
_ => "another block",
};
match value {
NodeValue::TaskItem(_) => (item, name),
v => (std::mem::discriminant(v), name),
}
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_text_that_starts_a_block_is_escaped_to_a_paragraph() {
for (text, written) in [
("# x", "\\# x"),
("1)", "1\\)"),
("1. x", "1\\. x"),
("[a]: /x", "[a]\\: /x"),
("- x", "\\- x"),
("a # b", "a # b"),
] {
assert_eq!(unit_written("", text).unwrap(), written, "{text:?}");
}
for (prefix, text, written) in [
("- ", "--", "\\--"),
("* ", "**", "\\**"),
("- ", "**", "**"),
("- ", "[ ] x", "[ ] x"),
] {
assert_eq!(unit_written(prefix, text).unwrap(), written, "{text:?}");
}
}
#[test]
fn an_empty_text_and_an_html_block_are_unwritable() {
assert_eq!(unit_written("", ""), Err(Unwritable::Empty));
assert_eq!(
unit_written("", "<div>"),
Err(Unwritable::Starts("an HTML block"))
);
assert_eq!(
unit_written("- ", "<div>"),
Err(Unwritable::Starts("an HTML block"))
);
}
}