Skip to main content

quillmark_core/document/
mod.rs

1//! Parsing and typed in-memory model for Quillmark card-yaml documents.
2//!
3//! A [`Document`] holds a root [`Card`] plus ordered composable cards. The
4//! format is specified in
5//! [markdown-spec.md](https://github.com/borb-sh/quillmark/blob/main/prose/references/markdown-spec.md).
6
7use serde::{Deserialize, Serialize};
8
9use quillmark_content::markdown::from_markdown as import_markdown;
10use quillmark_content::model::Content;
11
12use crate::error::ParseError;
13use crate::error::{Diagnostic, Severity};
14use crate::version::QuillReference;
15
16/// [`stored_as`] under the codec `content` holds.
17#[cfg(test)]
18pub(crate) fn stored_over(old: Option<&serde_json::Value>, content: &Content) -> serde_json::Value {
19    stored_as(old, content, content.codec)
20}
21
22/// `content` stored under `codec` over `old`, the value it is written over:
23/// under the ids of what it kept from `old`, or its own where there is none.
24pub(crate) fn stored_as(
25    old: Option<&serde_json::Value>,
26    content: &Content,
27    codec: quillmark_content::model::Codec,
28) -> serde_json::Value {
29    let mut content = match held_value(old) {
30        Some(held) => quillmark_content::diff::align(&held, content.clone()),
31        None => content.clone(),
32    };
33    content.codec = codec;
34    content.to_value()
35}
36
37fn held_value(old: Option<&serde_json::Value>) -> Option<Content> {
38    old.filter(|v| v.is_object())
39        .and_then(|v| Content::from_value_lenient(v).ok())
40        .map(|read| read.content)
41}
42
43pub(crate) fn import_body(md: &str) -> Result<Content, ImportError> {
44    import_markdown(md).map(|imported| imported.content)
45}
46
47/// [`import_body`], pushing a [`dropped_construct`] warning at `at` for each
48/// construct the import drops.
49pub(crate) fn import_body_at(
50    md: &str,
51    at: &crate::path::DocPath,
52    warnings: &mut Vec<Diagnostic>,
53) -> Result<Content, ImportError> {
54    let imported = import_markdown(md)?;
55    warnings.extend(dropped_constructs(imported.warnings, Some(at)));
56    Ok(imported.content)
57}
58
59/// The diagnostic code a markdown import's dropped construct rides.
60pub const DROPPED_CONSTRUCT: &str = "parse::dropped_construct";
61
62/// The warning a markdown import owes what it could not carry: `count` of
63/// `construct` dropped from one field. It carries no `path`: the caller that
64/// knows the field's address attaches it. Non-fatal: the rest of the markdown
65/// imports.
66pub fn dropped_construct(warning: ImportWarning) -> Diagnostic {
67    let ImportWarning { construct, count } = warning;
68    let (message, hint) = dropped_message(&construct, count);
69    let mut args = std::collections::BTreeMap::new();
70    args.insert("construct".to_string(), construct.to_string().into());
71    args.insert("count".to_string(), count.into());
72    Diagnostic::new(Severity::Warning, message)
73        .with_code(DROPPED_CONSTRUCT.to_string())
74        .with_hint(hint)
75        .with_args(args)
76}
77
78/// One [`dropped_construct`] per warning, each at `at` when given.
79pub fn dropped_constructs(
80    warnings: Vec<ImportWarning>,
81    at: Option<&crate::path::DocPath>,
82) -> Vec<Diagnostic> {
83    let at = at.map(ToString::to_string);
84    warnings
85        .into_iter()
86        .map(|w| match &at {
87            Some(at) => dropped_construct(w).with_path(at.clone()),
88            None => dropped_construct(w),
89        })
90        .collect()
91}
92
93/// The diagnostic code a stored content value read in a spelling other than
94/// its canonical one rides.
95pub const NONCANONICAL_READ: &str = "content::noncanonical_read";
96
97/// The warning a stored read owes a content value it rewrote to its canonical
98/// form: the value loads canonical, and storing the document again writes
99/// those bytes.
100pub fn noncanonical_read() -> Diagnostic {
101    Diagnostic::new(
102        Severity::Warning,
103        "a stored content value is not in canonical form, and reads as it".to_string(),
104    )
105    .with_code(NONCANONICAL_READ.to_string())
106    .with_hint("store the document again to write its canonical form".to_string())
107}
108
109/// `words` each in backticks, joined by commas and `last` before the final one.
110fn listed(words: &[&str], last: &str) -> String {
111    let ticked: Vec<String> = words.iter().map(|w| format!("`{w}`")).collect();
112    match ticked.split_last() {
113        Some((tail, [])) => tail.clone(),
114        Some((tail, init)) => format!("{} {last} {tail}", init.join(", ")),
115        None => String::new(),
116    }
117}
118
119/// [`dropped_construct`]'s message, naming what dropped, and its hint, naming
120/// the spelling that keeps it.
121fn dropped_message(construct: &DroppedConstruct, n: usize) -> (String, String) {
122    use quillmark_content::markdown::carrier::RESERVED_ATTRS;
123    use quillmark_content::table::{CELL_VALIGNS, TABLE_ALIGNS};
124    const TIGHT: &str =
125        "Markdown on the lines under a tag line drops with it, up to the next blank line.";
126    const BESIDE: &str = "A tag line beside a line of other tags drops with the markdown under it, up to the next blank line.";
127    let some = |one: &str, many: &str| {
128        if n == 1 {
129            format!("a {one}")
130        } else {
131            format!("{n} {many}")
132        }
133    };
134    let some_in_field = |one: &str, many: &str| {
135        if n == 1 {
136            format!("a {one} in this field was")
137        } else {
138            format!("{n} {many} in this field were")
139        }
140    };
141    let attr_dropped = |tag: &str, attr: &str, hint: String| {
142        let on = if n == 1 {
143            String::new()
144        } else {
145            format!(" on {n} tags")
146        };
147        (
148            format!(
149                "markdown import dropped the `{attr}` attribute of `<{tag}>`{on} in this field"
150            ),
151            hint,
152        )
153    };
154    let tag = construct.to_string();
155    match construct {
156        DroppedConstruct::Footnote => (
157            format!(
158                "markdown import dropped {} in this field",
159                some("footnote", "footnotes")
160            ),
161            "A footnote is a reference `[^label]` in prose, outside a table cell or another note, and one \
162             definition `[^label]: note` naming the same label."
163                .to_string(),
164        ),
165        DroppedConstruct::FootnoteSize => (
166            format!(
167                "markdown import kept {} in this field as written text",
168                some("footnote reference", "footnote references")
169            ),
170            format!(
171                "A reference copies its whole note, and after the first reading of each note the copies share                  {} characters; the references past it stay as `[^label]`. Cite a long note once.",
172                quillmark_content::MAX_NOTE_COPIES
173            ),
174        ),
175        DroppedConstruct::NoteBlock(block) => (
176            format!(
177                "markdown import kept the text of {} inside a footnote and dropped its structure",
178                some(&format!("{block} block"), &format!("{block} blocks"))
179            ),
180            "A footnote's note is inline text: each paragraph, list item or other block in it becomes a line \
181             of that text."
182                .to_string(),
183        ),
184        DroppedConstruct::Bidi => (
185            format!(
186                "markdown import dropped {} from this field",
187                some("bidi control", "bidi controls")
188            ),
189            "Content text admits no bidi formatting control (U+061C, U+200E, U+200F, U+202A–U+202E, \
190             U+2066–U+2069); the renderer orders mixed-direction text by the Unicode bidi algorithm."
191                .to_string(),
192        ),
193        DroppedConstruct::Math => (
194            format!(
195                "markdown import kept {} as written text in this field",
196                some("equation", "equations")
197            ),
198            "An equation `$…$` or `$$…$$` reads as one in prose, outside a table cell, an image's alt text \
199             and a footnote's note, around TeX that is not blank; write `\\$` for a dollar sign that opens none."
200                .to_string(),
201        ),
202        DroppedConstruct::Table => (
203            format!(
204                "markdown import closed {} in this field where its HTML block ended",
205                some("`<table>`", "`<table>`s")
206            ),
207            "An HTML table is one HTML block: a blank line inside it ends the table there, and what follows \
208             reads as markdown. Close each `<table>` with `</table>` before any blank line."
209                .to_string(),
210        ),
211        DroppedConstruct::TableRow => (
212            format!(
213                "markdown import padded {} in this field to its table's columns",
214                some("table row", "table rows")
215            ),
216            "An HTML table is as wide as its widest row. A row leaves out each cell a `rowspan` above it covers, \
217             and a row short of the width pads with empty cells."
218                .to_string(),
219        ),
220        DroppedConstruct::TableSize => (
221            format!(
222                "markdown import cut {} in this field at {} cells",
223                some("table", "tables"),
224                quillmark_content::MAX_TABLE_CELLS
225            ),
226            "A table's rows times its columns stay within the bound; the rows past it drop. Split the table."
227                .to_string(),
228        ),
229        DroppedConstruct::TableText => (
230            format!(
231                "markdown import dropped {} outside every cell of an HTML table in this field",
232                some("run of text", "runs of text")
233            ),
234            "Text in an HTML table sits in a `<td>` or `<th>`; a `<caption>` and text between rows drop.".to_string(),
235        ),
236        DroppedConstruct::TableAttr { tag: element, attr } => attr_dropped(
237            element,
238            attr,
239            match (element.as_str(), attr.as_str()) {
240                ("table", "widths") => {
241                    "`widths` is a whole number from 1 to 2^53 - 1, or `auto`, per column, such as `widths=\"2 1 auto\"`."
242                        .to_string()
243                }
244                ("table", "aligns") => {
245                    "`aligns` is `none`, `left`, `center` or `right` per column, such as `aligns=\"left none right\"`."
246                        .to_string()
247                }
248                ("table" | "td" | "th", "align") => format!("`align` is {}.", listed(&TABLE_ALIGNS, "or")),
249                ("table", _) => "`<table>` takes `widths`, `aligns` and `align`.".to_string(),
250                (_, "colspan" | "rowspan") => format!("`{attr}` is a whole number from 1."),
251                (_, "valign") => format!("`valign` is {}.", listed(&CELL_VALIGNS, "or")),
252                ("td" | "th", _) => "`<td>` and `<th>` take `colspan`, `rowspan`, `align` and `valign`.".to_string(),
253                _ => format!("`<{element}>` takes no attributes."),
254            },
255        ),
256        DroppedConstruct::ElementAttr { element, attr }
257            if attr == "ref" && quillmark_content::markdown::carrier::RESERVED.contains(&element.as_str()) =>
258        {
259            let (what, spelling) = match element == quillmark_content::markdown::carrier::ANCHOR {
260                true => ("anchor", ("tag", "tags")),
261                false => ("island", ("token", "tokens")),
262            };
263            let element = DroppedConstruct::Element(element.clone());
264            (
265                format!(
266                    "markdown revise dropped {} naming no {what} the stored value holds, or one an earlier \
267                     tag names, in this field",
268                    some(&format!("`<{element}>` {}", spelling.0), &format!("`<{element}>` {}", spelling.1))
269                ),
270                format!(
271                    "A `ref` names a {what} of the value the annotated read was taken from, once per {what}: \
272                     copy the tag from the read, or remove it. An anchor without its tag keeps its place by \
273                     the text around it."
274                ),
275            )
276        }
277        DroppedConstruct::ElementAttr { element, attr } => attr_dropped(
278            &DroppedConstruct::Element(element.clone()).to_string(),
279            attr,
280            format!(
281                "An attribute name is lowercase letters, digits and `_`, opening with a letter, once per tag, \
282                 and none of `{}` or a name opening `on`.",
283                RESERVED_ATTRS.join("`, `")
284            ),
285        ),
286        DroppedConstruct::BadName(_) => (
287            format!(
288                "markdown import does not carry raw HTML: {} dropped",
289                some_in_field(&format!("`<{tag}>` tag"), &format!("`<{tag}>` tags"))
290            ),
291            format!(
292                "An element name after `qm-` is lowercase words of letters and digits joined by single `-`, \
293                 opening with a letter. {TIGHT}"
294            ),
295        ),
296        DroppedConstruct::Element(name) if name == quillmark_content::markdown::carrier::SPAN => (
297            format!(
298                "markdown import dropped {} in this field",
299                some(&format!("`<{tag}>` tag"), &format!("`<{tag}>` tags"))
300            ),
301            format!(
302                "A `<{tag}>` pair sets a `family` inside one line of text and closes with `</{tag}>` there; \
303                 HTML reads `<{tag}/>` as an open tag. A family is a run's, never a block's. {BESIDE}"
304            ),
305        ),
306        DroppedConstruct::Element(name) if name == quillmark_content::markdown::carrier::ISLAND => (
307            format!(
308                "markdown import dropped {} in this field",
309                some(&format!("`<{tag}>` token"), &format!("`<{tag}>` tokens"))
310            ),
311            format!(
312                "A `<{tag}>` token stands for an island of the stored value an annotated read was taken from, \
313                 in prose: only a revise of that value reads it. A plain import, a table cell, a footnote and \
314                 an image's alt text drop it."
315            ),
316        ),
317        DroppedConstruct::Element(_) => (
318            format!(
319                "markdown import dropped {} in this field",
320                some(&format!("`<{tag}>` tag"), &format!("`<{tag}>` tags"))
321            ),
322            format!("A `<{tag}>` tag carries nothing: what it wraps stays and the tags drop. Remove them."),
323        ),
324        DroppedConstruct::Tag(name) => match name.as_str() {
325            "u" => (
326                format!("markdown import dropped {} in this field", some("`<u>` tag", "`<u>` tags")),
327                "A `<u>` takes no attributes and closes with `</u>` in the paragraph, heading, list item or \
328                 table cell it opens in."
329                    .to_string(),
330            ),
331            "pre" | "script" | "style" | "textarea" => (
332                format!(
333                    "markdown import does not carry raw HTML: {} dropped",
334                    some_in_field(&format!("`<{tag}>` block"), &format!("`<{tag}>` blocks"))
335                ),
336                format!("A `<{tag}>` block drops whole, through its closing tag. Write code in a backtick fence."),
337            ),
338            _ => (
339                format!(
340                    "markdown import does not carry raw HTML: {} dropped",
341                    some_in_field(&format!("`<{tag}>` tag"), &format!("`<{tag}>` tags"))
342                ),
343                "Raw HTML imports nothing but `<u>`, `<br>`, a `<table>` and `<qm-span>`. Where a line \
344                 opens with any other tag, its block runs to the next blank line and drops whole, markdown \
345                 included; a blank line under the tag line keeps what follows."
346                    .to_string(),
347            ),
348        },
349    }
350}
351
352/// Which encoding a [`Codec::decode_value`] failure came from, so a call site
353/// can prefix its diagnostic per encoding.
354#[derive(Debug, Clone, PartialEq, Eq)]
355pub(crate) enum ContentDecodeError {
356    NotContent(String),
357    BadMarkdown(String),
358}
359
360impl ContentDecodeError {
361    pub(crate) fn into_message(self) -> String {
362        match self {
363            ContentDecodeError::NotContent(m) | ContentDecodeError::BadMarkdown(m) => m,
364        }
365    }
366}
367
368/// A content codec: which authored string a [`Content`](quillmark_content::model::Content) field accepts, and which
369/// text a stored content projects back to. Both codecs also accept a canonical
370/// content object, so a codec is exactly the string end of the round trip. The
371/// declared type names one (`FieldType::codec`), and every schema-bound
372/// content read and projection runs the codec it names.
373#[derive(Debug, Clone, Copy, PartialEq, Eq)]
374pub(crate) enum Codec {
375    /// A string is markdown, and a content projects back to markdown — lossy,
376    /// content-only marks not surviving.
377    Richtext,
378    /// A string is literal text (`*hi*` stays four characters), and a content
379    /// projects back verbatim.
380    Text,
381}
382
383impl Codec {
384    /// The codec a content object names: [`Codec::Text`] for one spelling
385    /// `codec: "plain"`, [`Codec::Richtext`] for any other.
386    pub(crate) fn of_object(value: &serde_json::Value) -> Codec {
387        match value.get("codec").and_then(serde_json::Value::as_str) {
388            Some("plain") => Codec::Text,
389            _ => Codec::Richtext,
390        }
391    }
392
393    /// The content codec this codec rests under.
394    pub(crate) fn content(self) -> quillmark_content::model::Codec {
395        match self {
396            Codec::Richtext => quillmark_content::model::Codec::Rich,
397            Codec::Text => quillmark_content::model::Codec::Plain,
398        }
399    }
400
401    /// The schema keyword declaring this codec, carried verbatim on
402    /// [`EditError::FieldDecode`].
403    pub(crate) fn name(self) -> &'static str {
404        match self {
405            Codec::Richtext => edit::CODEC_RICHTEXT,
406            Codec::Text => edit::CODEC_TEXT,
407        }
408    }
409
410    /// How this codec reads a stored string, for the shape-mismatch message.
411    fn string_form(self) -> &'static str {
412        match self {
413            Codec::Richtext => "a markdown string",
414            Codec::Text => "a string",
415        }
416    }
417
418    /// Decode a JSON value in either accepted encoding: a canonical content
419    /// object, or an authored string read this codec's way, with what a
420    /// markdown import dropped (none from an object or literal text). `None`
421    /// when the value is neither an object nor a string; the call site handles
422    /// those shapes and maps the error into its own type.
423    pub(crate) fn decode_value(
424        self,
425        value: &serde_json::Value,
426    ) -> Option<Result<quillmark_content::markdown::Imported, ContentDecodeError>> {
427        self.decode_value_admitting(value, quillmark_content::markdown::Admit::Blocks)
428    }
429
430    /// [`decode_value`](Self::decode_value) of a value that admits `admit`.
431    pub(crate) fn decode_value_admitting(
432        self,
433        value: &serde_json::Value,
434        admit: quillmark_content::markdown::Admit,
435    ) -> Option<Result<quillmark_content::markdown::Imported, ContentDecodeError>> {
436        let whole = |content| quillmark_content::markdown::Imported {
437            content,
438            warnings: Vec::new(),
439        };
440        match value {
441            serde_json::Value::Object(_) => Some(
442                Content::from_value_lenient(value)
443                    .map(|read| whole(read.content))
444                    .map_err(|e| ContentDecodeError::NotContent(e.to_string())),
445            ),
446            serde_json::Value::String(s) => Some(match self {
447                Codec::Richtext => quillmark_content::markdown::from_markdown_admitting(s, admit)
448                    .map_err(|e| ContentDecodeError::BadMarkdown(e.to_string())),
449                Codec::Text => Ok(whole(quillmark_content::markdown::plain(s))),
450            }),
451            _ => None,
452        }
453    }
454
455    /// The shape-mismatch message for a value in neither accepted encoding,
456    /// naming the shape that arrived. Every surface that refuses an unshaped
457    /// richtext value spells this one sentence.
458    pub(crate) fn unshaped_message(self, value: &serde_json::Value) -> String {
459        format!(
460            "expected a {} content object or {}, got {}",
461            self.name(),
462            self.string_form(),
463            match value {
464                serde_json::Value::Bool(_) => "a boolean",
465                serde_json::Value::Number(_) => "a number",
466                serde_json::Value::Array(_) => "an array",
467                _ => "an unsupported value",
468            }
469        )
470    }
471
472    /// [`decode_value`](Self::decode_value) closed over the shapes a stored field
473    /// can hold: a null is the empty content (null ≡ absent), and anything
474    /// neither object nor string is a decode failure.
475    pub(crate) fn decode_field(
476        self,
477        value: &serde_json::Value,
478    ) -> Result<Content, ContentDecodeError> {
479        match self.decode_value(value) {
480            Some(result) => result.map(|imported| imported.content),
481            None if value.is_null() => Ok(Content::empty_as(self.content())),
482            None => Err(ContentDecodeError::NotContent(self.unshaped_message(value))),
483        }
484    }
485
486    /// [`decode_field`](Self::decode_field) as a content value: an object
487    /// keeps its ids, and a string imports with fresh ones.
488    pub(crate) fn decode_content(
489        self,
490        value: &serde_json::Value,
491    ) -> Result<Content, ContentDecodeError> {
492        match value {
493            serde_json::Value::Object(_) => Content::from_value(value)
494                .map_err(|e| ContentDecodeError::NotContent(e.to_string())),
495            serde_json::Value::String(s) => match self {
496                Codec::Richtext => quillmark_content::markdown::from_markdown(s)
497                    .map(|i| i.content)
498                    .map_err(|e| ContentDecodeError::BadMarkdown(e.to_string())),
499                Codec::Text => Ok(quillmark_content::markdown::plain(s)),
500            },
501            serde_json::Value::Null => Ok(Content::empty_as(self.content())),
502            _ => Err(ContentDecodeError::NotContent(self.unshaped_message(value))),
503        }
504    }
505
506    /// [`decode_content`](Self::decode_content) for a value the document
507    /// already holds: an object reads as a stored value does
508    /// ([`Content::from_value_lenient`]), the canonical form of what it spells.
509    pub(crate) fn read_content(
510        self,
511        value: &serde_json::Value,
512    ) -> Result<Content, ContentDecodeError> {
513        match value {
514            serde_json::Value::Object(_) => Content::from_value_lenient(value)
515                .map(|read| read.content)
516                .map_err(|e| ContentDecodeError::NotContent(e.to_string())),
517            _ => self.decode_content(value),
518        }
519    }
520
521    /// Project a content back to this codec's text: the inverse of its string
522    /// encoding.
523    pub(crate) fn project(self, content: &Content) -> String {
524        match self {
525            Codec::Richtext => quillmark_content::markdown::to_markdown(content),
526            Codec::Text => quillmark_content::markdown::to_plaintext(content),
527        }
528    }
529}
530
531/// Why a richtext value did not become stored content, classified so each layer
532/// words the failure in its own error vocabulary.
533#[derive(Debug, Clone, PartialEq, Eq)]
534pub(crate) enum RichtextValueError {
535    /// An accepted encoding that failed to decode.
536    Decode(ContentDecodeError),
537    /// Neither a canonical content object nor a markdown string.
538    Unshaped,
539    /// The field is one line and the content spans more than one paragraph.
540    NotSingleLine,
541    /// The field holds lines and the content holds a block or an island.
542    NotLines,
543}
544
545/// The contract for a richtext value that must *become* stored content: decode
546/// either accepted encoding, a markdown string read as `shape` admits, enforce the shape,
547/// canonicalize, and hand back what the import dropped. The strict typed write and the schema-literal companion
548/// cache share it and differ only in the diagnostic they render from the error.
549pub(crate) fn canonical_richtext_value(
550    value: &serde_json::Value,
551    shape: crate::quill::Shape,
552) -> Result<(serde_json::Value, Vec<ImportWarning>), RichtextValueError> {
553    let (mut content, warnings) = match value {
554        serde_json::Value::Object(_) => (
555            Content::from_value(value).map_err(|e| {
556                RichtextValueError::Decode(ContentDecodeError::NotContent(e.to_string()))
557            })?,
558            Vec::new(),
559        ),
560        serde_json::Value::String(s) => {
561            let imported = quillmark_content::markdown::from_markdown_admitting(s, shape.admit())
562                .map_err(|e| {
563                RichtextValueError::Decode(ContentDecodeError::BadMarkdown(e.to_string()))
564            })?;
565            (imported.content, imported.warnings)
566        }
567        _ => return Err(RichtextValueError::Unshaped),
568    };
569    if !shape.admits(&content) {
570        return Err(match shape {
571            crate::quill::Shape::Line => RichtextValueError::NotSingleLine,
572            _ => RichtextValueError::NotLines,
573        });
574    }
575    content.codec = quillmark_content::model::Codec::Rich;
576    Ok((content.to_value(), warnings))
577}
578
579/// Plain content less its trailing whitespace and breaks: a one-line `text`
580/// value's form before its single-line check, so the newline a clip-chomped
581/// YAML `|` scalar keeps is no second line. Its anchors hold, cut at the new
582/// end.
583pub(crate) fn trim_line_end(mut content: Content) -> Content {
584    let keep = content.text.trim_end().len();
585    if keep == content.text.len() {
586        return content;
587    }
588    content.text.truncate(keep);
589    content
590        .blocks
591        .truncate(content.text.matches('\n').count() + 1);
592    cut_anchors(&mut content);
593    content
594}
595
596/// Plain content as one paragraph, each break a space. The length holds, so
597/// a rendered region's offsets still index the stored value, and so do its
598/// anchors.
599pub(crate) fn fold_line_breaks(mut content: Content) -> Content {
600    content.text = content
601        .text
602        .chars()
603        .map(|c| match c {
604            '\n' | quillmark_content::model::HARD_BREAK => ' ',
605            c => c,
606        })
607        .collect();
608    content.blocks.truncate(1);
609    if let Some(block) = content.blocks.first_mut() {
610        block.kind = quillmark_content::model::BlockKind::Para;
611        block.path.clear();
612    }
613    content.containers.clear();
614    cut_anchors(&mut content);
615    content
616}
617
618fn cut_anchors(content: &mut Content) {
619    let len = content.len_scalars();
620    for a in &mut content.anchors {
621        a.start = a.start.min(len);
622        a.end = a.end.min(len);
623    }
624    content.normalize();
625}
626
627pub(crate) mod align;
628pub mod anchors;
629pub mod assemble;
630pub mod base;
631pub mod card_id;
632pub mod dto;
633pub mod edit;
634pub mod emit;
635pub mod fences;
636pub mod meta;
637pub mod payload;
638pub(crate) mod prescan;
639pub mod revise;
640pub mod wire;
641pub mod write;
642pub(crate) mod yaml_hints;
643
644pub use anchors::AnchorSelector;
645pub use base::{HASH_TAG, StaleBase, content_hash, value_hash};
646pub use dto::{
647    STORAGE_V0_124_0, STORAGE_V0_129_0, STORAGE_V0_131_0, STORAGE_V0_134_0, STORAGE_V0_135_0,
648    StorageError, StoredDocument, peek_storage_version,
649};
650pub use edit::{CardMut, EditError, Unchecked};
651pub use emit::{AnnotatedMarkdown, DocumentAnchor};
652pub use meta::{CardKindError, is_valid_kind_name, validate_composable_kind};
653pub use payload::{MetaKey, Payload, PayloadItem};
654/// Returned by [`Document::reattach`], so nameable from here.
655pub use quillmark_content::anchors::Reattached;
656/// Carried by [`EditError::Import`], so nameable from here.
657pub use quillmark_content::markdown::ImportError;
658/// Answered by [`Card::annotated`] and the content crate's anchor reads, so nameable from here.
659pub use quillmark_content::markdown::{AnchorRead, Annotated};
660/// Taken by [`dropped_construct`], so nameable from here.
661pub use quillmark_content::markdown::{DroppedConstruct, ImportWarning};
662pub use revise::DocumentRevised;
663// Reachable through `Payload::nested_comments`, so nameable from here.
664pub use prescan::NestedComment;
665pub use wire::{CardWire, PayloadItemWire, WireError};
666pub use write::{
667    Edit, Located, MAX_CHANGE_STEPS, Receipt, Target, WriteOptions, check_change,
668    check_content_value,
669};
670
671/// Where Quillmark Markdown departs from plain Markdown and YAML, as rules
672/// surfaced verbatim to LLM/MCP consumers and to the bindings. The single
673/// source of truth: bindings call in rather than re-stating the rules.
674pub const MARKDOWN_RULES: &str = "Quillmark Markdown rules:
675\u{2022} Block opener and closer are EXACTLY `~~~` (three tildes). The opener's info string is ignored \u{2014} `~~~card-yaml` is accepted and re-emits as a bare `~~~`.
676\u{2022} A blank line must precede every `~~~` block opener (unless it is line 1), and the opener must be at column zero (no leading spaces). An indented `~~~` is an ordinary code block, not a card.
677\u{2022} The first block is the root and MUST contain `$quill: <name>` or `$quill: <name>@<selector>`. Its `$kind` is `main` by position \u{2014} an explicit `$kind: main` is accepted but not required. Every later block is a composable card and MUST declare `$kind: <card_kind>`.
678\u{2022} Reserved `$`-keys: `$quill`, `$kind`, `$id`, `$ext`, `$seed`. User fields use lowercase snake_case.
679\u{2022} A composable card's `$id` line names it across edits: keep it when you edit or move the card, leave it out of a new card (one is minted), and never copy it onto a second card.
680\u{2022} Prose body is the text after a block's closing `~~~`, up to the next opener or EOF. To include a literal fenced code block in prose, use a backtick fence (```); any column-zero `~~~` block is parsed as card metadata.
681\u{2022} A blank or null value (`field:`, `field: null`, `field: ~`) is the same as omitting the field: it falls back to the field's default, else its blank. `field: \"\"` is kept as written, an explicit empty value.
682\u{2022} Plain-scalar values cannot start with `*` or `&` (YAML alias/anchor markers) and cannot contain `: ` (colon-space). For markdown emphasis, embedded colons, or other special prefixes, quote the value: `field: '**bold**'` or `field: \"Name: subtitle\"`. Multi-line values use `|-`, not multi-line quoted scalars.
683\u{2022} In a body or richtext value, `<qm-span family=\"<family>\">text</qm-span>` sets a run's font family. Pairs nest, the innermost winning and the outer resuming past it. Name only a family the host's font library supplies: any other keeps the surrounding font and warns.
684\u{2022} Markdown read from an annotated read carries `<qm-anchor ref=\"\u{2026}\"></qm-anchor>` tags and `<qm-island ref=\"\u{2026}\"></qm-island>` tokens. Keep each tag before the text it marks, moving it with that text; drop a tag only with its text. Keep each token where its island belongs: it stands for a table, image or equation kept as stored. Never write a `ref` the read did not hold.";
685
686#[cfg(test)]
687mod tests;
688
689/// The record of one load: the [`Document`] and any non-fatal warnings.
690/// Returned by both [`Document::parse`] and the bound
691/// [`Quill::parse`](crate::quill::Quill::parse), whose `warnings` also carry
692/// the `conform::*` ones. Warnings live here and only here: `Document` is the
693/// value, `Parsed` the load event.
694#[derive(Debug)]
695#[must_use = "carries parse warnings; read `.document`/`.warnings` or bind it"]
696pub struct Parsed {
697    pub document: Document,
698    pub warnings: Vec<Diagnostic>,
699}
700
701/// A parse ahead of a revise: the [`Parsed`] document, its cards unsettled,
702/// and each body's markdown, the main card's first.
703#[derive(Debug)]
704pub(crate) struct Revising {
705    pub parsed: Parsed,
706    pub bodies: Vec<String>,
707}
708
709/// A single card-yaml block (root or composable). `body` is the [`Content`]
710/// of the prose after the closing fence: the empty content when none follows.
711/// Markdown is a projection: [`Card::body_markdown`] re-emits it.
712#[derive(Debug, Clone, PartialEq)]
713pub struct Card {
714    payload: Payload,
715    body: Content,
716    hashes: Hashes,
717}
718
719/// The hash a write left on the body and on each richtext field it wrote,
720/// so the next write reads it rather than hashing the value again. A body
721/// set forgets the body's, and any payload write every field's. Derived from
722/// the values, so it takes no part in equality.
723#[derive(Clone, Default)]
724pub(crate) struct Hashes {
725    body: Option<String>,
726    fields: std::collections::HashMap<String, String>,
727}
728
729impl Hashes {
730    pub(crate) fn body(&self) -> Option<&str> {
731        self.body.as_deref()
732    }
733
734    pub(crate) fn field(&self, name: &str) -> Option<&str> {
735        self.fields.get(name).map(String::as_str)
736    }
737}
738
739impl PartialEq for Hashes {
740    fn eq(&self, _: &Self) -> bool {
741        true
742    }
743}
744
745impl std::fmt::Debug for Hashes {
746    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
747        f.write_str("Hashes")
748    }
749}
750
751impl Card {
752    /// Create a `Card` from its parts without validation.
753    pub(crate) fn from_parts(payload: Payload, body: Content) -> Self {
754        Self {
755            payload,
756            body,
757            hashes: Hashes::default(),
758        }
759    }
760
761    pub fn quill(&self) -> Option<&QuillReference> {
762        self.payload.quill()
763    }
764
765    pub fn kind(&self) -> Option<&str> {
766        self.payload.kind()
767    }
768
769    /// A composable card's `$id`: a [card id](card_id::is_card_id) no other
770    /// card of its document holds, minted where none was given. `None` on the
771    /// main card, and on a card not yet placed that spells none.
772    pub fn id(&self) -> Option<&str> {
773        self.payload.id()
774    }
775
776    /// Opaque `$ext` map for out-of-band extension data (UI editor state,
777    /// agent annotations, …). Carried through Markdown and storage DTO
778    /// round-trips; never emitted into the plate JSON backends consume.
779    pub fn ext(&self) -> Option<&serde_json::Map<String, serde_json::Value>> {
780        self.payload.ext()
781    }
782
783    /// The card's card-yaml storage as a read view; writes go through the verbs
784    /// [`Payload`] names.
785    pub fn payload(&self) -> &Payload {
786        &self.payload
787    }
788
789    pub(crate) fn payload_mut(&mut self) -> &mut Payload {
790        self.hashes.fields.clear();
791        &mut self.payload
792    }
793
794    /// The card body: the stored content value. For the markdown projection
795    /// use [`Card::body_markdown`].
796    pub fn body(&self) -> &Content {
797        &self.body
798    }
799
800    /// The card body rendered back to its markdown projection. This is a
801    /// derived view (`export ∘ body`), not stored state; a `Document` round-trip
802    /// therefore canonicalizes the body (e.g. `__b__` → `**b**`).
803    pub fn body_markdown(&self) -> String {
804        quillmark_content::markdown::to_markdown(&self.body)
805    }
806
807    pub(crate) fn set_body(&mut self, body: Content) {
808        self.hashes.body = None;
809        self.body = body;
810    }
811
812    /// Note the hash a write left at `field`, `None` the body.
813    pub(crate) fn remember_hash(&mut self, field: Option<&str>, hash: String) {
814        match field {
815            None => self.hashes.body = Some(hash),
816            Some(name) => {
817                self.hashes.fields.insert(name.to_string(), hash);
818            }
819        }
820    }
821
822    /// Read a content-valued user field back through `codec`: the field-level
823    /// twin of [`Card::body`].
824    ///
825    /// - `None`: the field is absent.
826    /// - `Some(Ok(content))`: decoded content, from either of the codec's
827    ///   encodings — a stored string and an already-canonical content object read
828    ///   back the same.
829    /// - `Some(Err(_))`: the field is present but decodes under neither (e.g. a
830    ///   bare number an opaque `store_field` wrote).
831    ///
832    /// A `Document` carries no schema, so the caller names the codec the field is
833    /// declared at; the schema-bound door is
834    /// [`TypedReader::get_content`](crate::reader::TypedReader::get_content).
835    #[cfg(test)]
836    pub(crate) fn field_content(
837        &self,
838        name: &str,
839        codec: Codec,
840    ) -> Option<Result<Content, ContentDecodeError>> {
841        Some(codec.decode_field(self.payload.get(name)?.as_json()))
842    }
843
844    /// The text projection of a content-valued field (`project ∘ decode`),
845    /// carrying [`field_content`](Card::field_content)'s `None`/`Ok`/`Err`.
846    #[cfg(test)]
847    pub(crate) fn field_text(
848        &self,
849        name: &str,
850        codec: Codec,
851    ) -> Option<Result<String, ContentDecodeError>> {
852        Some(
853            codec
854                .decode_field(self.payload.get(name)?.as_json())
855                .map(|c| codec.project(&c)),
856        )
857    }
858}
859
860/// A parsed, per-kind **seed overlay**: the sparse fields (and optional body) a
861/// newly-added card of a given kind starts with. Built from a `$seed[<kind>]`
862/// entry of the main card's [`Card::seed`] map, or a kind's `seed:` in
863/// `Quill.yaml`, via [`SeedOverlay::from_json`], and committed by
864/// [`crate::quill::Quill::seed_card`], a document's overlay replacing its
865/// kind's seed whole.
866/// The reserved inner key `$body` carries the body override; every other user
867/// field becomes an entry, while any other `$`-prefixed key is reserved and
868/// dropped. A present-null entry is kept, and `seed_card` reads it as absent.
869/// Serializes back to the `$seed[<kind>]` shape, `$body` last.
870#[derive(Debug, Clone, PartialEq, Default)]
871pub struct SeedOverlay {
872    /// Field-value overrides, keyed by field name.
873    pub fields: indexmap::IndexMap<String, crate::value::QuillValue>,
874    /// Body override, when the overlay declares a `$body` string.
875    pub body: Option<String>,
876}
877
878impl SeedOverlay {
879    /// Parse an overlay from a `$seed[<kind>]` JSON value, `None` when it is not
880    /// a mapping:
881    /// `doc.main().seed().and_then(|m| m.get(kind)).and_then(SeedOverlay::from_json)`.
882    pub fn from_json(value: &serde_json::Value) -> Option<Self> {
883        value.as_object().map(Self::from_json_map)
884    }
885
886    /// A non-string `$body` is ignored: no body override.
887    fn from_json_map(map: &serde_json::Map<String, serde_json::Value>) -> Self {
888        let mut fields = indexmap::IndexMap::new();
889        let mut body = None;
890        for (key, value) in map {
891            if key == "$body" {
892                if let Some(s) = value.as_str() {
893                    body = Some(s.to_string());
894                }
895            } else if key.starts_with('$') {
896                continue;
897            } else {
898                fields.insert(
899                    key.clone(),
900                    crate::value::QuillValue::from_json(value.clone()),
901                );
902            }
903        }
904        SeedOverlay { fields, body }
905    }
906}
907
908impl Serialize for SeedOverlay {
909    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
910        use serde::ser::SerializeMap;
911        let len = self.fields.len() + usize::from(self.body.is_some());
912        let mut map = serializer.serialize_map(Some(len))?;
913        for (key, value) in &self.fields {
914            map.serialize_entry(key, value.as_json())?;
915        }
916        if let Some(body) = &self.body {
917            map.serialize_entry("$body", body)?;
918        }
919        map.end()
920    }
921}
922
923/// A fully-parsed Quillmark document. Serde routes through [`StoredDocument`].
924///
925/// Parse-time warnings are *not* document state: they ride out-of-band on
926/// [`Parsed`] from [`Document::parse`], the single owner. Equality and the
927/// storage DTO therefore cover only structural content (`main` and `cards`).
928#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
929#[serde(into = "StoredDocument", try_from = "StoredDocument")]
930pub struct Document {
931    main: Card,
932    cards: Vec<Card>,
933}
934
935impl Document {
936    /// Create a blank document: a main card carrying only `$quill`, an empty
937    /// body, and no composable cards. The programmatic blank canvas: every
938    /// schema field is absent and resolves at render time (`default`, else
939    /// the field's blank), so nothing the caller did not set reaches the
940    /// output. For one card per declared kind, use `Quill::seed_document`.
941    pub fn new(quill: QuillReference) -> Self {
942        let mut payload = Payload::new();
943        payload.set_quill(quill);
944        // Parsed main cards always carry `$kind: main` (the parser normalizes
945        // it in); match that shape so a blank document round-trips equal.
946        payload.set_kind("main");
947        Self {
948            main: Card::from_parts(payload, Content::empty()),
949            cards: Vec::new(),
950        }
951    }
952
953    /// Create a `Document` from a pre-built main card and composable cards.
954    /// `main` must carry `$quill`; composable cards must carry `$kind` and must
955    /// not carry `$quill` or `$seed`.
956    ///
957    /// The invariants are `debug_assert`s because no caller can break them.
958    /// This is crate-internal; every public door that places a card gates it
959    /// ([`Unchecked::insert_card`](crate::document::Unchecked::insert_card),
960    /// parse, and
961    /// `TryFrom<StoredDocument>` for external data, which checks all three and
962    /// returns `StorageError::Malformed`), and a placed card is reachable only
963    /// as a [`CardMut`], which carries no whole-card assignment.
964    pub(crate) fn from_main_and_cards(main: Card, mut cards: Vec<Card>) -> Self {
965        debug_assert!(main.quill().is_some(), "main card must carry `$quill`");
966        debug_assert!(
967            cards.iter().all(|c| c.kind().is_some()),
968            "composable cards must carry `$kind`"
969        );
970        debug_assert!(
971            cards.iter().all(|c| c.quill().is_none()),
972            "composable cards must not carry `$quill`"
973        );
974        debug_assert!(
975            cards.iter().all(|c| c.seed().is_none()),
976            "composable cards must not carry `$seed`"
977        );
978        card_id::settle(&mut cards, &std::collections::HashSet::new());
979        Self { main, cards }
980    }
981
982    /// Read a stored row ([`StoredDocument`] JSON) into a [`Parsed`]: the
983    /// [`Document`], and a [`noncanonical_read`] warning at each body or field
984    /// whose content value the read rewrote to its canonical form. Fails as
985    /// deserializing a `Document` from `json` fails.
986    pub fn from_stored(json: &str) -> Result<Parsed, serde_json::Error> {
987        let stored: StoredDocument = serde_json::from_str(json)?;
988        dto::from_stored(stored).map_err(serde::de::Error::custom)
989    }
990
991    /// Parse card-yaml Markdown into a [`Parsed`]: the [`Document`] plus any
992    /// non-fatal warnings. The single parse entry; a caller that wants only the
993    /// document writes `Document::parse(md)?.document`. Errors on malformed
994    /// YAML, a missing root `$quill`, an over-size input, and the other
995    /// [`ParseError`] variants.
996    #[doc(alias = "from_markdown")]
997    pub fn parse(markdown: &str) -> Result<Parsed, ParseError> {
998        let mut parsed = Self::parse_unsettled(markdown)?;
999        let reserved = std::collections::HashSet::new();
1000        card_id::settle_reporting(&mut parsed.document.cards, &reserved, &mut parsed.warnings);
1001        Ok(parsed)
1002    }
1003
1004    /// [`parse`](Self::parse) with each card holding the `$id` it spells, or
1005    /// none, for a revise to settle against the ids it started from.
1006    pub(crate) fn parse_unsettled(markdown: &str) -> Result<Parsed, ParseError> {
1007        assemble::decompose_with_warnings(markdown, import_markdown)
1008            .map(|(document, warnings, _)| Parsed { document, warnings })
1009    }
1010
1011    /// [`parse_unsettled`](Self::parse_unsettled) for a revise: each body's
1012    /// `qm-island` tokens drop silently, the revise resolving them against the
1013    /// stored card it aligns the body's card to, and each body's markdown is
1014    /// kept for it.
1015    pub(crate) fn parse_revising(markdown: &str) -> Result<Revising, ParseError> {
1016        let (document, warnings, bodies) = assemble::decompose_with_warnings(
1017            markdown,
1018            quillmark_content::markdown::from_markdown_unresolved,
1019        )?;
1020        Ok(Revising {
1021            parsed: Parsed { document, warnings },
1022            bodies,
1023        })
1024    }
1025
1026    pub fn main(&self) -> &Card {
1027        &self.main
1028    }
1029
1030    pub fn main_mut(&mut self) -> CardMut<'_> {
1031        CardMut::new(&mut self.main)
1032    }
1033
1034    /// The root block's `$quill` reference, which parse validates present.
1035    pub fn quill_reference(&self) -> QuillReference {
1036        self.main
1037            .quill()
1038            .cloned()
1039            .expect("root block's $quill is validated at parse time")
1040    }
1041
1042    pub fn cards(&self) -> &[Card] {
1043        &self.cards
1044    }
1045
1046    /// A single composable card by index: the immutable twin of
1047    /// [`card_mut`](Document::card_mut). `None` when out of range.
1048    pub fn card(&self, index: usize) -> Option<&Card> {
1049        self.cards.get(index)
1050    }
1051
1052    /// The index of the composable card whose `$id` is `id`.
1053    pub fn card_index(&self, id: &str) -> Option<usize> {
1054        self.cards.iter().position(|card| card.id() == Some(id))
1055    }
1056
1057    /// A composable card by its `$id`, which it keeps wherever it moves.
1058    pub fn card_by_id(&self, id: &str) -> Option<&Card> {
1059        self.card_index(id).map(|index| &self.cards[index])
1060    }
1061
1062    pub(crate) fn main_card_mut(&mut self) -> &mut Card {
1063        &mut self.main
1064    }
1065
1066    pub(crate) fn cards_vec_mut(&mut self) -> &mut Vec<Card> {
1067        &mut self.cards
1068    }
1069
1070    /// Serialize to the JSON wire shape consumed by backend plates. This is
1071    /// the **only** place in `quillmark-core` that produces this shape:
1072    ///
1073    /// ```json
1074    /// {
1075    ///   "$quill": "<ref>",
1076    ///   "$body": { "text": "…", "blocks": [...], "containers": [...], "marks": [...], "islands": [...] },
1077    ///   "$cards": [{ "$kind": "<tag>", "$body": <content>, "<field>": <value>, ... }],
1078    ///   "<field>": <value>, ...
1079    /// }
1080    /// ```
1081    ///
1082    /// `$body` (global and per-card) is canonical Content-JSON: the content as
1083    /// a nested object, not a markdown string. Richtext payload fields likewise
1084    /// cross as content objects (committed at coercion time).
1085    ///
1086    /// `$`-prefixed keys carry document-level metadata (quill ref, body
1087    /// text, card list, card kind). User payload fields stay flat at the
1088    /// root: they cannot collide with `$` keys because user field names are
1089    /// never `$`-prefixed (they match `[A-Za-z_][A-Za-z0-9_]*`).
1090    ///
1091    /// Body presence is the caller's decision: the root carries `$body` iff
1092    /// `main_body`, and card *i* iff `card_bodies` is `None` (all present) or
1093    /// `card_bodies[i]` holds. The schema-gated render plate
1094    /// (`QuillConfig::compile_data`) passes the body-enabled bit it already
1095    /// resolved per card, so a card whose kind enables no body carries no
1096    /// `$body`, and the decision is never re-derived from the serialized plate.
1097    /// `Document` stays schema-free: it receives the decision, not a schema.
1098    pub(crate) fn to_plate_json_gated(
1099        &self,
1100        main_body: bool,
1101        card_bodies: Option<&[bool]>,
1102    ) -> serde_json::Value {
1103        let mut map = serde_json::Map::new();
1104
1105        map.insert(
1106            "$quill".to_string(),
1107            serde_json::Value::String(self.quill_reference().to_string()),
1108        );
1109
1110        // The seam carries the body as canonical Content-JSON: a nested content
1111        // object, byte-identical to `to_canonical_json`, never a lossy markdown
1112        // string. The markdown projection is `body_markdown`.
1113        if main_body {
1114            map.insert("$body".to_string(), self.main.body().to_value());
1115        }
1116
1117        let cards_array: Vec<serde_json::Value> = self
1118            .cards
1119            .iter()
1120            .enumerate()
1121            .map(|(i, card)| {
1122                let mut card_map = serde_json::Map::new();
1123                if let Some(kind) = card.kind() {
1124                    card_map.insert(
1125                        "$kind".to_string(),
1126                        serde_json::Value::String(kind.to_string()),
1127                    );
1128                }
1129                // `$body` iff the caller's schema defines a body for this card.
1130                if card_bodies.map_or(true, |f| f.get(i).copied().unwrap_or(true)) {
1131                    card_map.insert("$body".to_string(), card.body().to_value());
1132                }
1133                for (key, value) in card.payload.iter() {
1134                    card_map.insert(key.clone(), value.as_json().clone());
1135                }
1136                serde_json::Value::Object(card_map)
1137            })
1138            .collect();
1139
1140        map.insert("$cards".to_string(), serde_json::Value::Array(cards_array));
1141
1142        for (key, value) in self.main.payload.iter() {
1143            map.insert(key.clone(), value.as_json().clone());
1144        }
1145
1146        serde_json::Value::Object(map)
1147    }
1148}