use super::math::{latex, math_char};
use crate::model::{BOLD, ITALIC, MONO, SUB, SUP, Span};
use crate::render::inline_math::{Piece, has_math, split};
use crate::render::markdown::inline::merge;
use crate::render::notes::{Segment, segments};
use std::cell::RefCell;
use std::collections::HashSet;
use unicode_normalization::UnicodeNormalization;
const LINK_SCHEMES: [&str; 4] = ["http://", "https://", "mailto:", "ftp://"];
const LABEL_PREFIX: &str = "k:";
const TEXT_SYMBOLS: &[(char, &str)] = &[
('\\', "\\textbackslash{}"),
('{', "\\{"),
('}', "\\}"),
('#', "\\#"),
('$', "\\$"),
('%', "\\%"),
('&', "\\&"),
('_', "\\_"),
('~', "\\textasciitilde{}"),
('^', "\\textasciicircum{}"),
('<', "\\textless{}"),
('>', "\\textgreater{}"),
('|', "\\textbar{}"),
('\u{a0}', "~"),
('\u{ad}', "\\-"),
('–', "--"),
('—', "---"),
('‘', "`"),
('’', "'"),
('“', "``"),
('”', "''"),
('…', "\\ldots{}"),
('•', "\\textbullet{}"),
('†', "\\dag{}"),
('‡', "\\ddag{}"),
('ff', "ff"),
('fi', "fi"),
('fl', "fl"),
('ffi', "ffi"),
('ffl', "ffl"),
('ſt', "st"),
('st', "st"),
('\u{2002}', "\\enskip{}"),
('\u{2003}', "\\quad{}"),
('\u{2009}', "\\,"),
('\u{202f}', "\\,"),
('\u{200b}', ""),
('\u{200c}', ""),
('\u{200d}', ""),
('\u{2060}', ""),
('\u{feff}', ""),
];
const TEXT_MATH: &[(char, &str)] = &[
('∆', "\\Delta"),
('≲', "\\lesssim"),
('≳', "\\gtrsim"),
('⪅', "\\lessapprox"),
('⪆', "\\gtrapprox"),
];
const LIGATURE_PAIRS: &[(char, char)] = &[('-', '-'), ('`', '`'), ('\'', '\''), ('!', '`'), ('?', '`'), (',', ',')];
pub(crate) const LAST_LATIN: char = '\u{17f}';
pub(crate) const LATIN_GAPS: &[char] = &['ĸ', 'Ŀ', 'ŀ', 'ʼn', 'Ŧ', 'ŧ', 'ſ'];
pub(crate) struct Text<'a> {
pub(crate) anchors: &'a HashSet<String>,
pub(crate) math: bool,
pub(crate) table_notes: RefCell<Option<Vec<String>>>,
}
impl Text<'_> {
pub(crate) fn spans(&self, spans: &[Span]) -> String {
if !self.math || !has_math(spans) {
return self.runs(spans).trim().to_string();
}
let mut out = String::new();
for piece in split(spans) {
match piece {
Piece::Text(spans) => out.push_str(&self.runs(&spans)),
Piece::Math(node, _, _) => {
let tex = latex(&node).replace(['\n', '\r'], " ");
if !tex.trim().is_empty() {
out.push_str(&format!("${}$", tex.trim()));
}
}
}
}
out.trim().to_string()
}
fn runs(&self, spans: &[Span]) -> String {
let mut out = String::new();
for segment in segments(spans) {
match segment {
Segment::Text(spans) => out.push_str(&self.text_runs(spans)),
Segment::Note(call) => {
let note = self.spans(call.note.as_deref().unwrap_or_default());
match self.table_notes.borrow_mut().as_mut() {
Some(notes) => {
notes.push(note);
out.push_str("\\footnotemark{}");
}
None => out.push_str(&format!("\\footnote{{{note}}}")),
}
}
}
}
out
}
fn text_runs(&self, spans: &[Span]) -> String {
let mut out = String::new();
for (text, style, href) in merge(spans) {
let body = styled(&text, style);
if body.trim().is_empty() {
out.push_str(&body);
continue;
}
match href.as_deref() {
Some(href) => {
let lead = &body[..body.len() - body.trim_start().len()];
let trail = &body[body.trim_end().len()..];
out.push_str(&format!("{lead}{}{trail}", self.link(href, body.trim())));
}
None => out.push_str(&body),
}
}
out
}
fn link(&self, href: &str, body: &str) -> String {
if let Some(anchor) = href.strip_prefix('#') {
return if self.anchors.contains(anchor) {
format!("\\hyperref[{}]{{{body}}}", label(anchor))
} else {
body.to_string()
};
}
if LINK_SCHEMES.iter().any(|scheme| href.starts_with(scheme)) && !href.contains('&') {
format!("\\href{{{}}}{{{body}}}", url(href))
} else {
body.to_string()
}
}
}
pub(crate) fn label(anchor: &str) -> String {
let name: String = anchor
.chars()
.map(|ch| {
if ch.is_ascii_alphanumeric() || matches!(ch, '-' | '.' | ':' | '/') {
ch
} else {
'-'
}
})
.collect();
format!("{LABEL_PREFIX}{name}")
}
fn styled(text: &str, style: u8) -> String {
let inner = text.trim_matches(' ');
if inner.is_empty() {
return escape(text);
}
let lead = &text[..text.len() - text.trim_start_matches(' ').len()];
let trail = &text[text.trim_end_matches(' ').len()..];
let mut body = escape(inner);
for (bit, command) in [
(MONO, "\\texttt"),
(ITALIC, "\\textit"),
(BOLD, "\\textbf"),
(SUP, "\\textsuperscript"),
(SUB, "\\textsubscript"),
] {
if style & bit != 0 {
body = format!("{command}{{{body}}}");
}
}
format!("{lead}{body}{trail}")
}
pub(crate) fn escape(text: &str) -> String {
text.split(' ')
.map(|word| {
let escaped = escape_word(word);
if word.contains("://") || word.starts_with("www.") {
escaped.replace('/', "/\\allowbreak{}")
} else {
escaped
}
})
.collect::<Vec<_>>()
.join(" ")
}
fn escape_word(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for ch in text.nfc() {
if let Some((_, command)) = TEXT_SYMBOLS.iter().find(|(symbol, _)| *symbol == ch) {
push_text(&mut out, command);
} else if matches!(ch, '\n' | '\r' | '\t') {
out.push(' ');
} else if ch.is_control() {
} else if ch.is_ascii() || (ch <= LAST_LATIN && !LATIN_GAPS.contains(&ch)) {
push_text(&mut out, ch.encode_utf8(&mut [0; 4]));
} else if let Some(command) = math_char(ch).or_else(|| {
TEXT_MATH
.iter()
.find(|(symbol, _)| *symbol == ch)
.map(|(_, command)| (*command).to_string())
}) {
if !command.is_empty() {
out.push_str(&format!("\\ensuremath{{{command}}}"));
}
} else {
out.push(ch);
}
}
out
}
fn push_text(out: &mut String, piece: &str) {
if let (Some(last), Some(first)) = (out.chars().next_back(), piece.chars().next())
&& LIGATURE_PAIRS.contains(&(last, first))
{
out.push_str("{}");
}
out.push_str(piece);
}
fn url(href: &str) -> String {
let mut out = String::with_capacity(href.len());
for ch in href.chars() {
match ch {
'%' => out.push_str("\\%"),
'#' => out.push_str("\\#"),
ch if ch.is_control() => {}
ch if !ch.is_ascii() || "\\{}~^$ \"<>|`".contains(ch) => {
for byte in ch.encode_utf8(&mut [0; 4]).bytes() {
out.push_str(&format!("\\%{byte:02X}"));
}
}
ch => out.push(ch),
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn span(text: &str, style: u8) -> Span {
Span {
style,
..Span::plain(text)
}
}
#[test]
fn special_characters_are_escaped() {
assert_eq!(escape("50% of $x_1 & {y}"), "50\\% of \\$x\\_1 \\& \\{y\\}");
assert_eq!(
escape("a\\b ~ ^"),
"a\\textbackslash{}b \\textasciitilde{} \\textasciicircum{}"
);
assert_eq!(escape("“quoted” – dash"), "``quoted'' -- dash");
}
#[test]
fn ligatures_are_broken() {
assert_eq!(escape("--flag"), "-{}-flag");
assert_eq!(escape("a-–b"), "a-{}--b");
assert_eq!(escape("''"), "'{}'");
assert_eq!(escape("find"), "find");
assert_eq!(
escape("see https://a.org/b c/d"),
"see https:/\\allowbreak{}/\\allowbreak{}a.org/\\allowbreak{}b c/d"
);
}
#[test]
fn math_symbols_of_text_are_in_math_mode() {
assert_eq!(escape("∆t ≳"), "\\ensuremath{\\Delta}t \\ensuremath{\\gtrsim}");
assert_eq!(
escape("α ≤ 𝐱"),
"\\ensuremath{\\alpha} \\ensuremath{\\le} \\ensuremath{\\mathbf{x}}"
);
assert_eq!(escape("Erdős Ce\u{301}line"), "Erdős Céline");
}
#[test]
fn styles_and_links() {
let anchors: HashSet<String> = ["ref 1".to_string()].into();
let text = Text {
anchors: &anchors,
math: false,
table_notes: RefCell::default(),
};
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", BOLD);
web.href = Some("https://example.org/a b#c%d".into());
let mut query = span(" q", 0);
query.href = Some("https://example.org/?a=1&b=2".into());
assert_eq!(
text.spans(&[known, unknown, web, query]),
"\\hyperref[k:ref-1]{[1]} [2] \\href{https://example.org/a\\%20b\\#c\\%d}{\\textbf{site}} q"
);
assert_eq!(text.spans(&[span("x", SUP | ITALIC)]), "\\textsuperscript{\\textit{x}}");
}
}