anydoc 0.2.3

Convert documents (doc, docx, odt, rtf, epub, pdf, presentations, spreadsheets, csv) to GitHub-Flavored Markdown
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
//! Inline run normalization and rendering.

use crate::model::{ImageSource, Inline, LinkTarget, Style, checkbox_text, inlines_are_empty};
use crate::render::markdown::Ctx;
use crate::render::markdown::escape::{
    Delims, EscapeOpts, InlineContext, backtick_fence, escape_cell_code_span, escape_text,
    escape_url_as_text, format_url,
};
use std::borrow::Cow;
use std::fmt::Write as _;

pub(crate) enum Norm<'a> {
    Text { text: Cow<'a, str>, style: Style },
    Link { content: &'a [Inline], target: &'a LinkTarget },
    Image { alt: &'a str, source: &'a ImageSource },
    Anchor(&'a str),
    NoteRef(&'a str),
    LineBreak,
    Math(&'a str),
    Checkbox(bool),
}

/// Single-pass normalization: drops empty runs, strips styling from
/// whitespace-only runs, merges adjacent same-style runs, and re-joins styled
/// runs split only by whitespace (`**a** **b**` -> `**a b**`). Runs borrow
/// from the source inlines; text is owned only where runs actually merge.
/// Untargeted anchors drop out here: they render as nothing, so leaving them
/// in would part runs that belong together.
pub(crate) fn normalize<'a>(inlines: &'a [Inline], rc: &Ctx) -> Vec<Norm<'a>> {
    let mut out: Vec<Norm<'a>> = Vec::new();
    for inline in inlines {
        match inline {
            Inline::Text { text, style } => {
                if text.is_empty() {
                    continue;
                }
                let style = if text.trim().is_empty() { Style::PLAIN } else { *style };
                if let Some(Norm::Text { text: prev, style: prev_style }) = out.last_mut()
                    && *prev_style == style
                {
                    prev.to_mut().push_str(text);
                    continue;
                }
                // Bridge: [styled S][ws plain][incoming styled S] merges into one run.
                if style != Style::PLAIN
                    && !style.code
                    && out.len() >= 2
                    && matches!(&out[out.len() - 1],
                        Norm::Text { text: ws, style: s } if *s == Style::PLAIN && ws.trim().is_empty())
                    && matches!(&out[out.len() - 2],
                        Norm::Text { style: s, .. } if *s == style)
                {
                    let Some(Norm::Text { text: ws, .. }) = out.pop() else { unreachable!() };
                    let Some(Norm::Text { text: prev, .. }) = out.last_mut() else {
                        unreachable!()
                    };
                    let prev = prev.to_mut();
                    prev.push_str(&ws);
                    prev.push_str(text);
                    continue;
                }
                out.push(Norm::Text { text: Cow::Borrowed(text.as_str()), style });
            }
            Inline::Link { content, target } => {
                if target.is_empty() {
                    // No usable destination: keep the content as plain inlines.
                    if !inlines_are_empty(content) {
                        out.extend(normalize(content, rc));
                    }
                    continue;
                }
                out.push(Norm::Link { content, target });
            }
            Inline::Image { alt, source } => out.push(Norm::Image { alt, source }),
            Inline::Anchor(id) if rc.anchors.html_id(id).is_none() => continue,
            Inline::Anchor(id) => out.push(Norm::Anchor(id)),
            Inline::NoteRef(id) => out.push(Norm::NoteRef(id)),
            Inline::LineBreak => out.push(Norm::LineBreak),
            Inline::Math(tex) if tex.trim().is_empty() => continue,
            Inline::Math(tex) => out.push(Norm::Math(tex.trim())),
            Inline::Checkbox(checked) => out.push(Norm::Checkbox(*checked)),
        }
    }
    out
}

pub(crate) fn render_inlines(inlines: &[Inline], ctx: InlineContext, rc: &Ctx) -> String {
    render_inlines_mode(inlines, ctx, false, rc)
}

fn render_inlines_mode(inlines: &[Inline], ctx: InlineContext, in_label: bool, rc: &Ctx) -> String {
    let runs = normalize(inlines, rc);
    let suffix = delims_ahead(&runs, rc);
    let mut out = String::new();
    for (idx, run) in runs.iter().enumerate() {
        match run {
            Norm::Text { text, style } => {
                let next = runs.get(idx + 1);
                let next_active = matches!(
                    next,
                    Some(Norm::Link { .. } | Norm::Image { .. } | Norm::NoteRef(_) | Norm::Math(_))
                ) || matches!(
                    next,
                    Some(Norm::Text { style, .. }) if *style != Style::PLAIN
                );
                // A hard break renders as `\`, an anchor as `<a ...>`: not
                // markup, but a nonspace character a run-final delimiter can
                // be left-flanking against.
                let next_nonspace = matches!(next, Some(Norm::Anchor(_) | Norm::Checkbox(_)))
                    || (matches!(next, Some(Norm::LineBreak)) && ctx != InlineContext::Heading);
                let opts = EscapeOpts {
                    trailing_active: next_active,
                    trailing_nonspace: next_nonspace,
                    trailing_delims: suffix[idx + 1],
                    in_label,
                    ..Default::default()
                };
                render_text_run(text, *style, ctx, opts, &mut out)
            }
            Norm::NoteRef(id) => {
                if let Some(num) = rc.nums.get(*id) {
                    let _ = write!(out, "[^{num}]");
                }
            }
            Norm::Link { content, target } => render_link(content, target, ctx, rc, &mut out),
            Norm::Image { alt, source } => render_image(alt, source, ctx, in_label, &mut out),
            Norm::Anchor(id) => {
                if let Some(html_id) = rc.anchors.html_id(id) {
                    let _ = write!(out, "<a id=\"{html_id}\"></a>");
                }
            }
            Norm::LineBreak => match ctx {
                InlineContext::Block => out.push_str("\\\n"),
                InlineContext::Heading => out.push(' '),
                InlineContext::TableCell => out.push('\n'),
            },
            Norm::Math(tex) => push_math_span(tex, ctx, &mut out),
            Norm::Checkbox(checked) => {
                out.push_str(checkbox_text(*checked));
                // The token stands apart from a caption that follows it.
                if matches!(runs.get(idx + 1), Some(run) if !starts_with_space(run)) {
                    out.push(' ');
                }
            }
        }
    }
    out
}

fn render_link(
    content: &[Inline],
    target: &LinkTarget,
    ctx: InlineContext,
    rc: &Ctx,
    out: &mut String,
) {
    let label = render_inlines_mode(content, ctx, true, rc);
    let url = match target {
        LinkTarget::External(url) | LinkTarget::Relative(url) => url.clone(),
        LinkTarget::Anchor(id) => match rc.anchors.fragment(id) {
            Some(fragment) => format!("#{fragment}"),
            None => {
                // Target exists nowhere in the document: degrade to plain text.
                log::debug!("unresolved internal link target: {id}");
                out.push_str(&render_inlines_mode(content, ctx, false, rc));
                return;
            }
        },
    };
    // Emptiness is tested on the trimmed label, but the rendered label keeps
    // its source-significant edge spaces.
    if label.trim().is_empty() {
        if matches!(target, LinkTarget::Anchor(_)) {
            return;
        }
        let _ = write!(out, "[{}]({})", escape_url_as_text(&url, ctx), format_url(&url));
    } else {
        let _ = write!(out, "[{}]({})", label, format_url(&url));
    }
}

fn render_image(
    alt: &str,
    source: &ImageSource,
    ctx: InlineContext,
    in_label: bool,
    out: &mut String,
) {
    match source {
        ImageSource::External(url) => {
            let alt =
                escape_text(alt.trim(), ctx, EscapeOpts { in_label: true, ..Default::default() });
            let _ = write!(out, "![{}]({})", alt, format_url(url));
        }
        // Embedded assets render as their alt text: Markdown cannot embed
        // bytes, and the bytes stay available in `Document::assets`. A
        // source-less image has only its alt text to offer.
        ImageSource::Asset(_) | ImageSource::Unavailable => {
            if !alt.trim().is_empty() {
                out.push_str(&escape_text(
                    alt.trim(),
                    ctx,
                    EscapeOpts { in_label, ..Default::default() },
                ));
            }
        }
    }
}

/// Pairable delimiters the remaining runs will emit into the current rendered
/// line: closer-capable literals in plain text, plus the markup that styled runs,
/// code spans, links and images produce. A delimiter in an earlier run can
/// pair with any of them across the run seam, hard breaks included.
/// The delimiters each suffix of `runs` emits, indexed by where the suffix
/// starts, so one reverse pass answers every run's lookahead.
fn delims_ahead(runs: &[Norm], rc: &Ctx) -> Vec<Delims> {
    let mut suffix = vec![Delims::default(); runs.len() + 1];
    for idx in (0..runs.len()).rev() {
        let mut delims = suffix[idx + 1];
        delims.union(delims_of(&runs[idx], rc));
        suffix[idx] = delims;
    }
    suffix
}

/// What one run contributes to a later run's pairing partners.
fn delims_of(run: &Norm, rc: &Ctx) -> Delims {
    let mut delims = Delims::default();
    match run {
        Norm::Text { style, .. } if style.code => delims.insert('`'),
        Norm::Text { text, style } if *style == Style::PLAIN => delims.insert_closers(text),
        Norm::Text { text, style } => {
            // Emphasis content is escaped, which neutralizes everything
            // but backticks: code spans ignore backslash escapes, so an
            // emitted `\`` still closes a span an earlier raw backtick
            // opens. `]` is the one character escaping leaves raw.
            if style.bold || style.italic {
                delims.insert('*');
            }
            if style.strike {
                delims.insert('~');
            }
            if text.contains('`') {
                delims.insert('`');
            }
            if text.contains(']') {
                delims.insert(']');
            }
            delims.insert_closers(&text.replace(|c: char| c != '$' && !c.is_whitespace(), "x"));
        }
        Norm::Link { content, target } => match target {
            // An unresolved target degrades to its rendered content
            // (see render_link), which emits like any sibling runs.
            LinkTarget::Anchor(id) if rc.anchors.fragment(id).is_none() => {
                for run in &normalize(content, rc) {
                    delims.union(delims_of(run, rc));
                }
            }
            // Emphasis cannot cross a link boundary, but a code span
            // can: a backtick in the label or destination pairs with
            // one outside.
            _ => {
                if emits_backtick(content) || target_has_backtick(target) {
                    delims.insert('`');
                }
            }
        },
        Norm::Image { alt, source } => match source {
            ImageSource::External(_) if alt.contains('`') => delims.insert('`'),
            ImageSource::External(_) => {}
            // Sourceless images degrade to their alt as plain text.
            ImageSource::Asset(_) | ImageSource::Unavailable => delims.insert_closers(alt),
        },
        Norm::NoteRef(_)
        | Norm::Anchor(_)
        | Norm::LineBreak
        | Norm::Math(_)
        | Norm::Checkbox(_) => {}
    }
    delims
}

fn starts_with_space(run: &Norm) -> bool {
    match run {
        Norm::Text { text, .. } => text.starts_with(char::is_whitespace),
        Norm::LineBreak => true,
        _ => false,
    }
}

fn target_has_backtick(target: &LinkTarget) -> bool {
    match target {
        LinkTarget::External(url) | LinkTarget::Relative(url) => url.contains('`'),
        LinkTarget::Anchor(_) => false,
    }
}

/// True when rendering `inlines` inside a link label emits a backtick an
/// earlier raw one can pair with: any backtick in text counts even where the
/// label escapes it (code spans ignore backslash escapes), and a code run
/// emits fences unless it is whitespace-only and loses its styling.
fn emits_backtick(inlines: &[Inline]) -> bool {
    inlines.iter().any(|inline| match inline {
        Inline::Text { text, style } => {
            text.contains('`') || (style.code && !text.trim().is_empty())
        }
        Inline::Link { content, target } => emits_backtick(content) || target_has_backtick(target),
        Inline::Image { alt, .. } => alt.contains('`'),
        _ => false,
    })
}

/// Emit a styled run, moving edge whitespace outside the delimiters.
/// `opts` carries the trailing context; `at_line_start` and `styled` are
/// filled in here.
fn render_text_run(
    text: &str,
    style: Style,
    ctx: InlineContext,
    opts: EscapeOpts,
    out: &mut String,
) {
    if style == Style::PLAIN {
        let at_line_start = out.is_empty() || out.ends_with('\n');
        out.push_str(&escape_text(text, ctx, EscapeOpts { at_line_start, ..opts }));
        return;
    }
    let core_start = text.len() - text.trim_start().len();
    let core_end = text.trim_end().len();
    let (lead, core, trail) = (&text[..core_start], &text[core_start..core_end], &text[core_end..]);
    if !lead.is_empty() {
        out.push_str(lead);
    }
    if !core.is_empty() {
        if style.code {
            push_code_span(core, ctx, out);
        } else {
            let mut open = String::new();
            if style.strike {
                open.push_str("~~");
            }
            if style.bold {
                open.push_str("**");
            }
            if style.italic {
                open.push('*');
            }
            let close: String = open.chars().rev().collect();
            out.push_str(&open);
            out.push_str(&escape_text(
                core,
                ctx,
                EscapeOpts { styled: true, in_label: opts.in_label, ..Default::default() },
            ));
            out.push_str(&close);
        }
    }
    if !trail.is_empty() {
        out.push_str(trail);
    }
}

/// GFM inline math: `$` hugging both ends of the source. A line break
/// inside it would end the paragraph's math span, and a bare `$` (never
/// valid inside math) would close it early.
pub(crate) fn push_math_span(tex: &str, ctx: InlineContext, out: &mut String) {
    let mut source = String::with_capacity(tex.len());
    let mut backslashes = 0;
    for c in tex.trim().chars() {
        match c {
            '\n' => source.push(' '),
            '$' if backslashes % 2 == 0 => source.push_str("\\$"),
            c => source.push(c),
        }
        backslashes = if c == '\\' { backslashes + 1 } else { 0 };
    }
    // A row is split into cells before the math span is parsed, so a bare
    // pipe is syntax here; GFM strips the escaping backslash before the
    // math is read, so an already escaped pipe stays as it is.
    let source = match ctx {
        InlineContext::TableCell => {
            let mut escaped = String::with_capacity(source.len());
            let mut backslashes = 0;
            for c in source.chars() {
                if c == '|' && backslashes % 2 == 0 {
                    escaped.push('\\');
                }
                escaped.push(c);
                backslashes = if c == '\\' { backslashes + 1 } else { 0 };
            }
            escaped
        }
        _ => source,
    };
    let _ = write!(out, "${source}$");
}

pub(crate) fn push_code_span(text: &str, ctx: InlineContext, out: &mut String) {
    let text = text.replace('\n', " ");
    let fence = backtick_fence(&text, 1);
    let pad = if text.starts_with('`') || text.ends_with('`') { " " } else { "" };
    // A row is split into cells before any code span is parsed, so a pipe is
    // syntax here even though everything else between the fences is literal.
    let text = match ctx {
        InlineContext::TableCell => escape_cell_code_span(&text),
        _ => text,
    };
    let _ = write!(out, "{fence}{pad}{text}{pad}{fence}");
}