Skip to main content

inker/document/
render.rs

1// Copyright 2026 Mark AB (markik)
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! Round-trip rendering of [`EngineDocument`] back into native CommonMark
5//! and gemtext.
6//!
7//! Lets clips and notes export back into the formats their hosts expect.
8//! Spec-faithful: gemtext output flattens inline styling (gemtext has none)
9//! and surfaces inline links as separate `=> url label` lines after the
10//! paragraph, matching gemtext's link-line model.
11
12use super::{Block, DocumentTrustState, EngineDocument, InlineSpan, TableAlignment, inline_text};
13
14impl EngineDocument {
15    /// Render the document as CommonMark.
16    pub fn to_markdown(&self) -> String {
17        let mut out = String::new();
18        for block in &self.blocks {
19            block.write_markdown(&mut out, 0);
20        }
21        out
22    }
23
24    /// Render the document as gemtext (`text/gemini`).
25    ///
26    /// Spec-faithful: emphasis / strong / inline code styling is flattened
27    /// to plain text since gemtext has no inline styling. Inline `Link`
28    /// spans inside paragraphs are emitted as separate `=> url label` lines
29    /// after the paragraph, matching gemtext's link-line model.
30    pub fn to_gemini(&self) -> String {
31        let mut out = String::new();
32        for block in &self.blocks {
33            block.write_gemini(&mut out);
34        }
35        out
36    }
37
38    /// Render the document as a knot file (frontmatter + body).
39    ///
40    /// Frontmatter is written when the document has any of: a title,
41    /// `provenance.canonical_uri` / `fetched_at` / `source_label`, or a
42    /// non-`Unknown` trust state. The body is the same shape as
43    /// `to_markdown()` for structural blocks, with semantic variants
44    /// (`FeedHeader`, `FeedEntry`, `MetadataRow`, `Badge`) rendered as
45    /// fenced code blocks with their protocol language tag — so they
46    /// round-trip through `nematic::KnotEngine`'s polyglot fence
47    /// expansion without losing semantic intent.
48    ///
49    /// Round-trip: `parse → to_knot → parse → equivalent document` for
50    /// the document-level metadata + every structural and semantic block.
51    /// `note_kind` and `tags` MetadataRow blocks are NOT re-extracted
52    /// to frontmatter on re-render — they stay as MetadataRow blocks in
53    /// the body, preserving their content but shifting their storage
54    /// location. (Asymmetry by design; the reverse-extraction would be
55    /// fragile against user-authored MetadataRows that happen to use
56    /// `kind` / `tags` labels.)
57    pub fn to_knot(&self) -> String {
58        let mut out = String::new();
59        if self.has_frontmatter_content() {
60            self.write_knot_frontmatter(&mut out);
61        }
62        self.write_knot_body(&mut out);
63        out
64    }
65
66    /// Append the knot body (blocks only — no frontmatter) to `out`.
67    ///
68    /// Companion to [`Self::to_knot`] for callers that emit their own
69    /// frontmatter and just want the rendered block stream. Used by
70    /// `nematic::knot::build_clip_knot` so the clip-aware frontmatter
71    /// (which carries `note_kind` and other knot-format extensions
72    /// outside [`EngineDocument`]'s shape) isn't doubled by the
73    /// document-level frontmatter `to_knot` would otherwise emit.
74    pub fn write_knot_body(&self, out: &mut String) {
75        for block in &self.blocks {
76            block.write_knot(out);
77        }
78    }
79
80    /// True when [`Self::to_knot`] should emit a frontmatter block.
81    fn has_frontmatter_content(&self) -> bool {
82        self.title.is_some()
83            || self.provenance.canonical_uri.is_some()
84            || self.provenance.fetched_at.is_some()
85            || self.provenance.source_label.is_some()
86            || !matches!(self.trust, DocumentTrustState::Unknown)
87    }
88
89    fn write_knot_frontmatter(&self, out: &mut String) {
90        out.push_str("---\n");
91        if let Some(title) = &self.title {
92            out.push_str(&format!("title: {title}\n"));
93        }
94        if let Some(source) = &self.provenance.canonical_uri {
95            out.push_str(&format!("source: {source}\n"));
96        }
97        if let Some(captured) = &self.provenance.fetched_at {
98            out.push_str(&format!("captured: {captured}\n"));
99        }
100        if let Some(label) = &self.provenance.source_label {
101            out.push_str(&format!("source_label: {label}\n"));
102        }
103        let trust_str = match self.trust {
104            DocumentTrustState::Trusted => Some("trusted"),
105            DocumentTrustState::Tofu => Some("tofu"),
106            DocumentTrustState::Insecure => Some("insecure"),
107            DocumentTrustState::Broken => Some("broken"),
108            DocumentTrustState::Unknown => None,
109        };
110        if let Some(s) = trust_str {
111            out.push_str(&format!("trust: {s}\n"));
112        }
113        out.push_str("---\n\n");
114    }
115}
116
117/// Each table row (header first, if any) as a plain-text line, cells joined by
118/// " | ". For exporters whose target format has no table model (gemtext,
119/// gophermap, plain text); callers wrap or prefix the lines as fits.
120pub(super) fn table_lines(
121    header: &[Vec<InlineSpan>],
122    rows: &[Vec<Vec<InlineSpan>>],
123) -> Vec<String> {
124    let row_line = |cells: &[Vec<InlineSpan>]| {
125        cells
126            .iter()
127            .map(|c| inline_text(c))
128            .collect::<Vec<_>>()
129            .join(" | ")
130    };
131    let mut lines = Vec::new();
132    if !header.is_empty() {
133        lines.push(row_line(header));
134    }
135    lines.extend(rows.iter().map(|r| row_line(r)));
136    lines
137}
138
139/// A GitHub-style pipe table: header row, an alignment separator, then body rows.
140/// An empty header still emits a (blank) header row so the result stays valid
141/// markdown; cells render their inline markdown.
142fn write_markdown_table(
143    alignments: &[TableAlignment],
144    header: &[Vec<InlineSpan>],
145    rows: &[Vec<Vec<InlineSpan>>],
146    out: &mut String,
147    pad: &str,
148) {
149    let cols = header
150        .len()
151        .max(rows.iter().map(Vec::len).max().unwrap_or(0));
152    if cols == 0 {
153        return;
154    }
155    let write_row = |cells: &[Vec<InlineSpan>], out: &mut String| {
156        out.push_str(pad);
157        out.push('|');
158        for i in 0..cols {
159            out.push(' ');
160            if let Some(cell) = cells.get(i) {
161                write_inline_markdown(cell, out);
162            }
163            out.push_str(" |");
164        }
165        out.push('\n');
166    };
167    write_row(header, out);
168    out.push_str(pad);
169    out.push('|');
170    for i in 0..cols {
171        out.push_str(match alignments.get(i).copied().unwrap_or_default() {
172            TableAlignment::None => " --- |",
173            TableAlignment::Left => " :--- |",
174            TableAlignment::Center => " :---: |",
175            TableAlignment::Right => " ---: |",
176        });
177    }
178    out.push('\n');
179    for row in rows {
180        write_row(row, out);
181    }
182    out.push('\n');
183}
184
185impl Block {
186    fn write_markdown(&self, out: &mut String, indent: usize) {
187        let pad = "  ".repeat(indent);
188        match self {
189            Self::Heading { level, spans } => {
190                let level = (*level).clamp(1, 6) as usize;
191                out.push_str(&pad);
192                out.push_str(&"#".repeat(level));
193                out.push(' ');
194                write_inline_markdown(spans, out);
195                out.push_str("\n\n");
196            },
197            Self::Paragraph { spans } => {
198                out.push_str(&pad);
199                write_inline_markdown(spans, out);
200                out.push_str("\n\n");
201            },
202            Self::CodeBlock { language, text } => {
203                out.push_str(&pad);
204                out.push_str("```");
205                if let Some(lang) = language {
206                    out.push_str(lang);
207                }
208                out.push('\n');
209                out.push_str(text);
210                if !text.ends_with('\n') {
211                    out.push('\n');
212                }
213                out.push_str(&pad);
214                out.push_str("```\n\n");
215            },
216            Self::Quote { blocks } => {
217                let mut inner = String::new();
218                for block in blocks {
219                    block.write_markdown(&mut inner, 0);
220                }
221                for line in inner.lines() {
222                    out.push_str(&pad);
223                    out.push_str("> ");
224                    out.push_str(line);
225                    out.push('\n');
226                }
227                out.push('\n');
228            },
229            Self::List { ordered, items } => {
230                for (i, item) in items.iter().enumerate() {
231                    out.push_str(&pad);
232                    if *ordered {
233                        out.push_str(&format!("{}. ", i + 1));
234                    } else {
235                        out.push_str("- ");
236                    }
237                    let mut first = true;
238                    for block in item {
239                        if first {
240                            // Render the first block inline with the marker
241                            // by trimming the leading newline-pair it produces.
242                            let mut piece = String::new();
243                            block.write_markdown(&mut piece, 0);
244                            out.push_str(piece.trim_end());
245                            out.push('\n');
246                            first = false;
247                        } else {
248                            block.write_markdown(out, indent + 1);
249                        }
250                    }
251                }
252                out.push('\n');
253            },
254            Self::Image { url, alt } => {
255                out.push_str(&pad);
256                out.push_str(&format!("![{alt}]({url})\n\n"));
257            },
258            Self::Preformatted { text } => {
259                out.push_str(&pad);
260                out.push_str("```\n");
261                out.push_str(text);
262                if !text.ends_with('\n') {
263                    out.push('\n');
264                }
265                out.push_str(&pad);
266                out.push_str("```\n\n");
267            },
268            Self::Rule => out.push_str("---\n\n"),
269            Self::FeedHeader {
270                title,
271                subtitle,
272                summary,
273                source_url,
274            } => {
275                out.push_str(&format!("# {title}\n\n"));
276                if let Some(subtitle) = subtitle {
277                    out.push_str(&format!("## {subtitle}\n\n"));
278                }
279                if let Some(summary) = summary {
280                    out.push_str(summary);
281                    out.push_str("\n\n");
282                }
283                if let Some(url) = source_url {
284                    out.push_str(&format!("[Open source]({url})\n\n"));
285                }
286            },
287            Self::FeedEntry {
288                title,
289                date,
290                summary,
291                article_url,
292                source_url,
293            } => {
294                out.push_str(&format!("## {title}\n\n"));
295                if let Some(date) = date {
296                    out.push_str(&format!("*{date}*\n\n"));
297                }
298                if let Some(summary) = summary {
299                    out.push_str(summary);
300                    out.push_str("\n\n");
301                }
302                if let Some(url) = article_url {
303                    out.push_str(&format!("[Open article]({url})\n\n"));
304                }
305                if let Some(url) = source_url {
306                    out.push_str(&format!("[Open source]({url})\n\n"));
307                }
308            },
309            Self::MetadataRow { label, value } => {
310                out.push_str(&format!("**{label}:** {value}\n\n"));
311            },
312            Self::Badge { text } => {
313                out.push_str(&format!("> *{text}*\n\n"));
314            },
315            Self::Table {
316                alignments,
317                header,
318                rows,
319            } => {
320                write_markdown_table(alignments, header, rows, out, &pad);
321            },
322        }
323    }
324
325    fn write_gemini(&self, out: &mut String) {
326        match self {
327            Self::Table { header, rows, .. } => {
328                out.push_str("```\n");
329                for line in table_lines(header, rows) {
330                    out.push_str(&line);
331                    out.push('\n');
332                }
333                out.push_str("```\n");
334            },
335            Self::Heading { level, spans } => {
336                let prefix = match level {
337                    1 => "# ",
338                    2 => "## ",
339                    _ => "### ",
340                };
341                out.push_str(prefix);
342                out.push_str(&inline_text(spans));
343                out.push('\n');
344            },
345            Self::Paragraph { spans } => {
346                // A link-only paragraph (e.g. a parsed `=>` line, or a bare
347                // link on its own line) IS the link line — emitting its text
348                // first would double it.
349                let text = inline_text(spans);
350                if !text.is_empty() && !is_link_only(spans) && !is_submit_only(spans) {
351                    out.push_str(&text);
352                    out.push('\n');
353                }
354                // Surface inline links as separate gemtext link lines after
355                // the paragraph text.
356                let mut links = Vec::new();
357                for span in spans {
358                    collect_link_targets(span, &mut links);
359                }
360                for (url, label) in links {
361                    out.push_str("=> ");
362                    out.push_str(&url);
363                    if !label.is_empty() && label != url {
364                        out.push(' ');
365                        out.push_str(&label);
366                    }
367                    out.push('\n');
368                }
369                let mut submissions = Vec::new();
370                for span in spans {
371                    collect_submit_targets(span, &mut submissions);
372                }
373                for (target, label) in submissions {
374                    out.push_str("=: ");
375                    out.push_str(&target);
376                    if !label.is_empty() && label != target {
377                        out.push(' ');
378                        out.push_str(&label);
379                    }
380                    out.push('\n');
381                }
382            },
383            Self::CodeBlock { language, text } => {
384                out.push_str("```");
385                if let Some(lang) = language {
386                    out.push_str(lang);
387                }
388                out.push('\n');
389                out.push_str(text);
390                if !text.ends_with('\n') {
391                    out.push('\n');
392                }
393                out.push_str("```\n");
394            },
395            Self::Quote { blocks } => {
396                let mut inner = String::new();
397                for block in blocks {
398                    block.write_gemini(&mut inner);
399                }
400                for line in inner.lines() {
401                    out.push_str("> ");
402                    out.push_str(line);
403                    out.push('\n');
404                }
405            },
406            Self::List { items, .. } => {
407                for item in items {
408                    let mut inner = String::new();
409                    for block in item {
410                        block.write_gemini(&mut inner);
411                    }
412                    let trimmed = inner.trim();
413                    out.push_str("* ");
414                    out.push_str(trimmed);
415                    out.push('\n');
416                }
417            },
418            Self::Image { url, alt } => {
419                out.push_str("=> ");
420                out.push_str(url);
421                if !alt.is_empty() {
422                    out.push(' ');
423                    out.push_str(alt);
424                }
425                out.push('\n');
426            },
427            Self::Preformatted { text } => {
428                out.push_str("```\n");
429                out.push_str(text);
430                if !text.ends_with('\n') {
431                    out.push('\n');
432                }
433                out.push_str("```\n");
434            },
435            Self::Rule => out.push('\n'),
436            Self::FeedHeader {
437                title,
438                subtitle,
439                summary,
440                source_url,
441            } => {
442                out.push_str(&format!("# {title}\n"));
443                if let Some(subtitle) = subtitle {
444                    out.push_str(&format!("## {subtitle}\n"));
445                }
446                if let Some(summary) = summary {
447                    out.push_str(summary);
448                    out.push('\n');
449                }
450                if let Some(url) = source_url {
451                    out.push_str(&format!("=> {url} Open source\n"));
452                }
453            },
454            Self::FeedEntry {
455                title,
456                date,
457                summary,
458                article_url,
459                source_url,
460            } => {
461                out.push_str(&format!("## {title}\n"));
462                if let Some(date) = date {
463                    out.push_str(&format!("> {date}\n"));
464                }
465                if let Some(summary) = summary {
466                    out.push_str(summary);
467                    out.push('\n');
468                }
469                if let Some(url) = article_url {
470                    out.push_str(&format!("=> {url} Open article\n"));
471                }
472                if let Some(url) = source_url {
473                    out.push_str(&format!("=> {url} Open source\n"));
474                }
475            },
476            Self::MetadataRow { label, value } => {
477                out.push_str(&format!("{label}: {value}\n"));
478            },
479            Self::Badge { text } => {
480                out.push_str(&format!("> {text}\n"));
481            },
482        }
483    }
484}
485
486impl Block {
487    /// Knot-format renderer. Reuses `write_markdown` for structural blocks;
488    /// emits fenced code blocks with protocol language tags for the four
489    /// semantic block variants so they round-trip through
490    /// `nematic::KnotEngine`'s fence expansion.
491    fn write_knot(&self, out: &mut String) {
492        match self {
493            Self::FeedHeader {
494                title,
495                subtitle,
496                summary,
497                source_url,
498            } => {
499                out.push_str("```feed-header\n");
500                out.push_str(&format!("title: {title}\n"));
501                if let Some(s) = subtitle {
502                    out.push_str(&format!("subtitle: {s}\n"));
503                }
504                if let Some(s) = summary {
505                    out.push_str(&format!("summary: {s}\n"));
506                }
507                if let Some(url) = source_url {
508                    out.push_str(&format!("source: {url}\n"));
509                }
510                out.push_str("```\n\n");
511            },
512            Self::FeedEntry {
513                title,
514                date,
515                summary,
516                article_url,
517                source_url,
518            } => {
519                out.push_str("```feed-entry\n");
520                out.push_str(&format!("title: {title}\n"));
521                if let Some(d) = date {
522                    out.push_str(&format!("date: {d}\n"));
523                }
524                if let Some(s) = summary {
525                    out.push_str(&format!("summary: {s}\n"));
526                }
527                if let Some(url) = article_url {
528                    out.push_str(&format!("url: {url}\n"));
529                }
530                if let Some(url) = source_url {
531                    out.push_str(&format!("source: {url}\n"));
532                }
533                out.push_str("```\n\n");
534            },
535            Self::MetadataRow { label, value } => {
536                out.push_str("```metadata-row\n");
537                out.push_str(&format!("{label}: {value}\n"));
538                out.push_str("```\n\n");
539            },
540            Self::Badge { text } => {
541                out.push_str("```badge\n");
542                out.push_str(text);
543                if !text.ends_with('\n') {
544                    out.push('\n');
545                }
546                out.push_str("```\n\n");
547            },
548            // Recurse into containers so semantic blocks nested inside
549            // quotes / list items also serialise as fences.
550            Self::Quote { blocks } => {
551                let mut inner = String::new();
552                for block in blocks {
553                    block.write_knot(&mut inner);
554                }
555                for line in inner.lines() {
556                    out.push_str("> ");
557                    out.push_str(line);
558                    out.push('\n');
559                }
560                out.push('\n');
561            },
562            Self::List { ordered, items } => {
563                for (i, item) in items.iter().enumerate() {
564                    if *ordered {
565                        out.push_str(&format!("{}. ", i + 1));
566                    } else {
567                        out.push_str("- ");
568                    }
569                    let mut inner = String::new();
570                    for block in item {
571                        block.write_knot(&mut inner);
572                    }
573                    out.push_str(inner.trim_end());
574                    out.push('\n');
575                }
576                out.push('\n');
577            },
578            // For everything else, knot output and markdown output match.
579            other => other.write_markdown(out, 0),
580        }
581    }
582}
583
584fn write_inline_markdown(spans: &[InlineSpan], out: &mut String) {
585    for span in spans {
586        match span {
587            InlineSpan::Text(t) => out.push_str(t),
588            InlineSpan::Code(t) => {
589                out.push('`');
590                out.push_str(t);
591                out.push('`');
592            },
593            InlineSpan::Emphasis(s) => {
594                out.push('*');
595                write_inline_markdown(s, out);
596                out.push('*');
597            },
598            InlineSpan::Strong(s) => {
599                out.push_str("**");
600                write_inline_markdown(s, out);
601                out.push_str("**");
602            },
603            InlineSpan::Link { url, spans, .. } => {
604                out.push('[');
605                write_inline_markdown(spans, out);
606                out.push_str("](");
607                out.push_str(url);
608                out.push(')');
609            },
610            InlineSpan::Submit { target, spans } => {
611                write_inline_markdown(spans, out);
612                out.push_str(" [submit: ");
613                out.push_str(target);
614                out.push(']');
615            },
616            InlineSpan::SoftBreak => out.push('\n'),
617            InlineSpan::LineBreak => out.push_str("  \n"),
618        }
619    }
620}
621
622/// Whether a span list is links and whitespace only (with at least one
623/// link) — the "this paragraph IS a link line" case shared by the gemtext
624/// and gophermap writers.
625fn is_link_only(spans: &[InlineSpan]) -> bool {
626    let mut saw_link = false;
627    for span in spans {
628        match span {
629            InlineSpan::Link { .. } => saw_link = true,
630            InlineSpan::Text(text) if text.trim().is_empty() => {},
631            InlineSpan::SoftBreak | InlineSpan::LineBreak => {},
632            _ => return false,
633        }
634    }
635    saw_link
636}
637
638fn is_submit_only(spans: &[InlineSpan]) -> bool {
639    let mut saw_submit = false;
640    for span in spans {
641        match span {
642            InlineSpan::Submit { .. } => saw_submit = true,
643            InlineSpan::Text(text) if text.trim().is_empty() => {},
644            InlineSpan::SoftBreak | InlineSpan::LineBreak => {},
645            _ => return false,
646        }
647    }
648    saw_submit
649}
650
651fn collect_link_targets(span: &InlineSpan, out: &mut Vec<(String, String)>) {
652    match span {
653        InlineSpan::Link { url, spans, .. } => {
654            out.push((url.clone(), inline_text(spans)));
655            for inner in spans {
656                collect_link_targets(inner, out);
657            }
658        },
659        InlineSpan::Emphasis(spans)
660        | InlineSpan::Strong(spans)
661        | InlineSpan::Submit { spans, .. } => {
662            for inner in spans {
663                collect_link_targets(inner, out);
664            }
665        },
666        _ => {},
667    }
668}
669
670fn collect_submit_targets(span: &InlineSpan, out: &mut Vec<(String, String)>) {
671    match span {
672        InlineSpan::Submit { target, spans } => {
673            out.push((target.clone(), inline_text(spans)));
674        },
675        InlineSpan::Emphasis(spans)
676        | InlineSpan::Strong(spans)
677        | InlineSpan::Link { spans, .. } => {
678            for inner in spans {
679                collect_submit_targets(inner, out);
680            }
681        },
682        _ => {},
683    }
684}
685
686// Gophermap + plain-text exporters live in `render/export.rs`, the HTML
687// exporter in `render/html.rs` (this file is at the 600-LOC ceiling); tests
688// live in `render/tests.rs`.
689mod export;
690mod html;
691pub use export::GophermapContext;
692
693// Tests live in `render/tests.rs` to keep this file under the 600-LOC ceiling.
694#[cfg(test)]
695mod tests;