Skip to main content

cellix_doc/
figure.rs

1//! Pictures as a document's source writes them, so the page, the web page and the PDF all
2//! read a picture's size the same way. Markdown has no way to say how wide an image is, so
3//! this uses the form Pandoc and many others read: `![alt](path){width=50%}`.
4
5/// An image standing alone on a Markdown line.
6#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7pub struct ImageLine<'a> {
8    pub indent: usize,
9    pub alt: &'a str,
10    pub path: &'a str,
11    /// Share of the page, in percent.
12    pub width: Option<u32>,
13}
14
15fn percent(attributes: &str) -> Option<u32> {
16    let value = attributes.trim().strip_prefix("width=")?;
17    value.strip_suffix('%')?.trim().parse().ok()
18}
19
20pub fn image_line(line: &str) -> Option<ImageLine<'_>> {
21    let text = line.trim();
22    let (text, width) = match text.rsplit_once("){") {
23        Some((image, attributes)) if attributes.ends_with('}') => (
24            &text[..=image.len()],
25            percent(attributes.trim_end_matches('}')),
26        ),
27        _ => (text, None),
28    };
29    let rest = text.strip_prefix("![")?.strip_suffix(')')?;
30    let (alt, path) = rest.split_once("](")?;
31    (!path.contains(' ')).then_some(ImageLine {
32        indent: line.len() - line.trim_start().len(),
33        alt,
34        path,
35        width,
36    })
37}
38
39/// A Markdown image line, set to a share of the page.
40pub fn set_width(line: &str, percent: u32) -> Option<String> {
41    let image = image_line(line)?;
42    let pad = " ".repeat(image.indent);
43    Some(format!(
44        "{pad}![{}]({}){{width={percent}%}}",
45        image.alt, image.path
46    ))
47}
48
49/// A Markdown image line with another file in it, keeping its words and size.
50pub fn set_path(line: &str, path: &str) -> Option<String> {
51    let image = image_line(line)?;
52    let pad = " ".repeat(image.indent);
53    let size = image
54        .width
55        .map_or_else(String::new, |w| format!("{{width={w}%}}"));
56    Some(format!("{pad}![{}]({path}){size}", image.alt))
57}
58
59/// The share of the page an `\includegraphics` line asks for.
60pub fn graphics_width(line: &str) -> Option<u32> {
61    let from = line.find("\\includegraphics[")? + "\\includegraphics[".len();
62    let options = &line[from..from + line[from..].find(']')?];
63    let value = options
64        .split(',')
65        .find_map(|o| o.trim().strip_prefix("width="))?;
66    let number = value
67        .split('\\')
68        .next()
69        .filter(|n| !n.is_empty())
70        .unwrap_or("1");
71    Some((number.parse::<f32>().ok()? * 100.0).round() as u32)
72}
73
74/// An `\includegraphics` line, set to a share of the page.
75pub fn set_graphics_width(line: &str, percent: u32) -> Option<String> {
76    let at = line.find("\\includegraphics")?;
77    let after = at + "\\includegraphics".len();
78    let brace = after + line[after..].find('{')?;
79    let share = f64::from(percent) / 100.0;
80    let width = if percent == 100 {
81        "width=\\linewidth".to_string()
82    } else {
83        format!("width={share:.2}\\linewidth")
84    };
85    Some(format!(
86        "{}\\includegraphics[{width}]{}",
87        &line[..at],
88        &line[brace..]
89    ))
90}
91
92/// An `\includegraphics` line with another file in it.
93pub fn set_graphics_path(line: &str, path: &str) -> Option<String> {
94    let at = line.find("\\includegraphics")?;
95    let open = at + line[at..].find('{')?;
96    let close = open + line[open..].find('}')?;
97    Some(format!("{}{path}{}", &line[..=open], &line[close..]))
98}
99
100/// The document with each sized image written the way `write` says.
101pub fn rewrite_sized(markdown: &str, write: impl Fn(&ImageLine, u32) -> String) -> String {
102    let lines = markdown.lines().map(|line| {
103        image_line(line)
104            .and_then(|image| image.width.map(|width| write(&image, width)))
105            .unwrap_or_else(|| line.to_string())
106    });
107    lines.collect::<Vec<_>>().join("\n")
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113
114    #[test]
115    fn an_image_can_carry_its_width() {
116        let image = image_line("![Loss](plots/loss.png){width=50%}").unwrap();
117        assert_eq!(image.path, "plots/loss.png");
118        assert_eq!(image.alt, "Loss");
119        assert_eq!(image.width, Some(50));
120        assert_eq!(image_line("![a](b.png)").unwrap().width, None);
121        assert!(image_line("text ![a](b.png)").is_none());
122        assert!(image_line("![a](b c.png)").is_none());
123    }
124
125    #[test]
126    fn sizing_an_image_rewrites_only_its_size() {
127        assert_eq!(
128            set_width("  ![a](b.png)", 25).unwrap(),
129            "  ![a](b.png){width=25%}"
130        );
131        assert_eq!(
132            set_width("![a](b.png){width=25%}", 75).unwrap(),
133            "![a](b.png){width=75%}"
134        );
135        assert_eq!(
136            set_path("![a](b.png){width=25%}", "c.jpg").unwrap(),
137            "![a](c.jpg){width=25%}"
138        );
139    }
140
141    #[test]
142    fn a_paper_says_its_width_its_own_way() {
143        let line = "  \\includegraphics[width=0.8\\linewidth]{a.png}";
144        assert_eq!(graphics_width(line), Some(80));
145        assert_eq!(
146            graphics_width("\\includegraphics[width=\\linewidth]{a}"),
147            Some(100)
148        );
149        assert_eq!(graphics_width("\\includegraphics{a}"), None);
150        assert_eq!(
151            set_graphics_width(line, 50).unwrap(),
152            "  \\includegraphics[width=0.50\\linewidth]{a.png}"
153        );
154        assert_eq!(
155            set_graphics_width("\\includegraphics{a}", 100).unwrap(),
156            "\\includegraphics[width=\\linewidth]{a}"
157        );
158        assert_eq!(
159            set_graphics_path(line, "b.pdf").unwrap(),
160            "  \\includegraphics[width=0.8\\linewidth]{b.pdf}"
161        );
162    }
163}