inker 0.2.0

Modular engine/renderer controller — selects and orchestrates content engines (genet HTML lanes, nematic smolweb, scrying/graft/weld surface engines).
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
// Copyright 2026 Mark Alan Boykin
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// SPDX-License-Identifier: MPL-2.0

//! Round-trip rendering of [`EngineDocument`] back into native CommonMark
//! and gemtext.
//!
//! Lets clips and notes export back into the formats their hosts expect.
//! Spec-faithful: gemtext output flattens inline styling (gemtext has none)
//! and surfaces inline links as separate `=> url label` lines after the
//! paragraph, matching gemtext's link-line model.

use super::{
    Block, DocumentTrustState, EngineDocument, InlineSpan, TableAlignment, inline_text,
    menu_fallback_blocks,
};

impl EngineDocument {
    /// Render the document as CommonMark.
    pub fn to_markdown(&self) -> String {
        let mut out = String::new();
        for block in &self.blocks {
            block.write_markdown(&mut out, 0);
        }
        out
    }

    /// Render the document as gemtext (`text/gemini`).
    ///
    /// Spec-faithful: emphasis / strong / inline code styling is flattened
    /// to plain text since gemtext has no inline styling. Inline `Link`
    /// spans inside paragraphs are emitted as separate `=> url label` lines
    /// after the paragraph, matching gemtext's link-line model.
    pub fn to_gemini(&self) -> String {
        let mut out = String::new();
        for block in &self.blocks {
            block.write_gemini(&mut out);
        }
        out
    }

    /// Render the document as a knot file (frontmatter + body).
    ///
    /// Frontmatter is written when the document has any of: a title,
    /// `provenance.canonical_uri` / `fetched_at` / `source_label`, or a
    /// non-`Unknown` trust state. The body is the same shape as
    /// `to_markdown()` for structural blocks, with semantic variants
    /// (`FeedHeader`, `FeedEntry`, `MetadataRow`, `Badge`) rendered as
    /// fenced code blocks with their protocol language tag — so they
    /// round-trip through `nematic::KnotEngine`'s polyglot fence
    /// expansion without losing semantic intent.
    ///
    /// Round-trip: `parse → to_knot → parse → equivalent document` for
    /// the document-level metadata + every structural and semantic block.
    /// `note_kind` and `tags` MetadataRow blocks are NOT re-extracted
    /// to frontmatter on re-render — they stay as MetadataRow blocks in
    /// the body, preserving their content but shifting their storage
    /// location. (Asymmetry by design; the reverse-extraction would be
    /// fragile against user-authored MetadataRows that happen to use
    /// `kind` / `tags` labels.)
    pub fn to_knot(&self) -> String {
        let mut out = String::new();
        if self.has_frontmatter_content() {
            self.write_knot_frontmatter(&mut out);
        }
        self.write_knot_body(&mut out);
        out
    }

    /// Append the knot body (blocks only — no frontmatter) to `out`.
    ///
    /// Companion to [`Self::to_knot`] for callers that emit their own
    /// frontmatter and just want the rendered block stream. Used by
    /// `nematic::knot::build_clip_knot` so the clip-aware frontmatter
    /// (which carries `note_kind` and other knot-format extensions
    /// outside [`EngineDocument`]'s shape) isn't doubled by the
    /// document-level frontmatter `to_knot` would otherwise emit.
    pub fn write_knot_body(&self, out: &mut String) {
        for block in &self.blocks {
            block.write_knot(out);
        }
    }

    /// True when [`Self::to_knot`] should emit a frontmatter block.
    fn has_frontmatter_content(&self) -> bool {
        self.title.is_some()
            || self.provenance.canonical_uri.is_some()
            || self.provenance.fetched_at.is_some()
            || self.provenance.source_label.is_some()
            || !matches!(self.trust, DocumentTrustState::Unknown)
    }

    fn write_knot_frontmatter(&self, out: &mut String) {
        out.push_str("---\n");
        if let Some(title) = &self.title {
            out.push_str(&format!("title: {title}\n"));
        }
        if let Some(source) = &self.provenance.canonical_uri {
            out.push_str(&format!("source: {source}\n"));
        }
        if let Some(captured) = &self.provenance.fetched_at {
            out.push_str(&format!("captured: {captured}\n"));
        }
        if let Some(label) = &self.provenance.source_label {
            out.push_str(&format!("source_label: {label}\n"));
        }
        let trust_str = match self.trust {
            DocumentTrustState::Trusted => Some("trusted"),
            DocumentTrustState::Tofu => Some("tofu"),
            DocumentTrustState::Insecure => Some("insecure"),
            DocumentTrustState::Broken => Some("broken"),
            DocumentTrustState::Unknown => None,
        };
        if let Some(s) = trust_str {
            out.push_str(&format!("trust: {s}\n"));
        }
        out.push_str("---\n\n");
    }
}

