pub(crate) mod inline;
use super::latex::math::latex;
use super::{
CAP_LABEL, Equations, HtmlOptions, ImageStore, Mode, PageImage, caption_first, code, code_run, doc_title,
equation_math, figure_alt, float_class, heading_tag, is_abstract_text, is_scene_break, plain,
stray_equation_number, table_walk,
};
use crate::analysis::pipeline::Analysis;
use crate::backend::PdfFile;
use crate::model::{Block, BlockKind, Document, FloatKind, ImageSpec, Span, Table, TableCell};
use crate::render::Pictures;
use inline::{Inline, escape, escape_line_start, note_label, spans_html};
use std::collections::HashSet;
const MIN_FENCE: usize = 3;
const MD_NEST_INDENT: usize = 4;
const CONTENTS_INDENT: usize = 2;
#[derive(Debug, Clone)]
pub struct MarkdownOptions {
pub inline_images: bool,
pub asset_dir: String,
pub scale: f32,
pub jobs: usize,
pub equations: Equations,
pub mode: Mode,
}
impl Default for MarkdownOptions {
fn default() -> Self {
Self {
mode: Mode::Friendly,
inline_images: false,
asset_dir: "images".into(),
scale: 3.0,
jobs: 0,
equations: Equations::MathMl,
}
}
}
pub struct MarkdownOutput {
pub markdown: String,
pub files: Vec<(String, Vec<u8>)>,
}
pub fn render_markdown(analysis: &Analysis, pdf: Option<&PdfFile>, opts: &MarkdownOptions) -> MarkdownOutput {
let html_opts = HtmlOptions {
mode: Mode::Friendly,
inline_images: opts.inline_images,
asset_dir: opts.asset_dir.clone(),
scale: opts.scale,
page_image: PageImage::Svg,
jobs: opts.jobs,
embed_fonts: false,
equations: opts.equations,
};
let mut images = ImageStore {
opts: &html_opts,
jobs: Vec::new(),
};
let numbered = super::notes::numbered_analysis(analysis);
let doc = &numbered.as_ref().unwrap_or(analysis).doc;
let anchors = linked_anchors(doc);
let mut writer = Writer {
opts,
inline: Inline {
anchors: &anchors,
math: opts.equations == Equations::MathMl,
},
images: &mut images,
out: String::new(),
list_indent: 0,
bracket_src: !opts.inline_images && opts.asset_dir.contains(' '),
};
writer.write(doc);
let text = writer.out.trim_end().to_string() + "\n";
let out = images.finish(Pictures::new(pdf, &analysis.doc), text);
MarkdownOutput {
markdown: out.html,
files: out.files,
}
}
pub(crate) fn linked_anchors(doc: &Document) -> HashSet<String> {
let targets: HashSet<&str> = doc
.blocks
.iter()
.flat_map(|block| block.spans.iter().chain(block.rows.iter().flatten()))
.chain(
doc.blocks
.iter()
.filter_map(|block| block.table.as_ref())
.flat_map(|table| table.rows.iter().flatten().flat_map(|cell| cell.spans.iter())),
)
.filter_map(|span| span.href.as_deref()?.strip_prefix('#'))
.collect();
doc.blocks
.iter()
.filter_map(|block| block.anchor.as_deref())
.filter(|anchor| targets.contains(anchor))
.map(str::to_string)
.collect()
}
struct Writer<'a, 'r> {
opts: &'a MarkdownOptions,
inline: Inline<'a>,
images: &'a mut ImageStore<'r>,
out: String,
list_indent: usize,
bracket_src: bool,
}
impl Writer<'_, '_> {
fn write(&mut self, doc: &Document) {
let blocks: Vec<&Block> = doc.blocks.iter().collect();
let mut idx = 0;
let mut in_abstract = false;
let mut after_front = false;
while idx < blocks.len() {
let block = blocks[idx];
if !after_front && !matches!(block.kind, BlockKind::Title | BlockKind::Authors | BlockKind::Note) {
self.arxiv_link(doc);
after_front = true;
}
if let Some(end) = code_run(&blocks, idx) {
self.anchor(block);
self.fence(&code::listing_lines(&blocks[idx..end]));
(idx, in_abstract) = (end, false);
continue;
}
match &block.kind {
BlockKind::Title => {
let start = idx;
idx = self.title(doc, &blocks, idx);
blocks[start..idx].iter().for_each(|block| self.note_definitions(block));
continue;
}
BlockKind::Paragraph { in_abstract: true } => {
let had_heading = idx > 0
&& matches!(blocks[idx - 1].kind, BlockKind::Heading { .. })
&& is_abstract_text(&blocks[idx - 1].spans);
if !in_abstract && !had_heading {
self.paragraph(&format!("{} Abstract", heading_marks(1)));
}
in_abstract = true;
}
BlockKind::Equation { .. } => {}
_ => in_abstract = false,
}
if let BlockKind::Equation { image, number: None } = &block.kind
&& let Some(number) = blocks.get(idx + 1).and_then(|next| stray_equation_number(next))
{
self.equation(block, image.as_ref(), Some(&number));
idx += 2;
continue;
}
self.block(block);
self.note_definitions(block);
idx += 1;
}
if !after_front {
self.arxiv_link(doc);
}
}
fn block(&mut self, block: &Block) {
self.anchor(block);
match &block.kind {
BlockKind::Title => self.paragraph(&format!("# {}", self.inline.spans(&block.spans))),
BlockKind::Authors => self.authors(block),
BlockKind::Note => self.text_paragraph(&block.spans),
BlockKind::Heading { level } => {
let text = self.inline.spans(&block.spans);
self.paragraph(&format!("{} {text}", heading_marks(*level)));
}
BlockKind::Paragraph { .. } if is_scene_break(&block.spans) => self.paragraph("* * *"),
BlockKind::Paragraph { .. } => self.text_paragraph(&block.spans),
BlockKind::ListItem { marker, level } => self.list_item(block, marker.as_deref(), *level),
BlockKind::ListContinuation => {
let text = escape_line_start(&self.inline.spans(&block.spans));
self.paragraph(&format!("{}{text}", " ".repeat(self.list_indent.max(2))));
}
BlockKind::Reference { .. } => self.text_paragraph(&block.spans),
BlockKind::Footnote { marker } if marker.is_empty() => {
let text = self.inline.spans(&block.spans);
if !text.is_empty() {
self.paragraph(&format!("> {text}"));
}
}
BlockKind::Footnote { marker } => {
let mark = format!("<sup>{}</sup> ", escape(marker));
self.paragraph(&format!("{mark}{}", self.inline.spans(&block.spans)));
}
BlockKind::Equation { image, number } => self.equation(block, image.as_ref(), number.as_deref()),
BlockKind::Figure { kind, image, label } => self.figure(block, *kind, image.as_ref(), label),
BlockKind::ContentsEntry { level, page } => {
let indent = " ".repeat(usize::from(level.saturating_sub(1)) * CONTENTS_INDENT);
let text = self.inline.spans(&block.spans);
let page = if page.is_empty() {
String::new()
} else {
format!(" — {}", escape(page))
};
self.line(&format!("{indent}- {text}{page}"));
}
BlockKind::Code => {
let lines: Vec<String> = block
.rows
.iter()
.map(|row| row.iter().map(|span| span.text.as_str()).collect())
.collect();
self.fence(&lines);
}
}
}
fn note_definitions(&mut self, block: &Block) {
for call in super::notes::calls(&[block]) {
let text = self.inline.spans(call.note.as_deref().unwrap_or_default());
if !call.text.is_empty() {
self.paragraph(&format!("[^{}]: {text}", note_label(call)));
}
}
}
fn paragraph(&mut self, text: &str) {
self.end_tight_list();
self.out.push_str(text);
self.out.push_str("\n\n");
}
fn line(&mut self, text: &str) {
self.out.push_str(text);
self.out.push('\n');
}
fn end_tight_list(&mut self) {
if !self.out.is_empty() && !self.out.ends_with("\n\n") {
self.out.push('\n');
}
}
fn text_paragraph(&mut self, spans: &[Span]) {
let text = self.inline.spans(spans);
if !text.is_empty() {
self.paragraph(&escape_line_start(&text));
}
}
fn anchor(&mut self, block: &Block) {
if let Some(anchor) = block
.anchor
.as_deref()
.filter(|anchor| self.inline.anchors.contains(*anchor))
{
self.end_tight_list();
self.out.push_str(&format!("<a id=\"{}\"></a>\n\n", super::esc(anchor)));
}
}
fn arxiv_link(&mut self, doc: &Document) {
if let Some(id) = &doc.meta.arxiv_id {
self.paragraph(&format!("[arXiv:{}](https://arxiv.org/abs/{id})", escape(id)));
}
}
fn title(&mut self, doc: &Document, blocks: &[&Block], start: usize) -> usize {
let end = start
+ blocks[start..]
.iter()
.take_while(|block| matches!(block.kind, BlockKind::Title))
.count();
let mut spans: Vec<Span> = Vec::new();
for block in &blocks[start..end] {
self.anchor(block);
if !spans.is_empty() {
spans.push(Span::plain(" "));
}
spans.extend(block.spans.iter().cloned());
}
let text = self.inline.spans(&spans);
if text.is_empty() {
self.paragraph(&format!("# {}", escape(&doc_title(doc))));
} else {
self.paragraph(&format!("# {text}"));
}
end
}
fn authors(&mut self, block: &Block) {
let rows = if block.rows.is_empty() {
std::slice::from_ref(&block.spans)
} else {
&block.rows[..]
};
let lines: Vec<String> = rows
.iter()
.enumerate()
.map(|(i, row)| {
let text = self.inline.spans(row);
if i == 0 && !text.is_empty() && !text.contains('*') {
format!("**{text}**")
} else {
text
}
})
.filter(|text| !text.is_empty())
.collect();
if !lines.is_empty() {
self.paragraph(&escape_line_start(&lines.join(" \n")));
}
}
fn list_item(&mut self, block: &Block, marker: Option<&str>, level: u8) {
let number = marker
.map(|marker| marker.trim_end_matches(['.', ')']))
.filter(|digits| !digits.is_empty() && digits.len() <= 9 && digits.bytes().all(|b| b.is_ascii_digit()));
let rest = marker.and_then(|marker| strip_label(&block.spans, marker));
let prefix = match (number, marker, &rest) {
(Some(number), _, _) => format!("{number}. "),
(None, Some(marker), Some(_)) => format!("- {} ", escape(marker)),
_ => "- ".to_string(),
};
let text = self.inline.spans(rest.as_deref().unwrap_or(&block.spans));
let nest = " ".repeat(usize::from(level) * MD_NEST_INDENT);
self.list_indent = nest.len() + if number.is_some() { prefix.len() } else { 2 };
self.paragraph(&format!("{nest}{prefix}{text}"));
}
fn fence(&mut self, lines: &[String]) {
let longest = lines
.iter()
.flat_map(|line| line.split(|ch| ch != '`'))
.map(str::len)
.max()
.unwrap_or(0);
let fence = "`".repeat((longest + 1).max(MIN_FENCE));
let body = lines.join("\n");
self.paragraph(&format!("{fence}\n{}\n{fence}", body.trim_end()));
}
fn equation(&mut self, block: &Block, image: Option<&ImageSpec>, number: Option<&str>) {
let tag = number.map(|number| number.trim().trim_start_matches('(').trim_end_matches(')').trim());
if let Some(math) = equation_math(block, image, self.opts.equations) {
let tag = tag.map(|tag| format!(" \\tag{{{tag}}}")).unwrap_or_default();
self.paragraph(&format!("$$\n{}{tag}\n$$", latex(math)));
return;
}
let shown = match image {
Some(image) => self.picture(image, &plain(&block.spans), "eq"),
None => escape(&plain(&block.spans)),
};
let number = number.map(|number| format!(" {}", escape(number))).unwrap_or_default();
self.paragraph(&format!("{shown}{number}"));
}
fn figure(&mut self, block: &Block, kind: FloatKind, image: Option<&ImageSpec>, label: &Option<String>) {
let caption = (!block.spans.is_empty()).then(|| self.caption(&block.spans));
if kind == FloatKind::Algorithm
&& block.table.is_none()
&& let Some(lines) = code::float_listing_lines(block)
{
if let Some(caption) = &caption {
self.paragraph(caption);
}
return self.fence(&lines);
}
let caption_first = caption_first(block, image);
if caption_first && let Some(caption) = &caption {
self.paragraph(caption);
}
if let Some(table) = &block.table {
let text = self.table(table);
self.paragraph(&text);
} else if let Some(spec) = image {
let picture = self.picture(spec, &figure_alt(block, label), float_class(kind));
self.paragraph(&picture);
}
if !caption_first && let Some(caption) = &caption {
self.paragraph(caption);
}
}
fn caption(&self, spans: &[Span]) -> String {
if let Some(first) = spans.first()
&& let Some(found) = CAP_LABEL.find(&first.text)
{
let label = first.text[..found.end()].trim_end();
let mut rest = spans.to_vec();
rest[0].text = first.text[label.len()..].to_string();
let text = self.inline.spans(&rest);
return format!("**{}** {text}", escape(label)).trim_end().to_string();
}
escape_line_start(&self.inline.spans(spans))
}
fn picture(&mut self, spec: &ImageSpec, alt: &str, hint: &str) -> String {
let src = self.images.region(spec, hint);
let alt = escape(&alt.replace(['\n', '\r'], " "));
if self.bracket_src {
format!("")
} else {
format!("")
}
}
fn table(&self, table: &Table) -> String {
if self.opts.mode == Mode::Friendly && table.n_cols > 0 {
return flat_table(&self.inline, table);
}
let simple = table.header_rows == 1
&& table.n_cols > 0
&& table
.rows
.iter()
.flatten()
.all(|cell| cell.colspan == 1 && cell.rowspan == 1);
if simple {
self.pipe_table(table)
} else {
self.html_table(table)
}
}
fn pipe_table(&self, table: &Table) -> String {
let mut lines = Vec::new();
for (row_idx, row) in table.rows.iter().enumerate() {
let mut cells = vec![String::new(); table.n_cols];
for cell in row.iter().filter(|cell| cell.col < table.n_cols) {
cells[cell.col] = self.inline.cell(&cell.spans);
}
lines.push(format!("| {} |", cells.join(" | ")));
if row_idx == 0 {
let rule: Vec<&str> = (0..table.n_cols)
.map(|col| match table.col_align.get(col).copied() {
Some("center") => ":---:",
Some("right") => "---:",
_ => "---",
})
.collect();
lines.push(format!("| {} |", rule.join(" | ")));
}
}
lines.join("\n")
}
fn html_table(&self, table: &Table) -> String {
let mut out = String::from("<table>");
let mut open_row: Option<usize> = None;
table_walk(table, |row_idx, _, cell| {
if open_row != Some(row_idx) {
if open_row.is_some() {
out.push_str("</tr>");
}
out.push_str("\n<tr>");
open_row = Some(row_idx);
}
let tag = if row_idx < table.header_rows { "th" } else { "td" };
out.push_str(&match cell {
None => format!("<{tag}></{tag}>"),
Some(cell) => self.html_cell(cell, tag),
});
});
if open_row.is_some() {
out.push_str("</tr>");
}
out.push_str("\n</table>");
out
}
fn html_cell(&self, cell: &TableCell, tag: &str) -> String {
format!(
"<{tag}{}>{}</{tag}>",
super::span_attrs(cell),
spans_html(&cell.spans, self.inline.anchors)
)
}
}
fn flat_table(inline: &Inline<'_>, table: &Table) -> String {
let grid = covering_cells(table);
let header_rows = table.header_rows.min(grid.len());
let head = &grid[..header_rows];
let header: Vec<String> = (0..table.n_cols)
.map(|col| flat_header(inline, head, col, table.n_cols))
.collect();
let rule: Vec<&str> = (0..table.n_cols)
.map(|col| match table.col_align.get(col).copied() {
Some("center") => ":---:",
Some("right") => "---:",
_ => "---",
})
.collect();
let mut lines = vec![pipe_row(&header), pipe_row(&rule)];
lines.extend(
grid[header_rows..]
.iter()
.filter_map(|row| flat_row(inline, head, row, table.n_cols))
.map(|cells| pipe_row(&cells)),
);
lines.join("\n")
}
fn flat_header(inline: &Inline<'_>, head: &[Vec<Option<&TableCell>>], col: usize, n_cols: usize) -> String {
let mut out = String::new();
let mut group = false;
for (row_idx, row) in head.iter().enumerate() {
let Some(cell) = row[col] else { continue };
let is_group = is_group(head, row_idx, cell, n_cols);
if col != cell.col && !is_group {
continue;
}
let text = inline.cell(&cell.spans);
if text.is_empty() || out.ends_with(&text) {
continue;
}
if !out.is_empty() {
out.push_str(if group { HEADER_GROUP_JOIN } else { " " });
}
out.push_str(text.strip_suffix(':').unwrap_or(&text).trim_end());
group = is_group;
}
out
}
fn flat_row(
inline: &Inline<'_>,
head: &[Vec<Option<&TableCell>>],
row: &[Option<&TableCell>],
n_cols: usize,
) -> Option<Vec<String>> {
let mut cells: Vec<String> = (0..n_cols)
.map(|col| match row[col] {
Some(cell) if col == cell.col || under_one_group(head, cell, n_cols) => inline.cell(&cell.spans),
_ => String::new(),
})
.collect();
if cells.iter().all(String::is_empty) {
return None;
}
let label = n_cols > 1
&& row
.iter()
.all(|cell| cell.is_some_and(|cell| row[0].is_some_and(|first| std::ptr::eq(cell, first))));
if label {
let text = std::mem::take(&mut cells[0]);
cells.iter_mut().for_each(String::clear);
cells[0] = if text.starts_with("**") {
text
} else {
format!("**{text}**")
};
}
Some(cells)
}
const HEADER_GROUP_JOIN: &str = ": ";
fn pipe_row<S: AsRef<str>>(cells: &[S]) -> String {
let cells: Vec<&str> = cells.iter().map(AsRef::as_ref).collect();
format!("| {} |", cells.join(" | "))
}
fn is_group(header: &[Vec<Option<&TableCell>>], row_idx: usize, cell: &TableCell, n_cols: usize) -> bool {
cell.colspan > 1 && (cell.colspan < n_cols || splits_below(header, row_idx, cell))
}
fn splits_below(header: &[Vec<Option<&TableCell>>], row_idx: usize, cell: &TableCell) -> bool {
header[row_idx + 1..].iter().any(|row| {
row.iter()
.skip(cell.col)
.take(cell.colspan)
.any(|below| below.is_some_and(|below| !std::ptr::eq(below, cell) && !below.spans.is_empty()))
})
}
fn under_one_group(header: &[Vec<Option<&TableCell>>], cell: &TableCell, n_cols: usize) -> bool {
cell.colspan > 1
&& header.iter().enumerate().any(|(row_idx, row)| {
row.get(cell.col).copied().flatten().is_some_and(|group| {
group.col <= cell.col
&& group.col + group.colspan >= cell.col + cell.colspan
&& is_group(header, row_idx, group, n_cols)
})
})
}
fn covering_cells(table: &Table) -> Vec<Vec<Option<&TableCell>>> {
let n_rows = table.rows.len();
let mut grid = vec![vec![None; table.n_cols]; n_rows];
for (row_idx, row) in table.rows.iter().enumerate() {
for cell in row {
let rows_end = (row_idx + cell.rowspan.max(1)).min(n_rows);
let cols_end = (cell.col + cell.colspan.max(1)).min(table.n_cols);
for grid_row in &mut grid[row_idx..rows_end] {
for slot in grid_row.iter_mut().take(cols_end).skip(cell.col) {
*slot = Some(cell);
}
}
}
}
grid
}
fn heading_marks(level: u8) -> &'static str {
match heading_tag(level) {
"h2" => "##",
"h3" => "###",
"h4" => "####",
_ => "#####",
}
}
pub(crate) fn strip_label(spans: &[Span], label: &str) -> Option<Vec<Span>> {
let first = spans.first()?;
let rest = first.text.strip_prefix(label).filter(|_| !label.is_empty())?;
let mut spans = spans.to_vec();
spans[0].text = rest.trim_start().to_string();
Some(spans)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::TableGeom;
fn cell(col: usize, colspan: usize, rowspan: usize, text: &str) -> TableCell {
TableCell {
col,
colspan,
rowspan,
spans: vec![Span::plain(text)],
}
}
fn table(n_cols: usize, header_rows: usize, rows: Vec<Vec<TableCell>>) -> Table {
let n_rows = rows.len();
Table {
n_cols,
header_rows,
col_align: vec!["left"; n_cols],
rows,
rule_above: vec![vec![0; n_cols]; n_rows],
rule_bottom: vec![0; n_cols],
rule_left: vec![vec![false; n_cols]; n_rows],
rule_right: vec![false; n_rows],
geom: TableGeom::default(),
}
}
fn flat(table: &Table) -> String {
let anchors = HashSet::new();
let inline = Inline {
anchors: &anchors,
math: false,
};
flat_table(&inline, table)
}
#[test]
fn flat_table_joins_header_rows_and_repeats_spanning_cells() {
let table = table(
5,
2,
vec![
vec![cell(0, 1, 2, "Model"), cell(1, 2, 1, "BLEU"), cell(3, 2, 1, "Cost")],
vec![
cell(1, 1, 1, "DE"),
cell(2, 1, 1, "FR"),
cell(3, 1, 1, "DE"),
cell(4, 1, 1, "FR"),
],
vec![
cell(0, 1, 2, "A"),
cell(1, 1, 1, "1"),
cell(2, 1, 1, "2"),
cell(3, 2, 1, "9"),
],
vec![cell(1, 3, 1, "same as above"), cell(4, 1, 1, "8")],
vec![cell(0, 5, 1, "Ensembles")],
],
);
assert_eq!(
flat(&table),
"| Model | BLEU: DE | BLEU: FR | Cost: DE | Cost: FR |\n\
| --- | --- | --- | --- | --- |\n\
| A | 1 | 2 | 9 | 9 |\n\
| A | same as above | | | 8 |\n\
| **Ensembles** | | | | |"
);
}
#[test]
fn flat_table_joins_a_wrapped_header_with_a_space() {
let table = table(
2,
2,
vec![
vec![cell(0, 1, 1, "train"), cell(1, 1, 2, "BLEU")],
vec![cell(0, 1, 1, "steps")],
vec![cell(0, 1, 1, "100K"), cell(1, 1, 1, "25.8")],
],
);
assert_eq!(flat(&table), "| train steps | BLEU |\n| --- | --- |\n| 100K | 25.8 |");
}
#[test]
fn flat_table_writes_an_unsplit_header_once() {
let table = table(
3,
1,
vec![
vec![cell(0, 3, 1, "Dataset Prop. Size")],
vec![cell(0, 1, 1, "C4"), cell(1, 1, 1, "15%"), cell(2, 1, 1, "783 GB")],
],
);
assert_eq!(
flat(&table),
"| Dataset Prop. Size | | |\n| --- | --- | --- |\n| C4 | 15% | 783 GB |"
);
}
#[test]
fn flat_table_without_header_rows_has_an_empty_header() {
let table = table(2, 0, vec![vec![cell(0, 1, 1, "mass"), cell(1, 1, 1, "36 | 5")]]);
assert_eq!(flat(&table), "| | |\n| --- | --- |\n| mass | 36 \\| 5 |");
}
}