const ESCAPABLE: &str = r"\`*_{}[]()#+-.!|<>~=&";
fn hide(c: char) -> char {
char::from_u32(0xF_0000 + u32::from(c)).unwrap_or(c)
}
fn reveal(c: char) -> char {
match u32::from(c) {
code @ 0xF_0000..=0xF_007F => char::from_u32(code - 0xF_0000).unwrap_or(c),
_ => c,
}
}
fn space_reference(rest: &mut std::iter::Peekable<std::str::Chars<'_>>) -> bool {
let found = rest.clone().take(4).eq("#32;".chars());
if found {
rest.nth(3);
}
found
}
pub fn unescape_markdown(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
if c == '\\'
&& let Some(&next) = chars.peek()
&& ESCAPABLE.contains(next)
{
out.push(next);
chars.next();
continue;
}
if c == '&' && space_reference(&mut chars) {
out.push(' ');
continue;
}
out.push(c);
}
out
}
#[derive(Clone, Copy)]
enum Keep {
Inner,
Nothing,
NewSide,
BothSides,
}
fn strip_between(text: &str, open: &str, close: &str, keep: Keep) -> String {
let mut out = String::new();
let mut rest = text;
while let Some(start) = rest.find(open) {
out.push_str(&rest[..start]);
let inner_start = start + open.len();
let Some(len) = rest[inner_start..].find(close) else {
out.push_str(&rest[start..]);
rest = "";
break;
};
let inner = &rest[inner_start..inner_start + len];
match keep {
Keep::Inner => out.push_str(inner),
Keep::Nothing => {}
Keep::NewSide => out.push_str(inner.rsplit_once("~>").map_or(inner, |(_, new)| new)),
Keep::BothSides => {
let (old, new) = inner.rsplit_once("~>").unwrap_or((inner, ""));
out.push_str(old);
out.push_str(new);
}
}
rest = &rest[inner_start + len + close.len()..];
}
out.push_str(rest);
out
}
fn without_block_mark(text: &str) -> &str {
let trimmed = text.trim_start();
let hashes = trimmed.bytes().take_while(|&b| b == b'#').count();
if (1..=6).contains(&hashes) && trimmed.as_bytes().get(hashes) == Some(&b' ') {
return &trimmed[hashes + 1..];
}
for bullet in ["> ", "- ", "+ ", "* "] {
if let Some(rest) = trimmed.strip_prefix(bullet) {
return rest;
}
}
let digits = trimmed.bytes().take_while(u8::is_ascii_digit).count();
if (1..=9).contains(&digits)
&& matches!(trimmed.as_bytes().get(digits), Some(b'.' | b')'))
&& trimmed.as_bytes().get(digits + 1) == Some(&b' ')
{
return &trimmed[digits + 2..];
}
trimmed
}
fn blank(c: char) -> bool {
c.is_whitespace() || c == hide(' ')
}
fn without_emphasis(text: &str) -> String {
let mut text = text.to_string();
for mark in [
"**", "~~", "==", "<u>", "</u>", "<mark>", "</mark>", "<s>", "</s>",
] {
text = text.replace(mark, "");
}
while let Some(at) = text.find("<mark class=\"") {
let end = text[at..]
.find("\">")
.map_or(text.len(), |found| at + found + 2);
text.replace_range(at..end, "");
}
let chars: Vec<char> = text.chars().collect();
let spaced =
|i: usize| i > 0 && blank(chars[i - 1]) && chars.get(i + 1).is_some_and(|&c| blank(c));
let star = |i: usize| chars[i] == '*' && !spaced(i);
if (0..chars.len())
.filter(|&i| star(i))
.count()
.is_multiple_of(2)
{
text = (0..chars.len())
.filter(|&i| !star(i))
.map(|i| chars[i])
.collect();
}
let chars: Vec<char> = text.chars().collect();
let mut drop = vec![false; chars.len()];
let mut open: Vec<(usize, usize, usize, bool)> = Vec::new();
let mut i = 0;
while i < chars.len() {
if chars[i] != '_' {
i += 1;
continue;
}
let end = i + chars[i..].iter().take_while(|&&c| c == '_').count();
let len = end - i;
let before = i.checked_sub(1).map(|b| chars[b]);
let after = chars.get(end).copied();
let closes = before.is_some_and(|c| !blank(c)) && !after.is_some_and(char::is_alphanumeric);
let opens = after.is_some_and(|c| !blank(c)) && !before.is_some_and(char::is_alphanumeric);
let mut from = i;
while closes && from < end {
let Some(at) = open.iter().rposition(|&(_, _, opener, both)| {
!((both || opens)
&& (opener + len).is_multiple_of(3)
&& !(opener.is_multiple_of(3) && len.is_multiple_of(3)))
}) else {
break;
};
let (a, z, opener, both) = open[at];
let used = if z - a >= 2 && end - from >= 2 { 2 } else { 1 };
drop[z - used..z].fill(true);
drop[from..from + used].fill(true);
from += used;
open.truncate(at + 1);
if z - used == a {
open.pop();
} else {
open[at] = (a, z - used, opener, both);
}
}
if opens && from < end {
open.push((from, end, len, closes));
}
i = end;
}
if drop.contains(&true) {
text = chars
.iter()
.zip(&drop)
.filter(|(_, d)| !**d)
.map(|(c, _)| *c)
.collect();
}
text
}
pub fn plain_anchor(text: &str) -> String {
read_anchor(text, Keep::Nothing, Keep::NewSide)
}
#[doc(hidden)]
pub fn plain_anchor_with_removed(text: &str) -> String {
read_anchor(text, Keep::Inner, Keep::BothSides)
}
fn read_anchor(text: &str, deleted: Keep, substituted: Keep) -> String {
let mut literal = String::with_capacity(text.len());
let mut at = 0;
for (event, range) in
pulldown_cmark::Parser::new_ext(text, super::write::parser_options()).into_offset_iter()
{
match event {
pulldown_cmark::Event::Code(code) => {
literal.push_str(&text[at..range.start]);
literal.extend(code.chars().map(|c| if c.is_ascii() { hide(c) } else { c }));
at = range.end;
}
pulldown_cmark::Event::InlineMath(math) | pulldown_cmark::Event::DisplayMath(math) => {
literal.push_str(&text[at..range.start]);
literal.push_str(&math);
at = range.end;
}
pulldown_cmark::Event::Start(
pulldown_cmark::Tag::Superscript | pulldown_cmark::Tag::Subscript,
) => {
literal.push_str(&text[at..range.start]);
at = range.start + 1;
}
pulldown_cmark::Event::End(
pulldown_cmark::TagEnd::Superscript | pulldown_cmark::TagEnd::Subscript,
) => {
literal.push_str(&text[at..range.end - 1]);
at = range.end;
}
_ => {}
}
}
literal.push_str(&text[at..]);
let text = literal.as_str();
let mut hidden = String::with_capacity(text.len());
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
if c == '\\' && chars.peek() == Some(&'\n') {
hidden.push(hide('\n'));
chars.next();
while chars.peek() == Some(&' ') {
chars.next();
}
continue;
}
if c == '\\'
&& let Some(&next) = chars.peek()
&& ESCAPABLE.contains(next)
{
hidden.push(hide(next));
chars.next();
continue;
}
if c == '&' && space_reference(&mut chars) {
hidden.push(hide(' '));
continue;
}
hidden.push(c);
}
let blocks: Vec<&str> = hidden.split('\n').map(without_block_mark).collect();
let mut text = strip_between(
&super::critic::without_attributions(&blocks.join("\n")),
"{>>",
"<<}",
Keep::Nothing,
);
text = strip_between(&text, "{--", "--}", deleted);
text = strip_between(&text, "{~~", "~~}", substituted);
text = strip_between(&text, "{++", "++}", Keep::Inner);
text = strip_between(&text, "{==", "==}", Keep::Inner);
let text = without_emphasis(text.trim_matches('\n'));
text.chars().map(reveal).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_removed_reading_keeps_deletions_and_both_sides() {
assert_eq!(
plain_anchor_with_removed("pay {--bankers--} now"),
"pay bankers now"
);
assert_eq!(
plain_anchor_with_removed("{~~old~>new~~} end"),
"oldnew end"
);
assert_eq!(plain_anchor_with_removed("{++in++}{>>note<<}"), "in");
assert_eq!(plain_anchor("pay {--bankers--} now"), "pay now");
}
#[test]
fn plain_anchor_drops_the_marks_the_agent_view_adds() {
for (anchor, plain) in [
("# Chapter 1", "Chapter 1"),
("**secret**", "secret"),
("<u>secret</u>", "secret"),
("<mark>secret</mark>", "secret"),
("<mark class=\"hl-cyan\">secret</mark>", "secret"),
("<mark class=\"hl-Cyan\">secret</mark> tail", "secret tail"),
("A <mark class=\"hl-cyan\">-</mark> B", "A - B"),
("<s>secret</s>", "secret"),
("{==keep it secret.==}{>>c5 @AC: Cap?<<}", "keep it secret."),
("keep {++it++}{r0 @AC} secret", "keep it secret"),
("keep {~~that~>it~~}{r0 @AC} secret", "keep it secret"),
("keep it {--very --}{r1 @AC}secret", "keep it secret"),
("\\*\\*stars\\*\\*", "**stars**"),
("1. one", "one"),
("{++1. one++}{r0 @AC}", "1. one"),
("1. {++one++}{r0 @AC}", "one"),
("{++\n\n1. item two++}{r0 @AC}", "item two"),
("one{++\n\n## Two++}{r0 @AC}", "one\n\nTwo"),
("a\\\n1\\. b", "a\n1. b"),
("a\\\n", "a\n"),
("# {~~Old~>New~~}{r1 @AC}", "New"),
("- item", "item"),
("a_b", "a_b"),
("*x*", "x"),
("2 * 3", "2 * 3"),
("2 * 3 * 4", "2 * 3 * 4"),
("*a* times 2 * 3", "a times 2 * 3"),
("Intro\\\n\\# Not", "Intro\n# Not"),
("\\\\*", "\\*"),
("snake_case and _x_", "snake_case and x"),
("snake__case", "snake__case"),
("a__b__c", "a__b__c"),
("__init__", "init"),
("__bold__ and snake__case", "bold and snake__case"),
("foo__bar__", "foo__bar__"),
("__x__y", "__x__y"),
("a _b_ c", "a b c"),
("_a_ and foo__bar__", "a and foo__bar__"),
("_foo__", "foo_"),
("__foo_", "_foo"),
("___foo___", "foo"),
("_foo___", "foo__"),
("unclosed {++ insert", "unclosed {++ insert"),
("\\# 1", "# 1"),
("alpha\\\n beta", "alpha\n beta"),
(" lead", " lead"),
(" - item", " - item"),
("a  b", "a b"),
(" ", " "),
("2 * 3 * 4", "2 * 3 * 4"),
("a _b_ c", "a b c"),
(
"Code \\  and \\& literal.",
"Code   and & literal.",
),
] {
assert_eq!(plain_anchor(anchor), plain, "{anchor}");
}
}
fn reader_text(s: &str) -> String {
pulldown_cmark::Parser::new_ext(s, super::super::write::parser_options())
.filter_map(|event| match event {
pulldown_cmark::Event::Text(text)
| pulldown_cmark::Event::Code(text)
| pulldown_cmark::Event::InlineMath(text)
| pulldown_cmark::Event::DisplayMath(text) => Some(text.into_string()),
_ => None,
})
.collect()
}
#[test]
fn underscore_emphasis_reads_as_the_markdown_reader_reads_it() {
for s in [
"_x(__(y)__)__",
"_foo__",
"__foo_",
"___foo___",
"_foo___",
"__a_ b__",
"___foo___bar___",
"_foo___bar___baz_",
"_a _b_ c_",
"_(__foo__)_",
"-_ x__-",
"-___-___-",
"___foo__",
"__foo___",
"foo_bar_baz_",
"snake__case",
"__init__",
"foo-_(bar)_",
"foo__bar__",
"__x__y",
"a _b_ c",
] {
assert_eq!(plain_anchor(s), reader_text(s), "{s}");
}
}
#[test]
fn plain_anchor_keeps_mark_shaped_code_literal() {
assert_eq!(plain_anchor("`{++x++}`"), "{++x++}");
}
#[test]
fn extension_anchors_match_the_reader() {
for source in ["$a`b`c$", "~~x~~", "^x^", "~x~"] {
assert_eq!(plain_anchor(source), reader_text(source), "{source}");
}
}
#[test]
fn plain_anchor_keeps_code_span_contents_literal() {
assert_eq!(
plain_anchor("`a*b _c_ {++literal++}{r0 @A}` {++`new`++}{r1 @A}"),
"a*b _c_ {++literal++}{r0 @A} new"
);
}
#[test]
fn plain_anchor_keeps_all_code_span_spaces() {
assert_eq!(
plain_anchor("Before ` ` after"),
"Before after"
);
}
#[test]
fn plain_anchor_reads_code_span_padding() {
for (source, text) in [("` x `", " x "), ("`` `x` ``", "`x`"), ("`a\nb`", "a b")] {
assert_eq!(plain_anchor(source), text, "{source}");
}
}
#[test]
fn unescape_markdown_resolves_punctuation_escapes_only() {
assert_eq!(unescape_markdown("\\*a\\_b\\\\ \\n \\é"), "*a_b\\ \\n \\é");
assert_eq!(unescape_markdown("trailing \\"), "trailing \\");
assert_eq!(unescape_markdown(" lead and  "), " lead and  ");
assert_eq!(unescape_markdown("\\ "), " ");
}
}