cellix-doc 0.4.1

Documents for Cellix: typeset math, HTML export, LaTeX structure and PDF pages
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
//! A Markdown file as a web page that stands alone: math is inline SVG, so the page needs
//! no scripts and no network.

use pulldown_cmark::{CodeBlockKind, Event, Options, Parser, Tag, TagEnd, html};

use crate::{diagram, figure, math};

const STYLE: &str = "
:root { color-scheme: light dark; --text: #1f2328; --dim: #59636e; --line: #d1d9e0;
  --code: #f6f8fa; --link: #0969da; }
@media (prefers-color-scheme: dark) { :root { --text: #e6edf3; --dim: #9198a1;
  --line: #3d444d; --code: #151b23; --link: #4493f8; }
  .math svg, .inline-math svg { filter: invert(1); }
  .diagram { background: #fff; border-radius: 8px; } }
body { max-width: 46rem; margin: 3rem auto; padding: 0 1.25rem; color: var(--text);
  font: 17px/1.65 -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; }
h1, h2, h3 { line-height: 1.25; margin: 2em 0 .6em; } h1 { margin-top: 0; }
a { color: var(--link); } img { max-width: 100%; }
code { font: .88em ui-monospace, Menlo, monospace; background: var(--code);
  padding: .15em .35em; border-radius: 5px; }
pre { background: var(--code); border: 1px solid var(--line); border-radius: 8px;
  padding: 1em; overflow: auto; } pre code { background: none; padding: 0; }
blockquote { margin: 1em 0; padding-left: 1em; border-left: 3px solid var(--line);
  color: var(--dim); }
table { border-collapse: collapse; margin: 1em 0; }
th, td { border: 1px solid var(--line); padding: .4em .8em; } th { background: var(--code); }
.math { text-align: center; margin: 1.2em 0; overflow-x: auto; }
.diagram { text-align: center; margin: 1.2em 0; padding: 1em; overflow-x: auto; }
.diagram svg { max-width: 100%; height: auto; }
mark { background: #ffec9e; color: #1f2328; padding: 0 .15em; border-radius: 3px; }
ins { color: #1a7f37; } del { color: #cf222e; } .note { color: var(--dim); font-size: .85em; }
blockquote[class^=markdown-alert] { color: inherit; border-left-width: 4px; }
blockquote[class^=markdown-alert]::before { display: block; font-weight: 600; margin-top: .6em; }
blockquote[class^=markdown-alert]:has(> .callout-title)::before { content: none; }
.callout-title { font-weight: 600; margin-bottom: .2em; }
.markdown-alert-note { border-color: var(--link); } .markdown-alert-note::before { content: 'Note'; }
.markdown-alert-tip { border-color: #1a7f37; } .markdown-alert-tip::before { content: 'Tip'; }
.markdown-alert-important { border-color: #8857e0; }
.markdown-alert-important::before { content: 'Important'; }
.markdown-alert-warning { border-color: #c08610; }
.markdown-alert-warning::before { content: 'Warning'; }
.markdown-alert-caution { border-color: #cf222e; }
.markdown-alert-caution::before { content: 'Caution'; }
.footnote-definition { font-size: .88em; color: var(--dim); }
hr { border: 0; border-top: 1px solid var(--line); margin: 2em 0; }
";

/// A callout's opening line, `[!NOTE]` or Obsidian's `[!tip]- Title`: GitHub's kind it reads
/// as, and the title written after it, if any. Obsidian's other kinds map to the nearest of
/// GitHub's five.
pub fn callout(line: &str) -> Option<(&'static str, Option<String>)> {
    let rest = line.trim().strip_prefix("[!")?;
    let (name, after) = rest.split_once(']')?;
    let kind = match name.to_ascii_lowercase().as_str() {
        "note" | "info" | "abstract" | "summary" | "tldr" | "todo" | "example" | "quote"
        | "cite" => "NOTE",
        "tip" | "hint" | "success" | "check" | "done" => "TIP",
        "important" | "question" | "help" | "faq" => "IMPORTANT",
        "warning" | "attention" => "WARNING",
        "caution" | "danger" | "error" | "failure" | "fail" | "missing" | "bug" => "CAUTION",
        _ => return None,
    };
    // `-` and `+` only say whether it starts folded.
    let title = after.trim_start_matches(['-', '+']).trim();
    Some((kind, (!title.is_empty()).then(|| title.to_string())))
}

/// Callouts as GitHub writes them, which the parser knows, keeping a title of their own in a
/// first paragraph the page styles as the heading in place of the kind's name.
fn callouts(markdown: &str) -> String {
    let mut out = String::with_capacity(markdown.len());
    for line in markdown.split_inclusive('\n') {
        let body = line.trim_end_matches('\n');
        let quoted = body.trim_start().strip_prefix('>');
        match quoted.and_then(callout) {
            Some((kind, title)) => {
                let lead = &body[..body.len() - body.trim_start().len()];
                out.push_str(&format!("{lead}> [!{kind}]\n"));
                if let Some(title) = title {
                    out.push_str(&format!(
                        "{lead}> <p class=\"callout-title\">{}</p>\n{lead}>\n",
                        escape(&title)
                    ));
                }
            }
            None => out.push_str(line),
        }
    }
    out
}

fn escape(text: &str) -> String {
    text.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
}

fn formula(source: &str, display: bool) -> String {
    let shown =
        math::svg(source, display).unwrap_or_else(|_| format!("<code>{}</code>", escape(source)));
    if display {
        format!("<div class=\"math\">{shown}</div>")
    } else {
        format!("<span class=\"inline-math\">{shown}</span>")
    }
}

/// A block only LaTeX can draw, as what `built` has for it, or as its source.
fn built_or_source(language: &str, source: &str, built: &Built) -> String {
    let body = diagram::fenced_tikz(language, source);
    match built(&body) {
        Some(picture) => format!("<div class=\"diagram\">{picture}</div>"),
        None => format!("<pre><code>{}</code></pre>", escape(source)),
    }
}

/// A diagram as a picture, or its source if it can't be drawn.
fn drawn(kind: diagram::Kind, source: &str) -> String {
    match diagram::svg(kind, source, false) {
        Ok(svg) => format!("<div class=\"diagram\">{svg}</div>"),
        Err(_) => format!("<pre><code>{}</code></pre>", escape(source)),
    }
}

/// `H~2~O` and `x^2^` as tags, leaving alone any tilde or caret that doesn't hug its text.
fn raised(line: &str, marker: char, tag: &str) -> String {
    let chars: Vec<char> = line.chars().collect();
    let mut out = String::with_capacity(line.len());
    let (mut i, mut code) = (0, false);
    while i < chars.len() {
        code ^= chars[i] == '`' || chars[i] == '$';
        let close = (chars[i] == marker && !code)
            .then(|| (i + 2..chars.len().min(i + 32)).find(|n| chars[*n] == marker))
            .flatten()
            .filter(|n| {
                chars[i + 1..*n]
                    .iter()
                    .all(|c| !c.is_whitespace() && *c != marker)
            });
        match close {
            Some(close) => {
                let inner: String = chars[i + 1..close].iter().collect();
                out.push_str(&format!("<{tag}>{inner}</{tag}>"));
                i = close + 1;
            }
            None => {
                out.push(chars[i]);
                i += 1;
            }
        }
    }
    out
}

/// Highlights, tracked changes and raised text, which Markdown doesn't know, as the HTML
/// they mean. The paper reads the same tags.
pub fn marked(markdown: &str) -> String {
    let pairs = [
        ("{++", "<ins>"),
        ("++}", "</ins>"),
        ("{--", "<del>"),
        ("--}", "</del>"),
        ("{==", "<mark>"),
        ("==}", "</mark>"),
        ("{~~", "<del>"),
        ("~>", "</del><ins>"),
        ("~~}", "</ins>"),
        ("{>>", "<span class=\"note\">"),
        ("<<}", "</span>"),
    ];
    let mut out = String::with_capacity(markdown.len());
    let mut code = false;
    let mut highlight = false;
    for line in markdown.split_inclusive('\n') {
        if line.trim_start().starts_with("```") {
            code = !code;
        }
        if code {
            out.push_str(line);
            continue;
        }
        // Inline code keeps its text exactly: `a == b` is code, not a highlight.
        for (index, piece) in line.split('`').enumerate() {
            if index > 0 {
                out.push('`');
            }
            if index % 2 == 1 {
                out.push_str(piece);
            } else {
                out.push_str(&marks_in(piece, &pairs, &mut highlight));
            }
        }
    }
    out
}

/// Text without CriticMarkup's `{>>…<<}` notes.
fn without_notes(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut rest = text;
    while let Some(at) = rest.find("{>>") {
        let Some(end) = rest[at..].find("<<}") else {
            break;
        };
        out.push_str(rest[..at].trim_end_matches(' '));
        rest = &rest[at + end + 3..];
    }
    out.push_str(rest);
    out
}

/// Markdown's marks in text that isn't code.
fn marks_in(text: &str, pairs: &[(&str, &str)], highlight: &mut bool) -> String {
    // `{>>note<<}` is a reviewer's note, for the people writing, not the page.
    let mut text = without_notes(text);
    for (from, to) in pairs {
        text = text.replace(from, to);
    }
    let text = raised(&raised(&text, '~', "sub"), '^', "sup");
    let mut parts = text.split("==");
    let mut out = parts.next().unwrap_or("").to_string();
    for part in parts {
        *highlight = !*highlight;
        out.push_str(if *highlight { "<mark>" } else { "</mark>" });
        out.push_str(part);
    }
    out
}

/// The body of a Markdown document. Formulas that won't parse stay as their source.
pub fn body(markdown: &str) -> String {
    body_with(markdown, &|_| None)
}

/// What's already been built for a block of LaTeX, as HTML.
pub type Built<'a> = dyn Fn(&str) -> Option<String> + 'a;

/// The body of a Markdown document, with what's been built for its blocks of TikZ.
pub fn body_with(markdown: &str, built: &Built) -> String {
    let options = Options::ENABLE_TABLES
        | Options::ENABLE_TASKLISTS
        | Options::ENABLE_STRIKETHROUGH
        | Options::ENABLE_FOOTNOTES
        | Options::ENABLE_GFM
        | Options::ENABLE_MATH;
    let markdown = &callouts(markdown);
    let sized = figure::rewrite_sized(markdown, |image, width| {
        format!(
            "<img src=\"{}\" alt=\"{}\" style=\"width:{width}%\">",
            escape(image.path),
            escape(image.alt)
        )
    });
    let (front, sized) = crate::front::split(&sized);
    let sized = marked(sized);
    let mut events = Vec::new();
    if let Some(title) = &front.title {
        events.push(Event::Html(
            format!("<h1 class=\"title\">{}</h1>\n", escape(title)).into(),
        ));
    }
    let byline: Vec<&str> = [&front.author, &front.date]
        .into_iter()
        .flatten()
        .map(String::as_str)
        .collect();
    if !byline.is_empty() {
        let byline = escape(&byline.join(" · "));
        events.push(Event::Html(
            format!("<p class=\"byline\">{byline}</p>\n").into(),
        ));
    }
    let mut open: Option<(diagram::Kind, String)> = None;
    let mut tikz: Option<(String, String)> = None;
    for event in Parser::new_ext(&sized, options) {
        if let Some((language, source)) = &mut tikz {
            match event {
                Event::Text(text) => source.push_str(&text),
                Event::End(TagEnd::CodeBlock) => {
                    let html = built_or_source(language, source.trim_end(), built);
                    events.push(Event::Html(html.into()));
                    tikz = None;
                }
                _ => {}
            }
            continue;
        }
        match (&mut open, event) {
            (None, Event::Start(Tag::CodeBlock(CodeBlockKind::Fenced(language))))
                if diagram::is_tikz(&language) =>
            {
                tikz = Some((language.to_string(), String::new()));
            }
            (None, Event::Start(Tag::CodeBlock(CodeBlockKind::Fenced(language))))
                if diagram::kind_of(&language).is_some() =>
            {
                open = diagram::kind_of(&language).map(|kind| (kind, String::new()));
            }
            (Some((_, source)), Event::Text(text)) => source.push_str(&text),
            (Some((kind, source)), Event::End(TagEnd::CodeBlock)) => {
                events.push(Event::Html(drawn(*kind, source).into()));
                open = None;
            }
            (_, Event::InlineMath(source)) => {
                events.push(Event::InlineHtml(formula(&source, false).into()));
            }
            (_, Event::DisplayMath(source)) => {
                events.push(Event::Html(formula(&source, true).into()));
            }
            (_, other) => events.push(other),
        }
    }
    let mut out = String::new();
    html::push_html(&mut out, events.into_iter());
    out
}

/// A whole page. `base` is the folder relative links and images start from.
pub fn page(title: &str, markdown: &str, base: &str) -> String {
    page_with(title, markdown, base, &|_| None)
}

/// A whole page, with what's been built for its blocks of TikZ.
pub fn page_with(title: &str, markdown: &str, base: &str, built: &Built) -> String {
    format!(
        "<!doctype html>\n<html><head><meta charset=\"utf-8\">\
         <meta name=\"viewport\" content=\"width=device-width\">\
         <title>{}</title><base href=\"file://{}/\"><style>{STYLE}</style></head>\n<body>\n{}</body></html>\n",
        escape(title),
        escape(base),
        body_with(markdown, built)
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_reviewers_note_stays_out_of_an_export() {
        let html = body("Ship it {>>check with infra<<} now.\n");
        assert!(!html.contains("check with infra"), "{html}");
        assert!(html.contains("Ship it now."), "{html}");
    }

    #[test]
    fn inline_code_keeps_its_equals_signs() {
        let html = body("Check `hits == misses` and ==this==.\n");
        assert!(html.contains("hits == misses"), "{html}");
        assert_eq!(html.matches("<mark>").count(), 1, "{html}");
    }

    #[test]
    fn front_matter_is_a_title_not_a_heading_of_keys() {
        let html = body("---\ntitle: The Plan\nauthor: Ada\n---\n\nWords.\n");
        assert!(html.contains("<h1 class=\"title\">The Plan</h1>"), "{html}");
        assert!(html.contains("Ada"), "{html}");
        assert!(!html.contains("title:"), "{html}");
    }

    #[test]
    fn a_page_carries_tables_tasks_and_math() {
        let text = "# Title\n\n| a | b |\n|---|---|\n| 1 | 2 |\n\n- [x] done\n\nInline $x^2$ here.\n\n$$\\frac{1}{2}$$\n";
        let html = body(text);
        assert!(html.contains("<h1>Title</h1>"));
        assert!(html.contains("<table>"));
        assert!(html.contains("checkbox"));
        assert_eq!(html.matches("<svg").count(), 2, "{html}");
        assert!(html.contains("class=\"math\""));
    }

    #[test]
    fn diagrams_and_sized_images_reach_the_web_page() {
        let text = "```mermaid\nflowchart LR\n  A --> B\n```\n\n![Plot](a.png){width=40%}\n";
        let html = body(text);
        assert!(html.contains("class=\"diagram\""), "{html}");
        assert!(html.contains("<svg"), "{html}");
        assert!(!html.contains("flowchart"), "{html}");
        assert!(html.contains("style=\"width:40%\""), "{html}");
    }

    #[test]
    fn a_callout_keeps_its_own_title() {
        let html = body("> [!tip]- Keep it short\n> Say less.\n\n> [!WARNING]\n> Careful.\n");
        assert!(html.contains("markdown-alert-tip"), "{html}");
        assert!(
            html.contains("<p class=\"callout-title\">Keep it short</p>"),
            "{html}"
        );
        assert!(html.contains("Say less."), "{html}");
        assert!(!html.contains("[!tip]"), "{html}");
        assert!(html.contains("markdown-alert-warning"), "{html}");
        assert_eq!(
            callout("[!bug] Crash"),
            Some(("CAUTION", Some("Crash".to_string())))
        );
        assert_eq!(callout("[!NOTE]"), Some(("NOTE", None)));
        assert_eq!(callout("[!nonsense]"), None);
    }

    #[test]
    fn writing_marks_reach_the_web_page() {
        let html = body(
            "==key== H~2~O x^2^ {++new++}{--old--}[^a]\n\n[^a]: Note.\n\n> [!WARNING]\n> Careful.\n",
        );
        for want in [
            "<mark>key</mark>",
            "<sub>2</sub>",
            "<sup>2</sup>",
            "<ins>new</ins>",
            "<del>old</del>",
            "markdown-alert-warning",
            "Note.",
        ] {
            assert!(html.contains(want), "{want}: {html}");
        }
    }

    #[test]
    fn tikz_reaches_the_web_page_once_it_has_been_built() {
        let text = "```tikz\n\\draw (0,0);\n```\n";
        assert!(
            body(text).contains("\\draw"),
            "unbuilt, it stays as its source"
        );
        let html = body_with(text, &|tex| {
            assert!(tex.contains("\\begin{tikzpicture}"));
            Some("<img src=\"drawn\">".to_string())
        });
        assert!(html.contains("<img src=\"drawn\">"), "{html}");
        assert!(!html.contains("\\draw"), "{html}");
    }

    #[test]
    fn a_broken_diagram_stays_as_its_source() {
        let html = body("```mermaid\nnot a diagram (\n```\n");
        assert!(html.contains("not a diagram"), "{html}");
    }

    #[test]
    fn a_broken_formula_stays_as_its_source() {
        assert!(body("A $\\frac{$ b").contains("\\frac{"));
    }

    #[test]
    fn a_page_needs_no_network() {
        let html = page("Doc <1>", "text", "/tmp/here");
        assert!(html.contains("<title>Doc &lt;1&gt;</title>"));
        assert!(html.contains("file:///tmp/here/"));
        assert!(!html.contains("<script"));
        assert!(!html.contains("http"));
    }
}