/// Each table row (header first, if any) as a plain-text line, cells joined by
/// " | ". For exporters whose target format has no table model (gemtext,
/// gophermap, plain text); callers wrap or prefix the lines as fits.
pub(super) fn table_lines(
    header: &[Vec<InlineSpan>],
    rows: &[Vec<Vec<InlineSpan>>],
) -> Vec<String> {
    let row_line = |cells: &[Vec<InlineSpan>]| {
        cells
            .iter()
            .map(|c| inline_text(c))
            .collect::<Vec<_>>()
            .join(" | ")
    };
    let mut lines = Vec::new();
    if !header.is_empty() {
        lines.push(row_line(header));
    }
    lines.extend(rows.iter().map(|r| row_line(r)));
    lines
}

/// A GitHub-style pipe table: header row, an alignment separator, then body rows.
/// An empty header still emits a (blank) header row so the result stays valid
/// markdown; cells render their inline markdown.
fn write_markdown_table(
    alignments: &[TableAlignment],
    header: &[Vec<InlineSpan>],
    rows: &[Vec<Vec<InlineSpan>>],
    out: &mut String,
    pad: &str,
) {
    let cols = header
        .len()
        .max(rows.iter().map(Vec::len).max().unwrap_or(0));
    if cols == 0 {
        return;
    }
    let write_row = |cells: &[Vec<InlineSpan>], out: &mut String| {
        out.push_str(pad);
        out.push('|');
        for i in 0..cols {
            out.push(' ');
            if let Some(cell) = cells.get(i) {
                write_inline_markdown(cell, out);
            }
            out.push_str(" |");
        }
        out.push('\n');
    };
    write_row(header, out);
    out.push_str(pad);
    out.push('|');
    for i in 0..cols {
        out.push_str(match alignments.get(i).copied().unwrap_or_default() {
            TableAlignment::None => " --- |",
            TableAlignment::Left => " :--- |",
            TableAlignment::Center => " :---: |",
            TableAlignment::Right => " ---: |",
        });
    }
    out.push('\n');
    for row in rows {
        write_row(row, out);
    }
    out.push('\n');
}

mod blocks;

impl Block {
    /// Knot-format renderer. Reuses `write_markdown` for structural blocks;
    /// emits fenced code blocks with protocol language tags for the four
    /// semantic block variants so they round-trip through
    /// `nematic::KnotEngine`'s fence expansion.
    fn write_knot(&self, out: &mut String) {
        match self {
            Self::Presented {
                presentation,
                block,
            } => block.write_markdown(out, presentation.indent_level as usize),
            Self::FeedHeader {
                title,
                subtitle,
                summary,
                source_url,
            } => {
                out.push_str("```feed-header\n");
                out.push_str(&format!("title: {title}\n"));
                if let Some(s) = subtitle {
                    out.push_str(&format!("subtitle: {s}\n"));
                }
                if let Some(s) = summary {
                    out.push_str(&format!("summary: {s}\n"));
                }
                if let Some(url) = source_url {
                    out.push_str(&format!("source: {url}\n"));
                }
                out.push_str("```\n\n");
            },
            Self::FeedEntry {
                title,
                date,
                summary,
                article_url,
                source_url,
                ..
            } => {
                out.push_str("```feed-entry\n");
                out.push_str(&format!("title: {title}\n"));
                if let Some(d) = date {
                    out.push_str(&format!("date: {d}\n"));
                }
                if let Some(s) = summary {
                    out.push_str(&format!("summary: {s}\n"));
                }
                if let Some(url) = article_url {
                    out.push_str(&format!("url: {url}\n"));
                }
                if let Some(url) = source_url {
                    out.push_str(&format!("source: {url}\n"));
                }
                out.push_str("```\n\n");
            },
            Self::MetadataRow { label, value } => {
                out.push_str("```metadata-row\n");
                out.push_str(&format!("{label}: {value}\n"));
                out.push_str("```\n\n");
            },
            Self::Badge { text } => {
                out.push_str("```badge\n");
                out.push_str(text);
                if !text.ends_with('\n') {
                    out.push('\n');
                }
                out.push_str("```\n\n");
            },
            // Recurse into containers so semantic blocks nested inside
            // quotes / list items also serialise as fences.
            Self::Quote { blocks } => {
                let mut inner = String::new();
                for block in blocks {
                    block.write_knot(&mut inner);
                }
                for line in inner.lines() {
                    out.push_str("> ");
                    out.push_str(line);
                    out.push('\n');
                }
                out.push('\n');
            },
            Self::List { ordered, items } => {
                for (i, item) in items.iter().enumerate() {
                    if *ordered {
                        out.push_str(&format!("{}. ", i + 1));
                    } else {
                        out.push_str("- ");
                    }
                    let mut inner = String::new();
                    for block in item {
                        block.write_knot(&mut inner);
                    }
                    out.push_str(inner.trim_end());
                    out.push('\n');
                }
                out.push('\n');
            },
            // For everything else, knot output and markdown output match.
            other => other.write_markdown(out, 0),
        }
    }
}

