use crate::model::{BOLD, ITALIC, MONO, SUB, SUP, Span};
use crate::render::esc;
use crate::render::inline_math::{Piece, has_math, split};
use crate::render::latex::math::latex;
use std::collections::HashSet;
const ESCAPED: &[char] = &['\\', '`', '*', '_', '[', ']', '<', '>', '|', '$'];
const LINK_SCHEMES: [&str; 4] = ["http://", "https://", "mailto:", "ftp://"];
const MARKDOWN_STYLE: u8 = BOLD | ITALIC | MONO | SUP | SUB;
pub(crate) struct Inline<'a> {
pub(crate) anchors: &'a HashSet<String>,
pub(crate) math: bool,
}
impl Inline<'_> {
pub(crate) fn spans(&self, spans: &[Span]) -> String {
self.write(spans, false)
}
pub(crate) fn cell(&self, spans: &[Span]) -> String {
self.write(spans, true)
}
fn write(&self, spans: &[Span], in_table: bool) -> String {
if !self.math || !has_math(spans) {
return self.text(spans).trim().to_string();
}
let mut out = String::new();
for piece in split(spans) {
match piece {
Piece::Text(spans) => out.push_str(&self.text(&spans)),
Piece::Math(node, _) => {
let mut tex = latex(&node);
if in_table {
tex = tex.replace("\\|", "\\Vert ").replace('|', "\\vert ");
}
out.push_str(&format!("${}$", tex.trim()));
}
}
}
out.trim().to_string()
}
fn text(&self, spans: &[Span]) -> String {
let mut out = String::new();
for (text, style, href) in merge(spans) {
let body = styled(&text, style);
match href.as_deref().filter(|href| self.is_link(href)) {
Some(href) if !body.trim().is_empty() => {
let lead = &body[..body.len() - body.trim_start().len()];
let trail = &body[body.trim_end().len()..];
out.push_str(&format!("{lead}[{}]({}){trail}", body.trim(), destination(href)));
}
_ => out.push_str(&body),
}
}
out
}
fn is_link(&self, href: &str) -> bool {
match href.strip_prefix('#') {
Some(anchor) => self.anchors.contains(anchor),
None => LINK_SCHEMES.iter().any(|scheme| href.starts_with(scheme)),
}
}
}
pub(crate) fn merge(spans: &[Span]) -> Vec<(String, u8, Option<String>)> {
let mut runs: Vec<(String, u8, Option<String>)> = Vec::new();
for span in spans {
let style = span.style & MARKDOWN_STYLE;
let text = span.text.replace(['\n', '\r', '\t'], " ");
match runs.last_mut() {
Some((last, last_style, last_href)) if *last_style == style && *last_href == span.href => {
last.push_str(&text);
}
_ => runs.push((text, style, span.href.clone())),
}
}
runs
}
fn styled(text: &str, style: u8) -> String {
let inner = text.trim_matches(' ');
if inner.is_empty() {
return text.to_string();
}
let lead = &text[..text.len() - text.trim_start_matches(' ').len()];
let trail = &text[text.trim_end_matches(' ').len()..];
let mut body = if style & MONO != 0 {
code_span(inner)
} else if style & (BOLD | ITALIC) != 0 {
emphasis(inner, style)
} else {
escape(inner)
};
if style & SUP != 0 {
body = format!("<sup>{body}</sup>");
}
if style & SUB != 0 {
body = format!("<sub>{body}</sub>");
}
format!("{lead}{body}{trail}")
}
fn emphasis(text: &str, style: u8) -> String {
let core_start = text.find(char::is_alphanumeric);
let core_end = text
.rfind(char::is_alphanumeric)
.map(|idx| idx + text[idx..].chars().next().map_or(1, char::len_utf8));
let (Some(start), Some(end)) = (core_start, core_end) else {
return escape(text);
};
let mut core = escape(&text[start..end]);
if style & ITALIC != 0 {
core = format!("*{core}*");
}
if style & BOLD != 0 {
core = format!("**{core}**");
}
format!("{}{core}{}", escape(&text[..start]), escape(&text[end..]))
}
fn code_span(text: &str) -> String {
let longest = text.split(|ch| ch != '`').map(str::len).max().unwrap_or(0);
let fence = "`".repeat(longest + 1);
let pad = if text.starts_with('`') || text.ends_with('`') {
" "
} else {
""
};
format!("{fence}{pad}{text}{pad}{fence}")
}
pub(crate) fn escape(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for ch in text.chars() {
if ESCAPED.contains(&ch) {
out.push('\\');
}
out.push(ch);
}
out
}
pub(crate) fn escape_line_start(line: &str) -> String {
if line.starts_with(['#', '-', '+', '=']) {
return format!("\\{line}");
}
let digits = line.len() - line.trim_start_matches(|ch: char| ch.is_ascii_digit()).len();
let rest = &line[digits..];
if digits > 0 && (rest.starts_with(". ") || rest.starts_with(") ") || rest == "." || rest == ")") {
return format!("{}\\{}", &line[..digits], rest);
}
line.to_string()
}
fn destination(href: &str) -> String {
if href.contains([' ', '(', ')', '<', '>']) {
format!("<{}>", href.replace('<', "%3C").replace('>', "%3E").replace(' ', "%20"))
} else {
href.to_string()
}
}
pub(crate) fn spans_html(spans: &[Span], anchors: &HashSet<String>) -> String {
let mut out = String::new();
for (text, style, href) in merge(spans) {
let inner = text.trim_matches(' ');
let lead = &text[..text.len() - text.trim_start_matches(' ').len()];
let trail = if inner.is_empty() {
""
} else {
&text[text.trim_end_matches(' ').len()..]
};
let mut body = esc(if inner.is_empty() { &text } else { inner });
for (bit, tag) in [
(MONO, "code"),
(ITALIC, "em"),
(BOLD, "strong"),
(SUP, "sup"),
(SUB, "sub"),
] {
if style & bit != 0 {
body = format!("<{tag}>{body}</{tag}>");
}
}
let inline = Inline { anchors, math: false };
let body = match href.filter(|href| inline.is_link(href)) {
Some(href) => format!("<a href=\"{}\">{body}</a>", esc(&href)),
None => body,
};
out.push_str(&format!("{lead}{body}{trail}"));
}
out.trim().to_string()
}
#[cfg(test)]
mod tests {
use super::*;
fn span(text: &str, style: u8) -> Span {
Span {
style,
..Span::plain(text)
}
}
#[test]
fn emphasis_keeps_spaces_outside() {
let anchors = HashSet::new();
let inline = Inline {
anchors: &anchors,
math: false,
};
let spans = [span("a ", 0), span("bold ", BOLD), span("x_1 * y", 0)];
assert_eq!(inline.spans(&spans), "a **bold** x\\_1 \\* y");
let spans = [span("Bottom row:", ITALIC), span("A", 0)];
assert_eq!(inline.spans(&spans), "*Bottom row*:A");
}
#[test]
fn links_only_to_known_anchors_and_web() {
let anchors: HashSet<String> = ["ref-1".to_string()].into();
let inline = Inline {
anchors: &anchors,
math: false,
};
let mut known = span("[1]", 0);
known.href = Some("#ref-1".into());
let mut unknown = span(" [2]", 0);
unknown.href = Some("#ref-2".into());
let mut web = span(" site", 0);
web.href = Some("https://example.org/a b".into());
assert_eq!(
inline.spans(&[known, unknown, web]),
"[\\[1\\]](#ref-1) \\[2\\] [site](<https://example.org/a%20b>)"
);
}
#[test]
fn code_with_backticks() {
assert_eq!(code_span("a`b"), "``a`b``");
assert_eq!(code_span("`x"), "`` `x ``");
}
#[test]
fn line_start_is_not_a_block() {
assert_eq!(escape_line_start("# not a heading"), "\\# not a heading");
assert_eq!(escape_line_start("2019. A year"), "2019\\. A year");
assert_eq!(escape_line_start("2019 was"), "2019 was");
}
}