mod highlight;
use super::*;
use crate::model::{HLine, Line, MONO, Span};
use highlight::{Carry, Lang, detect, highlight_line};
const MONO_ADVANCE_EM: f32 = 0.6;
const BLANK_LINE_MIN_PITCHES: f32 = 1.6;
const INDENT_LEVEL_TOLERANCE_EM: f32 = 0.4;
const LONE_LINE_PITCH_EM: f32 = 1.2;
const NUMBERED_MIN_LINES: usize = 5;
const ALGORITHM_MIN_LINES: usize = 3;
const INDENT_TOLERANCE_PT: f32 = 2.0;
const ALGORITHM_MAX_INDENT: usize = 3;
const ORPHAN_MAX_CHARS: usize = 2;
const ALGORITHM_OPENERS: [&str; 12] = [
"Require",
"Ensure",
"Input",
"Output",
"Initialize",
"Initialise",
"procedure",
"function",
"for",
"while",
"repeat",
"Data",
];
const ALGORITHM_CONTROL_WORDS: [&str; 10] = [
"repeat", "until", "for", "while", "if", "else", "end", "return", "do", "loop",
];
const ALGORITHM_ASSIGNMENTS: [&str; 2] = ["\u{2190}", ":="];
const ALGORITHM_HEADERS: [&str; 5] = ["Require", "Ensure", "Input", "Output", "Data"];
pub(crate) fn is_code_paragraph(block: &Block) -> bool {
if matches!(block.kind, BlockKind::Code) {
return block.hlines.len() == block.lines.len();
}
matches!(block.kind, BlockKind::Paragraph { in_abstract: false })
&& block.spans.iter().any(|span| !span.text.trim().is_empty())
&& block
.spans
.iter()
.all(|span| span.style & MONO != 0 || span.text.trim().is_empty())
&& block.hlines.len() == block.lines.len()
}
pub(crate) fn listing_lines(blocks: &[&Block]) -> Vec<String> {
if blocks.iter().all(|block| block.lines.is_empty()) {
return blocks
.iter()
.flat_map(|block| &block.rows)
.map(|row| row.iter().map(|span| span.text.as_str()).collect())
.collect();
}
let pitch = line_pitch(blocks);
let mut parts: Vec<Vec<(&Line, &HLine)>> = Vec::new();
let mut hull: Option<(usize, f32, f32)> = None;
for block in blocks {
for (line, hline) in block.lines.iter().zip(&block.hlines) {
let moves = hull.is_some_and(|(_, x0, x1)| line.bbox.x0 >= x1 || line.bbox.x1 <= x0);
match parts.last_mut() {
Some(part) if !moves => part.push((line, hline)),
_ => parts.push(vec![(line, hline)]),
}
hull = Some(match hull {
Some((page, x0, x1)) if !moves && page == line.page => {
(page, x0.min(line.bbox.x0), x1.max(line.bbox.x1))
}
_ => (line.page, line.bbox.x0, line.bbox.x1),
});
}
}
parts.iter().flat_map(|part| part_lines(part, pitch)).collect()
}
fn part_lines(part: &[(&Line, &HLine)], pitch: f32) -> Vec<String> {
let all: Vec<&Line> = part.iter().map(|(line, _)| *line).collect();
let starts = indent_starts(&all);
let base = starts.first().copied().unwrap_or(0.0);
let width = listing_char_width(&all);
let mut lines = Vec::new();
let mut previous: Option<&Line> = None;
for (line, hline) in part {
if let Some(prev) = previous
&& prev.page == line.page
&& line.baseline - prev.baseline > BLANK_LINE_MIN_PITCHES * pitch
{
lines.push(String::new());
}
let mut text: String = hline.spans.iter().map(|span| span.text.as_str()).collect();
if text.ends_with(' ') {
text.pop();
}
if hline.soft_hyphen {
text.push('-');
}
let start = indent_start(&starts, line.bbox.x0);
let indent = ((start - base) / width).round().max(0.0) as usize;
lines.push(format!("{}{}", " ".repeat(indent), text.trim_start()));
previous = Some(line);
}
lines
}
fn line_pitch(blocks: &[&Block]) -> f32 {
let lines: Vec<&Line> = blocks.iter().flat_map(|block| block.lines.iter()).collect();
lines
.windows(2)
.filter(|pair| pair[0].page == pair[1].page)
.map(|pair| pair[1].baseline - pair[0].baseline)
.filter(|pitch| *pitch > 0.0)
.fold(f32::INFINITY, f32::min)
.min(
lines
.first()
.map_or(f32::INFINITY, |line| LONE_LINE_PITCH_EM * line.size),
)
}
pub(crate) fn float_listing_lines(block: &Block) -> Option<Vec<String>> {
let spans = &block.inner_spans;
let mono = spans
.iter()
.flatten()
.all(|span| span.style & MONO != 0 || span.text.trim().is_empty());
if block.inner_lines.len() < 2 || !mono {
return None;
}
let base = block
.inner_lines
.iter()
.map(|line| line.bbox.x0)
.fold(f32::INFINITY, f32::min);
Some(
block
.inner_lines
.iter()
.zip(spans)
.map(|(line, line_spans)| {
let text: String = line_spans.iter().map(|span| span.text.as_str()).collect();
let indent = ((line.bbox.x0 - base) / char_width(line)).round().max(0.0) as usize;
format!("{}{}", " ".repeat(indent), text.trim())
})
.collect(),
)
}
fn indent_starts(lines: &[&Line]) -> Vec<f32> {
let mut edges: Vec<(f32, f32)> = lines.iter().map(|line| (line.bbox.x0, line.size)).collect();
edges.sort_by(|a, b| a.0.total_cmp(&b.0));
let mut starts: Vec<f32> = Vec::new();
let mut last = f32::NEG_INFINITY;
for (edge, size) in edges {
if edge - last > INDENT_LEVEL_TOLERANCE_EM * size {
starts.push(edge);
}
last = edge;
}
starts
}
fn indent_start(starts: &[f32], x0: f32) -> f32 {
starts.iter().rev().find(|start| **start <= x0).copied().unwrap_or(x0)
}
fn listing_char_width(lines: &[&Line]) -> f32 {
let mut widths: Vec<f32> = lines
.iter()
.flat_map(|line| line.glyphs.iter())
.filter(|glyph| glyph.text.chars().count() == 1)
.map(|glyph| glyph.x1 - glyph.x0)
.filter(|width| *width > 0.0)
.collect();
widths.sort_by(f32::total_cmp);
widths
.get(widths.len() / 2)
.copied()
.unwrap_or_else(|| MONO_ADVANCE_EM * lines.first().map_or(1.0, |line| line.size.max(1.0)))
}
fn char_width(line: &Line) -> f32 {
let mut widths: Vec<f32> = line
.glyphs
.iter()
.filter(|glyph| glyph.text.chars().count() == 1)
.map(|glyph| glyph.x1 - glyph.x0)
.filter(|width| *width > 0.0)
.collect();
widths.sort_by(f32::total_cmp);
widths
.get(widths.len() / 2)
.copied()
.unwrap_or(MONO_ADVANCE_EM * line.size.max(1.0))
}
pub(crate) fn listing_html(lines: &[String], caption: &str, id: &str) -> String {
let code = lines.join("\n");
let (lang, confident) = detect(&code);
let lang = if confident { lang } else { Lang::Generic };
let mut carry = Carry::None;
let body: String = lines
.iter()
.map(|line| format!("<span class=\"l\">{}</span>", highlight_line(line, lang, &mut carry)))
.collect();
let mut classes = String::from("listing");
if lines.len() >= NUMBERED_MIN_LINES {
classes.push_str(" numbered");
}
if confident {
classes.push_str(" hl");
}
let caption = if caption.is_empty() {
String::new()
} else {
format!("<figcaption>{caption}</figcaption>")
};
format!(
"<figure class=\"code\"{id}><div class=\"code-head\">{caption}<div class=\"code-tools\">\
<button class=\"btn code-hl\" type=\"button\" aria-pressed=\"{confident}\" aria-label=\"Colour code\">Colour</button>\
<button class=\"btn code-copy\" type=\"button\" aria-label=\"Copy code\"><span class=\"cp\">Copy</span><span class=\"ok\">Copied</span></button>\
</div></div><div class=\"code-box\"><pre class=\"{classes}\" tabindex=\"0\" data-lang=\"{}\" translate=\"no\"><code>{body}</code></pre></div></figure>\n",
lang_name(lang)
)
}
fn lang_name(lang: Lang) -> &'static str {
match lang {
Lang::Python => "python",
Lang::CFamily => "c",
Lang::JavaScript => "javascript",
Lang::Go => "go",
Lang::Rust => "rust",
Lang::Generic => "text",
}
}
struct AlgoLine {
spans: Vec<Span>,
line: Line,
}
pub(crate) fn algorithm_html(block: &Block) -> Option<String> {
let mut lines: Vec<AlgoLine> = block
.inner_lines
.iter()
.zip(&block.inner_spans)
.map(|(line, spans)| AlgoLine {
spans: spans.clone(),
line: line.clone(),
})
.collect();
merge_orphans(&mut lines);
lines.retain(|algo| !plain(&algo.spans).is_empty());
let texts: Vec<String> = lines.iter().map(|algo| plain(&algo.spans)).collect();
if lines.len() < ALGORITHM_MIN_LINES || !reads_as_pseudocode(&texts) {
return None;
}
let levels = indent_levels(&lines);
let mut out = String::from("<div class=\"algo\">");
let mut number = 0;
for (algo, level) in lines.iter().zip(levels) {
let text = plain(&algo.spans);
let header = ALGORITHM_HEADERS.iter().any(|word| text.starts_with(word));
let (statement, comment) = split_comment(&algo.spans, &text);
let num = if header {
String::new()
} else {
number += 1;
number.to_string()
};
let cmt = comment
.map(|spans| format!("<span class=\"cmt\">{}</span>", spans_html(&spans)))
.unwrap_or_default();
out.push_str(&format!(
"<div class=\"ln{}\"><i>{num}</i><div class=\"st in{level}\"><span>{}</span>{cmt}</div></div>",
if header { " req" } else { "" },
spans_html(&statement)
));
}
out.push_str("</div>");
Some(out)
}
fn reads_as_pseudocode(texts: &[String]) -> bool {
let assigns = texts
.iter()
.any(|text| ALGORITHM_ASSIGNMENTS.iter().any(|sign| text.contains(sign)));
let controls = texts.iter().any(|text| {
let word: String = text.trim_start().chars().take_while(|ch| ch.is_alphabetic()).collect();
ALGORITHM_CONTROL_WORDS.contains(&word.as_str())
});
texts.first().is_some_and(|first| opens_algorithm(first)) || (assigns && controls)
}
fn opens_algorithm(first: &str) -> bool {
let word: String = first.chars().take_while(|ch| ch.is_alphanumeric()).collect();
ALGORITHM_OPENERS.contains(&word.as_str()) || first.split_once([':', '.']).is_some_and(|(num, _)| num == "1")
}
fn merge_orphans(lines: &mut Vec<AlgoLine>) {
let mut idx = 0;
while idx < lines.len() {
let text = plain(&lines[idx].spans);
let orphan = !text.is_empty() && text.chars().count() <= ORPHAN_MAX_CHARS && lines.len() > 1;
let host = orphan
.then(|| nearest_line(lines, idx))
.flatten()
.filter(|&host| (lines[host].line.baseline - lines[idx].line.baseline).abs() < lines[idx].line.size);
match host {
Some(host) => {
let x0 = lines[idx].line.bbox.x0;
let at = char_offset_at(&lines[host].line, x0);
insert_text(&mut lines[host].spans, at, &text);
lines.remove(idx);
}
None => idx += 1,
}
}
}
fn nearest_line(lines: &[AlgoLine], idx: usize) -> Option<usize> {
let baseline = lines[idx].line.baseline;
(0..lines.len()).filter(|&other| other != idx).min_by(|&a, &b| {
let da = (lines[a].line.baseline - baseline).abs();
let db = (lines[b].line.baseline - baseline).abs();
da.total_cmp(&db)
})
}
fn char_offset_at(line: &Line, x: f32) -> usize {
let mut offset = 0;
for (glyph_idx, glyph) in line.glyphs.iter().enumerate() {
if glyph.space_before && glyph_idx > 0 {
offset += 1;
}
if glyph.x0 >= x {
return offset;
}
offset += glyph.text.chars().count();
}
offset
}
fn insert_text(spans: &mut [Span], at: usize, text: &str) {
let mut start = 0;
let count = spans.len();
for (idx, span) in spans.iter_mut().enumerate() {
let len = span.text.chars().count();
if at <= start + len || idx + 1 == count {
let byte = span
.text
.char_indices()
.nth(at.saturating_sub(start))
.map_or(span.text.len(), |(byte, _)| byte);
span.text.insert_str(byte, text);
return;
}
start += len;
}
}
fn split_spans(spans: &[Span], at: usize) -> (Vec<Span>, Vec<Span>) {
let (mut head, mut tail) = (Vec::new(), Vec::new());
let mut start = 0;
for span in spans {
let len = span.text.chars().count();
if start + len <= at {
head.push(span.clone());
} else if start >= at {
tail.push(span.clone());
} else {
let byte = span
.text
.char_indices()
.nth(at - start)
.map_or(span.text.len(), |(byte, _)| byte);
let mut first = span.clone();
first.text.truncate(byte);
let mut second = span.clone();
second.text = span.text[byte..].to_string();
head.push(first);
tail.push(second);
}
start += len;
}
(head, tail)
}
fn split_comment(spans: &[Span], text: &str) -> (Vec<Span>, Option<Vec<Span>>) {
let chars: Vec<char> = text.chars().collect();
let marker = chars
.iter()
.position(|ch| *ch == '▷')
.or_else(|| text.find(" // ").map(|byte| text[..byte].chars().count() + 1));
let at = marker.or_else(|| trailing_parenthetical(&chars));
match at {
Some(at) if at > 0 => {
let lead = spans.iter().map(|span| span.text.as_str()).collect::<String>();
let skipped = lead.chars().take_while(|ch| ch.is_whitespace()).count();
let (statement, comment) = split_spans(spans, at + skipped);
(statement, Some(comment))
}
_ => (spans.to_vec(), None),
}
}
fn trailing_parenthetical(chars: &[char]) -> Option<usize> {
if chars.last() != Some(&')') {
return None;
}
let mut depth = 0;
for idx in (0..chars.len()).rev() {
match chars[idx] {
')' => depth += 1,
'(' => {
depth -= 1;
if depth == 0 {
let words = chars.get(idx + 1).is_some_and(|ch| ch.is_uppercase()) && chars[idx..].contains(&' ');
let spaced = idx > 0 && chars[idx - 1] == ' ';
return (words && spaced).then_some(idx);
}
}
_ => {}
}
}
None
}
fn indent_levels(lines: &[AlgoLine]) -> Vec<usize> {
let is_header = |algo: &AlgoLine| {
ALGORITHM_HEADERS
.iter()
.any(|word| plain(&algo.spans).starts_with(word))
};
let mut edges: Vec<f32> = lines
.iter()
.filter(|algo| !is_header(algo))
.map(|algo| algo.line.bbox.x0)
.collect();
edges.sort_by(f32::total_cmp);
edges.dedup_by(|a, b| (*a - *b).abs() < INDENT_TOLERANCE_PT);
lines
.iter()
.map(|algo| {
if is_header(algo) {
return 0;
}
let x0 = algo.line.bbox.x0;
edges
.iter()
.take_while(|edge| **edge < x0 - INDENT_TOLERANCE_PT)
.count()
.min(ALGORITHM_MAX_INDENT)
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
fn texts(lines: &[&str]) -> Vec<String> {
lines.iter().map(|line| (*line).to_string()).collect()
}
#[test]
fn pseudocode_without_an_opener_is_recognised() {
let vae = texts(&[
"θ, φ ← Initialize parameters",
"repeat",
"XM ← Random minibatch of M datapoints",
"until convergence of parameters (θ, φ)",
"return θ, φ",
]);
assert!(reads_as_pseudocode(&vae));
assert!(reads_as_pseudocode(&texts(&["Require: α", "m0 ← 0", "end while"])));
assert!(reads_as_pseudocode(&texts(&["1: x := 0", "2: y := 1", "3: z := 2"])));
}
#[test]
fn text_that_is_not_pseudocode_keeps_its_picture() {
assert!(!reads_as_pseudocode(&texts(&["Encoder ← input", "Decoder", "Loss"])));
assert!(!reads_as_pseudocode(&texts(&[
"If the input is long",
"the model",
"returns early"
])));
assert!(!reads_as_pseudocode(&[]));
}
}