fn write_inline_markdown(spans: &[InlineSpan], out: &mut String) {
    for span in spans {
        match span {
            // An in-page link exports as its label (plan decision 9).
            InlineSpan::Presented { spans, .. } | InlineSpan::InPage { spans, .. } => {
                write_inline_markdown(spans, out)
            },
            InlineSpan::Text(t) => out.push_str(t),
            InlineSpan::Code(t) => {
                out.push('`');
                out.push_str(t);
                out.push('`');
            },
            InlineSpan::Emphasis(s) => {
                out.push('*');
                write_inline_markdown(s, out);
                out.push('*');
            },
            InlineSpan::Strong(s) => {
                out.push_str("**");
                write_inline_markdown(s, out);
                out.push_str("**");
            },
            InlineSpan::Link { url, spans, .. } => {
                out.push('[');
                write_inline_markdown(spans, out);
                out.push_str("](");
                out.push_str(url);
                out.push(')');
            },
            InlineSpan::Submit { target, spans } => {
                write_inline_markdown(spans, out);
                out.push_str(" [submit: ");
                out.push_str(target);
                out.push(']');
            },
            InlineSpan::SoftBreak => out.push('\n'),
            InlineSpan::LineBreak => out.push_str("  \n"),
        }
    }
}

/// Whether a span list is links and whitespace only (with at least one
/// link) — the "this paragraph IS a link line" case shared by the gemtext
/// and gophermap writers.
fn is_link_only(spans: &[InlineSpan]) -> bool {
    let mut saw_link = false;
    for span in spans {
        if !is_link_only_span(span, &mut saw_link) {
            return false;
        }
    }
    saw_link
}

fn is_link_only_span(span: &InlineSpan, saw_link: &mut bool) -> bool {
    match span {
        InlineSpan::Link { .. } => {
            *saw_link = true;
            true
        },
        InlineSpan::Text(text) => text.trim().is_empty(),
        InlineSpan::SoftBreak | InlineSpan::LineBreak => true,
        InlineSpan::Presented { spans, .. }
        | InlineSpan::Emphasis(spans)
        | InlineSpan::Strong(spans) => spans.iter().all(|span| is_link_only_span(span, saw_link)),
        _ => false,
    }
}

fn is_submit_only(spans: &[InlineSpan]) -> bool {
    let mut saw_submit = false;
    for span in spans {
        if !is_submit_only_span(span, &mut saw_submit) {
            return false;
        }
    }
    saw_submit
}

fn is_submit_only_span(span: &InlineSpan, saw_submit: &mut bool) -> bool {
    match span {
        InlineSpan::Submit { .. } => {
            *saw_submit = true;
            true
        },
        InlineSpan::Text(text) => text.trim().is_empty(),
        InlineSpan::SoftBreak | InlineSpan::LineBreak => true,
        InlineSpan::Presented { spans, .. }
        | InlineSpan::Emphasis(spans)
        | InlineSpan::Strong(spans) => spans
            .iter()
            .all(|span| is_submit_only_span(span, saw_submit)),
        _ => false,
    }
}

fn collect_link_targets(span: &InlineSpan, out: &mut Vec<(String, String)>) {
    match span {
        InlineSpan::Link { url, spans, .. } => {
            out.push((url.clone(), inline_text(spans)));
            for inner in spans {
                collect_link_targets(inner, out);
            }
        },
        InlineSpan::Presented { spans, .. }
        | InlineSpan::Emphasis(spans)
        | InlineSpan::Strong(spans)
        | InlineSpan::Submit { spans, .. } => {
            for inner in spans {
                collect_link_targets(inner, out);
            }
        },
        _ => {},
    }
}

fn collect_submit_targets(span: &InlineSpan, out: &mut Vec<(String, String)>) {
    match span {
        InlineSpan::Submit { target, spans } => {
            out.push((target.clone(), inline_text(spans)));
        },
        InlineSpan::Presented { spans, .. }
        | InlineSpan::Emphasis(spans)
        | InlineSpan::Strong(spans)
        | InlineSpan::Link { spans, .. } => {
            for inner in spans {
                collect_submit_targets(inner, out);
            }
        },
        _ => {},
    }
}

// Gophermap + plain-text exporters live in `render/export.rs`, the HTML
// exporter in `render/html.rs` (this file is at the 600-LOC ceiling); tests
// live in `render/tests.rs`.
mod export;
mod html;
pub use export::GophermapContext;

// Tests live in `render/tests.rs` to keep this file under the 600-LOC ceiling.
#[cfg(test)]
mod tests;