use crate::model::{Block, BlockKind, Span};
use crate::render::inline_math::{Piece, has_math, split};
use crate::render::latex::math::latex;
pub(crate) fn plain_of(spans: &[Span]) -> String {
let mut out = String::new();
if has_math(spans) {
for piece in split(spans) {
match piece {
Piece::Text(spans) => spans.iter().for_each(|span| out.push_str(&span.text)),
Piece::Math(node, _, _) => {
out.push('$');
out.push_str(latex(&node).trim());
out.push('$');
}
}
}
} else {
spans.iter().for_each(|span| out.push_str(&span.text));
}
squeeze(&out)
}
pub(crate) fn block_plain(block: &Block) -> Option<String> {
let text = match &block.kind {
BlockKind::Authors if !block.rows.is_empty() => block
.rows
.iter()
.map(|row| plain_of(row))
.collect::<Vec<_>>()
.join("\n"),
BlockKind::Code => block
.rows
.iter()
.map(|row| {
row.iter()
.map(|span| span.text.as_str())
.collect::<String>()
.replace(super::super::assets::MARK, "")
})
.collect::<Vec<_>>()
.join("\n"),
BlockKind::Equation { .. } => match &block.math {
Some(node) => format!("$${}$$", latex(node).trim()),
None => squeeze(&block.text()),
},
_ => plain_of(&block.spans),
};
(!text.is_empty()).then_some(text)
}
fn squeeze(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for word in text.split(|ch: char| ch.is_whitespace() || ch == super::super::assets::MARK) {
if word.is_empty() {
continue;
}
if !out.is_empty() {
out.push(' ');
}
out.push_str(word);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn white_space_is_one_space() {
let spans = [Span::plain(" Deep\u{2003}residual \n learning ")];
assert_eq!(plain_of(&spans), "Deep residual learning");
}
#[test]
fn styles_and_links_are_dropped() {
let mut bold = Span::plain("Adam");
bold.style = crate::model::BOLD;
let mut link = Span::plain("[12]");
link.href = Some("#ref-12".into());
let spans = [bold, Span::plain(" works well "), link];
assert_eq!(plain_of(&spans), "Adam works well [12]");
}
}