use docx_rs::*;
use std::collections::HashMap;
use comrak::nodes::{AstNode, NodeValue};
use super::text_of;
use super::Ctx;
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Kind {
Figure,
Table,
}
impl Kind {
fn word(self) -> &'static str {
match self {
Kind::Figure => "Figure",
Kind::Table => "Table",
}
}
}
pub(crate) struct Caption {
pub kind: Kind,
pub text: String,
pub label: Option<String>,
}
pub(crate) fn caption_of(text: &str) -> Option<Caption> {
let (head, rest) = text.split_once(':')?;
let kind = match head.trim().to_ascii_lowercase().as_str() {
"figure" => Kind::Figure,
"table" => Kind::Table,
_ => return None,
};
let (body, label) = split_label(rest.trim());
Some(Caption {
kind,
text: body.trim().to_string(),
label,
})
}
fn split_label(s: &str) -> (&str, Option<String>) {
if let Some(open) = s.rfind("{#") {
if s.ends_with('}') {
let label = &s[open + 2..s.len() - 1];
if !label.is_empty() {
return (&s[..open], Some(label.to_string()));
}
}
}
(s, None)
}
pub(crate) fn collect<'a>(root: &'a AstNode<'a>, ctx: &mut Ctx) {
if !ctx.opts.captions {
return;
}
for node in root.children() {
if !matches!(node.data.borrow().value, NodeValue::Paragraph) {
continue;
}
let Some(cap) = caption_of(&text_of(node)) else {
continue;
};
let Some(label) = cap.label else {
continue;
};
if ctx.caption_labels.contains_key(&label) {
continue;
}
let name = unique_name(&label, &ctx.caption_labels);
ctx.caption_labels.insert(label, name);
}
}
fn unique_name(label: &str, used: &HashMap<String, String>) -> String {
let base = bookmark_name(label);
if !used.values().any(|v| v == &base) {
return base;
}
(2..)
.map(|n| format!("{base}_{n}"))
.find(|c| !used.values().any(|v| v == c))
.expect("suffix search always terminates")
}
pub(crate) fn paragraph(cap: &Caption, ctx: &mut Ctx) -> Paragraph {
let word = cap.kind.word();
let mut p = Paragraph::new().style("Caption");
let bookmark = cap
.label
.as_ref()
.and_then(|l| ctx.caption_labels.get(l).cloned())
.map(|name| (ctx.bookmark_id(), name));
if let Some((id, name)) = &bookmark {
p = p.add_bookmark_start(*id, name.clone());
}
p = p
.add_run(Run::new().bold().add_text(format!("{word} ")))
.add_run(seq_field(word));
if let Some((id, _)) = &bookmark {
p = p.add_bookmark_end(*id);
}
p = p.add_run(Run::new().bold().add_text(": "));
if !cap.text.is_empty() {
p = p.add_run(Run::new().add_text(&cap.text));
}
p
}
pub(crate) fn reference(label: &str, placeholder: &str, ctx: &Ctx) -> Option<Run> {
let name = ctx.caption_labels.get(label)?;
let shown = if placeholder.is_empty() {
label
} else {
placeholder
};
Some(
Run::new()
.add_field_char(FieldCharType::Begin, true)
.add_instr_text(InstrText::Unsupported(format!("REF {name} \\h")))
.add_field_char(FieldCharType::Separate, false)
.add_text(shown)
.add_field_char(FieldCharType::End, false),
)
}
fn seq_field(kind: &str) -> Run {
Run::new()
.bold()
.add_field_char(FieldCharType::Begin, true)
.add_instr_text(InstrText::Unsupported(format!("SEQ {kind} \\* ARABIC")))
.add_field_char(FieldCharType::Separate, false)
.add_text("1")
.add_field_char(FieldCharType::End, false)
}
pub(crate) fn bookmark_name(label: &str) -> String {
let mut slug: String = label
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
.collect();
slug.truncate(32);
format!("qd_cap_{slug}")
}