use super::super::inline_math::{self, Piece};
use super::super::latex::math::latex;
use crate::model::{BOLD, ITALIC, MATH, MONO, SANS, SMALL_CAPS, SUB, SUP, Span};
const STYLE_TAGS: [(u8, &str); 8] = [
(BOLD, "b"),
(ITALIC, "i"),
(MONO, "code"),
(SANS, "sf"),
(SMALL_CAPS, "sc"),
(MATH, "mf"),
(SUP, "sup"),
(SUB, "sub"),
];
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Markup {
pub(crate) text: String,
pub(crate) formulas: Vec<Vec<Span>>,
}
#[derive(Debug, Clone, PartialEq)]
enum Wrap {
Link(String),
Color([u8; 3]),
Style(u8),
}
impl Wrap {
fn open(&self) -> String {
match self {
Self::Link(href) => format!("<a href=\"{}\">", escape(href)),
Self::Color([red, green, blue]) => format!("<font color=\"#{red:02x}{green:02x}{blue:02x}\">"),
Self::Style(flag) => format!("<{}>", style_tag(*flag)),
}
}
fn close(&self) -> String {
match self {
Self::Link(_) => "</a>".to_string(),
Self::Color(_) => "</font>".to_string(),
Self::Style(flag) => format!("</{}>", style_tag(*flag)),
}
}
fn name(&self) -> &'static str {
match self {
Self::Link(_) => "a",
Self::Color(_) => "font",
Self::Style(flag) => style_tag(*flag),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Parsed {
pub(crate) spans: Vec<Span>,
pub(crate) formulas_used: Vec<usize>,
pub(crate) warnings: Vec<String>,
}
pub(crate) fn to_markup(spans: &[Span]) -> Markup {
let pieces = if inline_math::has_math(spans) {
inline_math::split(spans)
} else {
vec![Piece::Text(spans.to_vec())]
};
let mut writer = Writer::default();
let mut formulas = Vec::new();
for piece in pieces {
match piece {
Piece::Text(spans) => spans.iter().for_each(|span| writer.span(span)),
Piece::Math(node, _, spans) => {
writer.close_all();
formulas.push(spans);
writer
.out
.push_str(&format!("<m id=\"{}\">{}</m>", formulas.len(), escape(&latex(&node))));
}
}
}
writer.close_all();
Markup {
text: writer.out,
formulas,
}
}
pub(crate) fn from_markup(text: &str, formulas: &[Vec<Span>]) -> Result<Parsed, String> {
let mut reader = Reader::default();
let mut rest = text;
while let Some(pos) = rest.find(['<', '&']) {
reader.text(&rest[..pos]);
rest = &rest[pos..];
if rest.starts_with('&') {
let (ch, len) = entity(rest);
reader.text(&ch);
rest = &rest[len..];
continue;
}
if !rest[1..].starts_with(|ch: char| ch.is_ascii_alphabetic() || ch == '/') {
reader.text("<");
rest = &rest[1..];
continue;
}
let end = rest
.find('>')
.ok_or_else(|| format!("a tag is not closed by '>': {}", excerpt(rest)))?;
let tag = Tag::parse(&rest[1..end])?;
rest = &rest[end + 1..];
if let Tag::Formula { id, closed } = tag {
let spans = formulas
.get(id.wrapping_sub(1))
.ok_or_else(|| format!("there is no formula {id} in this block"))?;
reader.formula(id, spans);
if !closed {
match rest.find("</m>") {
Some(pos) => rest = &rest[pos + "</m>".len()..],
None => reader.warnings.push(format!("<m id=\"{id}\"> is not closed")),
}
}
continue;
}
reader.tag(tag);
}
reader.text(rest);
Ok(reader.finish())
}
fn style_tag(flag: u8) -> &'static str {
STYLE_TAGS
.iter()
.find(|(bit, _)| *bit == flag)
.map_or("span", |(_, name)| name)
}
fn wraps_of(span: &Span) -> Vec<Wrap> {
let mut wraps = Vec::new();
if let Some(href) = &span.href {
wraps.push(Wrap::Link(href.clone()));
}
if span.color != [0; 3] {
wraps.push(Wrap::Color(span.color));
}
for (flag, _) in STYLE_TAGS {
if span.style & flag != 0 {
wraps.push(Wrap::Style(flag));
}
}
wraps
}
fn escape(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for ch in text.chars() {
match ch {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'"' => out.push_str("""),
other => out.push(other),
}
}
out
}
fn entity(text: &str) -> (String, usize) {
const NAMED: [(&str, char); 5] = [("amp", '&'), ("lt", '<'), ("gt", '>'), ("quot", '"'), ("apos", '\'')];
let Some(end) = text[1..]
.find(';')
.map(|pos| pos + 1)
.filter(|&end| end <= MAX_ENTITY_LEN)
else {
return ("&".to_string(), 1);
};
let name = &text[1..end];
let ch = NAMED
.iter()
.find(|(entity, _)| *entity == name)
.map(|&(_, ch)| ch)
.or_else(|| {
let code = match name.strip_prefix('#') {
Some(hex) if hex.starts_with(['x', 'X']) => u32::from_str_radix(&hex[1..], 16).ok(),
Some(dec) => dec.parse().ok(),
None => None,
};
code.and_then(char::from_u32)
});
match ch {
Some(ch) => (ch.to_string(), end + 1),
None => ("&".to_string(), 1),
}
}
const MAX_ENTITY_LEN: usize = 10;
fn excerpt(text: &str) -> String {
text.chars().take(40).collect()
}
#[derive(Default)]
struct Writer {
out: String,
open: Vec<Wrap>,
}
impl Writer {
fn span(&mut self, span: &Span) {
if span.text.is_empty() {
return;
}
let wanted = wraps_of(span);
let kept = self
.open
.iter()
.zip(&wanted)
.take_while(|(open, want)| open == want)
.count();
while self.open.len() > kept {
let wrap = self.open.pop().expect("more wraps open than kept");
self.out.push_str(&wrap.close());
}
for wrap in &wanted[kept..] {
self.out.push_str(&wrap.open());
}
self.open = wanted;
self.out.push_str(&escape(&span.text));
}
fn close_all(&mut self) {
while let Some(wrap) = self.open.pop() {
self.out.push_str(&wrap.close());
}
}
}
#[derive(Debug, Clone, PartialEq)]
enum Tag {
Open(Wrap),
Close(String),
Formula {
id: usize,
closed: bool,
},
}
impl Tag {
fn parse(inner: &str) -> Result<Self, String> {
let inner = inner.trim();
if let Some(name) = inner.strip_prefix('/') {
return Ok(Self::Close(name.trim().to_ascii_lowercase()));
}
let (body, closed) = match inner.strip_suffix('/') {
Some(body) => (body.trim(), true),
None => (inner, false),
};
let name_end = body.find(char::is_whitespace).unwrap_or(body.len());
let name = body[..name_end].to_ascii_lowercase();
let attrs = &body[name_end..];
match name.as_str() {
"m" => {
let id = attribute(attrs, "id")
.and_then(|id| id.trim().parse().ok())
.ok_or_else(|| format!("<{inner}> has no formula id"))?;
Ok(Self::Formula { id, closed })
}
"a" => {
let href = attribute(attrs, "href").ok_or_else(|| format!("<{inner}> has no href"))?;
Ok(Self::Open(Wrap::Link(href)))
}
"font" => {
let color = attribute(attrs, "color")
.and_then(|color| parse_color(&color))
.ok_or_else(|| format!("<{inner}> has no colour #rrggbb"))?;
Ok(Self::Open(Wrap::Color(color)))
}
_ => STYLE_TAGS
.iter()
.find(|(_, tag)| *tag == name)
.map(|&(flag, _)| Self::Open(Wrap::Style(flag)))
.ok_or_else(|| format!("unknown tag <{inner}>")),
}
}
}
fn attribute(attrs: &str, name: &str) -> Option<String> {
let mut rest = attrs;
loop {
let pos = rest.find(name)?;
let before_ok = rest[..pos].chars().next_back().is_none_or(char::is_whitespace);
let after = rest[pos + name.len()..].trim_start();
if before_ok && let Some(value) = after.strip_prefix('=') {
let value = value.trim_start();
let quote = value.chars().next().filter(|ch| *ch == '"' || *ch == '\'')?;
let end = value[1..].find(quote)? + 1;
return Some(unescape(&value[1..end]));
}
rest = &rest[pos + name.len()..];
}
}
fn unescape(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut rest = text;
while let Some(pos) = rest.find('&') {
out.push_str(&rest[..pos]);
let (ch, len) = entity(&rest[pos..]);
out.push_str(&ch);
rest = &rest[pos + len..];
}
out.push_str(rest);
out
}
fn parse_color(text: &str) -> Option<[u8; 3]> {
let hex = text.trim().strip_prefix('#')?;
if hex.len() != 6 || !hex.is_ascii() {
return None;
}
let part = |idx: usize| u8::from_str_radix(&hex[idx..idx + 2], 16).ok();
Some([part(0)?, part(2)?, part(4)?])
}
#[derive(Default)]
struct Reader {
spans: Vec<Span>,
open: Vec<Wrap>,
after_formula: bool,
formulas_used: Vec<usize>,
warnings: Vec<String>,
}
impl Reader {
fn text(&mut self, text: &str) {
if text.is_empty() {
return;
}
let mut span = Span::plain(text);
for wrap in &self.open {
match wrap {
Wrap::Link(href) => span.href = Some(href.clone()),
Wrap::Color(color) => span.color = *color,
Wrap::Style(flag) => span.style |= flag,
}
}
match self.spans.last_mut() {
Some(last)
if !self.after_formula
&& last.style == span.style
&& last.href == span.href
&& last.color == span.color =>
{
last.text.push_str(text);
}
_ => self.spans.push(span),
}
self.after_formula = false;
}
fn formula(&mut self, id: usize, spans: &[Span]) {
self.spans.extend(spans.iter().cloned());
self.formulas_used.push(id);
self.after_formula = true;
}
fn tag(&mut self, tag: Tag) {
match tag {
Tag::Open(wrap) => self.open.push(wrap),
Tag::Close(name) => match self.open.iter().rposition(|wrap| wrap.name() == name) {
Some(pos) => {
self.open.remove(pos);
}
None => self.warnings.push(format!("</{name}> closes no open tag")),
},
Tag::Formula { .. } => unreachable!("formulas are read by from_markup"),
}
}
fn finish(mut self) -> Parsed {
for wrap in &self.open {
self.warnings.push(format!("<{}> is not closed", wrap.name()));
}
Parsed {
spans: self.spans,
formulas_used: self.formulas_used,
warnings: self.warnings,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn span(text: &str, style: u8) -> Span {
Span {
style,
..Span::plain(text)
}
}
fn link(text: &str, href: &str) -> Span {
Span {
href: Some(href.to_string()),
..Span::plain(text)
}
}
#[test]
fn styles_become_tags_and_come_back() {
let spans = vec![
span("The ", 0),
span("goal", ITALIC),
span(" of ", 0),
span("bold italic", BOLD | ITALIC),
span(" bold", BOLD),
span(" x<y & \"z\" ", 0),
link("16", "#ref-16"),
];
let markup = to_markup(&spans);
assert_eq!(
markup.text,
"The <i>goal</i> of <b><i>bold italic</i> bold</b> x<y & "z" <a href=\"#ref-16\">16</a>"
);
let parsed = from_markup(&markup.text, &markup.formulas).unwrap();
assert_eq!(parsed.spans, spans);
assert!(parsed.warnings.is_empty());
}
#[test]
fn colour_and_rare_styles_come_back() {
let spans = vec![
Span {
color: [0xff, 0, 0x10],
..span("red", SANS)
},
span(" small caps", SMALL_CAPS),
span("2", SUP),
span("i", SUB),
span(" code", MONO),
];
let markup = to_markup(&spans);
let parsed = from_markup(&markup.text, &markup.formulas).unwrap();
assert_eq!(parsed.spans, spans);
}
#[test]
fn formulas_are_kept_whatever_the_text_around_them() {
let spans = vec![
span("the regret ", 0),
span("f", MATH | ITALIC),
span("t", SUB | MATH | ITALIC),
span(" is small", 0),
];
let markup = to_markup(&spans);
assert_eq!(markup.formulas.len(), 1);
assert!(markup.text.starts_with("the regret <m id=\"1\">"), "{}", markup.text);
assert!(markup.text.ends_with("</m> is small"), "{}", markup.text);
let parsed = from_markup(&markup.text, &markup.formulas).unwrap();
assert_eq!(parsed.spans, spans);
let parsed = from_markup("độ hối tiếc <m id=\"1\">garbled</m> là nhỏ", &markup.formulas).unwrap();
let text: String = parsed.spans.iter().map(|span| span.text.as_str()).collect();
assert_eq!(text, "độ hối tiếc ft là nhỏ");
assert_eq!(parsed.formulas_used, vec![1]);
let parsed = from_markup("<m id=\"1\"/> nhỏ", &markup.formulas).unwrap();
assert_eq!(parsed.spans[0], markup.formulas[0][0]);
}
#[test]
fn edited_markup_is_read_leniently() {
let parsed = from_markup("<b><i>x</b></i> A & B & C α", &[]).unwrap();
assert_eq!(parsed.spans, vec![span("x", BOLD | ITALIC), span(" A & B & C α", 0)]);
assert!(parsed.warnings.is_empty());
let parsed = from_markup("x < y <= z", &[]).unwrap();
assert_eq!(parsed.spans, vec![span("x < y <= z", 0)]);
let parsed = from_markup("<B>x</b></i>", &[]).unwrap();
assert_eq!(parsed.spans, vec![span("x", BOLD)]);
assert_eq!(parsed.warnings.len(), 1);
let parsed = from_markup("<a href='#sec-2'>x", &[]).unwrap();
assert_eq!(parsed.spans, vec![link("x", "#sec-2")]);
assert_eq!(parsed.warnings.len(), 1);
}
#[test]
fn broken_markup_is_an_error() {
assert!(from_markup("x <blink>y</blink>", &[]).is_err());
assert!(from_markup("x <b y", &[]).is_err());
assert!(from_markup("x <m id=\"2\"/>", &[vec![span("y", MATH)]]).is_err());
assert!(from_markup("x <m>", &[]).is_err());
assert!(from_markup("<font color=\"red\">x</font>", &[]).is_err());
}
}