Skip to main content

sokf_core/include/
expand.rs

1//! This module computes the expected content of every include block and
2//! definition block (`SOKF_VALIDATION_15`). It expands each file after the
3//! files that it includes, so each include block holds the expected content of
4//! its target, never the target's text on disk. `sokf validate --fix` writes
5//! this content into each block, and validation compares each block with it.
6
7use std::{
8    collections::{BTreeSet, HashMap, HashSet},
9    fmt::Write as _,
10};
11
12use super::{fence, graph, region};
13use crate::{
14    Body, Model, RepoPath, Segments,
15    compare::{Layout, Pair, Source},
16    markdown::{self, IncludeTarget, Link, sokf_label},
17    model::{KeyIndex, Query, keys},
18    source,
19};
20
21/// A `DefinitionEntry` is one line of a definition block.
22#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
23pub struct DefinitionEntry {
24    /// `label` holds the label with its `sokf:` prefix.
25    pub label: String,
26    /// `path` holds the path of the target.
27    pub path: RepoPath,
28    /// `slug` holds the `#slug` of the target when the fragment identifies a
29    /// heading or a key that a heading captures. Otherwise it is `None`.
30    pub slug: Option<String>,
31}
32
33/// An `Expected` holds what every generated block should hold.
34#[derive(Debug, Clone, Default)]
35pub struct Expected {
36    /// This map holds the interior of each include block, keyed by file and
37    /// by the line of its open marker. The value is `None` when the interior
38    /// can't be regenerated.
39    pub includes: HashMap<(RepoPath, usize), Option<String>>,
40    /// This map holds the source of each include block that holds a file
41    /// in a fence, keyed as `includes` is. An include block of a document's
42    /// body has no entry.
43    pub fences: HashMap<(RepoPath, usize), Fenced>,
44    /// This map holds the path from the root, as same-same reads it, of the
45    /// document whose body each include block of a body holds, keyed as
46    /// `includes` is.
47    pub bodies: HashMap<(RepoPath, usize), String>,
48    /// This map holds the definition entries of each file. The list is empty
49    /// when the file needs no block, and the value is `None` when a label
50    /// doesn't resolve.
51    pub definitions: HashMap<RepoPath, Option<Vec<DefinitionEntry>>>,
52    /// `cycles` lists each include cycle as the files on it.
53    pub cycles: Vec<Vec<RepoPath>>,
54    /// `on_cycle` holds every file that lies on an include cycle.
55    pub on_cycle: HashSet<RepoPath>,
56    /// `layout` records which blocks that differ from their expected text
57    /// same-same finds the same (CLI-4_AC-45).
58    pub layout: Layout,
59}
60
61/// A `Fenced` is the source of an include block that holds a file, whole or
62/// one region of it, in a fence.
63#[derive(Debug, Clone, PartialEq, Eq)]
64pub struct Fenced {
65    /// The included file.
66    pub path: RepoPath,
67    /// Whether the block includes a region of the file.
68    pub region: bool,
69    /// The lines of the file that the code of the fence holds.
70    pub lines: Vec<u32>,
71    /// Those lines as one run of whole lines, where they are one.
72    pub range: Option<std::ops::Range<u32>>,
73}
74
75impl Expected {
76    /// `include` returns the expected interior of the include block that
77    /// opens at `line` in `path`, when the interior can be regenerated.
78    pub fn include(&self, path: &RepoPath, line: usize) -> Option<&str> {
79        self.includes
80            .get(&(path.clone(), line))
81            .and_then(|i| i.as_deref())
82    }
83
84    /// `include_pair` returns the pair of texts that same-same compares
85    /// for the include block that opens at `line` in `path` and holds
86    /// `content`, when the block differs from its expected interior. An
87    /// include of a file compares the code inside the fence under the path
88    /// of its source, a region of it as a part of a file, and an
89    /// include of a body compares the whole interior under the path of the
90    /// included document (CLI-4_AC-113). It returns `None` when the
91    /// block has no expected interior, holds it, or holds a fence of another
92    /// form.
93    // sokf-implements: CLI-4_AC-47
94    // sokf-implements: CLI-4_AC-113
95    pub fn include_pair(&self, path: &RepoPath, line: usize, content: &str) -> Option<Pair> {
96        let expected = self.include(path, line)?;
97        if expected == content {
98            return None;
99        }
100        let key = (path.clone(), line);
101        let Some(fenced) = self.fences.get(&key) else {
102            return Some(Pair {
103                path: path.clone(),
104                name: self.bodies.get(&key)?.clone(),
105                fragment: false,
106                expected: expected.into(),
107                actual: content.into(),
108                source: None,
109            });
110        };
111        let (open, close) = fence_ends(expected)?;
112        let code = |text: &str| -> Option<String> {
113            let inner = text.strip_prefix(open)?.strip_suffix(close)?;
114            Some(inner.to_string())
115        };
116        Some(Pair {
117            path: path.clone(),
118            name: crate::compare::name_of(&fenced.path),
119            fragment: fenced.region,
120            expected: code(expected)?,
121            actual: code(content)?,
122            source: Some(Source {
123                path: fenced.path.clone(),
124                range: fenced.range.clone().filter(|_| fenced.region),
125                lines: fenced.lines.clone(),
126            }),
127        })
128    }
129
130    /// `include_current` returns whether the include block that opens at
131    /// `line` in `path` and holds `content` is current: whether it holds its
132    /// expected interior, or same-same finds the two the same. It returns
133    /// `None` when the block has no expected interior.
134    // sokf-implements: CLI-4_AC-44
135    // sokf-implements: CLI-4_AC-45
136    pub fn include_current(&self, path: &RepoPath, line: usize, content: &str) -> Option<bool> {
137        let expected = self.include(path, line)?;
138        Some(
139            expected == content
140                || self
141                    .include_pair(path, line, content)
142                    .is_some_and(|p| self.layout.same(&p)),
143        )
144    }
145
146    /// `include_stale` returns the warning that the formatter failed on the
147    /// texts of the stale include block that opens at `line` in `path`,
148    /// holds `content`, and whose target is written as `written`, when it
149    /// did, and the message of its finding.
150    pub fn include_stale(
151        &self,
152        path: &RepoPath,
153        line: usize,
154        content: &str,
155        written: &str,
156    ) -> (Option<crate::Finding>, String) {
157        let Some(p) = self.include_pair(path, line, content) else {
158            return (None, crate::compare::stale_message(written, None, None));
159        };
160        (
161            self.layout.warning(&p),
162            crate::compare::stale_message(
163                written,
164                p.source.as_ref().map(|s| &s.path),
165                self.layout.line(&p),
166            ),
167        )
168    }
169}
170
171/// `fence_ends` returns the line that opens the fence of an include
172/// interior, after the interior's first blank line, and the text that
173/// closes it, from the fence to the interior's end.
174fn fence_ends(interior: &str) -> Option<(&str, &str)> {
175    let rest = interior.strip_prefix('\n')?;
176    let ticks = rest.len() - rest.trim_start_matches('`').len();
177    let open_len = 1 + rest.find('\n')? + 1;
178    let close_len = ticks + 2;
179    (ticks >= 3 && open_len + close_len <= interior.len()).then(|| {
180        (
181            &interior[..open_len],
182            &interior[interior.len() - close_len..],
183        )
184    })
185}
186
187/// `interior` returns the text that goes between the markers of an include
188/// block that holds `body`. The `body` has no trailing newline.
189fn interior(body: &str) -> String {
190    if body.is_empty() {
191        "\n".to_string()
192    } else {
193        format!("\n{body}\n\n")
194    }
195}
196
197/// `render_definitions` returns the text of the definition block for
198/// `entries`, or an empty string when there are no entries.
199// sokf-implements: SOKF_FORMAT_79
200// sokf-implements: SOKF_FORMAT_80
201// sokf-implements: SOKF_FORMAT_81
202pub fn render_definitions(entries: &[DefinitionEntry]) -> String {
203    if entries.is_empty() {
204        return String::new();
205    }
206    let mut out = String::from("<!-- sokf:links -->\n\n");
207    for e in entries {
208        let _ = write!(out, "[{}]: {}", e.label, e.path);
209        if let Some(slug) = &e.slug {
210            out.push('#');
211            out.push_str(slug);
212        }
213        out.push('\n');
214    }
215    out
216}
217
218/// `expected` computes the expected content of every generated block.
219// sokf-implements: SOKF_FORMAT_85
220pub fn expected(model: &Model, keys: &KeyIndex) -> Expected {
221    expected_for(model, keys, None)
222}
223
224/// `expected_for` computes the expected content of the generated blocks of
225/// the files in `only`, or of every file when `only` is `None`. It expands the
226/// include targets of those files too. It reads the body of a summarised
227/// document from the disk when a file that depends on it needs the body
228/// (CACHE-3_AC-1).
229// sokf-implements: SOKF_FORMAT_85
230// sokf-implements: SOKF_VALIDATION_15
231// sokf-implements: CACHE-3_AC-1
232pub fn expected_for(model: &Model, keys: &KeyIndex, only: Option<&BTreeSet<RepoPath>>) -> Expected {
233    // The nodes to expand are the wanted files and every file that they
234    // include, directly or through another file.
235    let (g, needed) = graph::graph_for(model, only);
236    let o = graph::order(&g);
237    let mut expander = Expander {
238        model,
239        keys,
240        out: Expected {
241            cycles: o.cycles.clone(),
242            on_cycle: o.cycles.iter().flatten().cloned().collect(),
243            ..Expected::default()
244        },
245        expansions: HashMap::new(),
246    };
247    let cycle_nodes: Vec<usize> = (0..g.nodes.len())
248        .filter(|i| expander.out.on_cycle.contains(&g.nodes[*i]))
249        .collect();
250    for &node in o.sorted.iter().chain(cycle_nodes.iter()) {
251        if needed.as_ref().is_some_and(|n| !n.contains(&node)) {
252            continue;
253        }
254        expander.expand_file(&g.nodes[node]);
255    }
256    expander.add_definitions(only);
257    expander.out
258}
259
260/// An `Expander` holds what `expected_for` builds as it expands the files,
261/// each after the files that it includes.
262struct Expander<'a> {
263    /// The model.
264    model: &'a Model,
265    /// The captured keys.
266    keys: &'a KeyIndex,
267    /// The expected content so far.
268    out: Expected,
269    /// This map holds the expanded body of each document by path, or `None`
270    /// when the body can't be computed.
271    expansions: HashMap<RepoPath, Option<String>>,
272}
273
274impl Expander<'_> {
275    /// `expand_file` computes the expected interior of each include block of
276    /// the file at `path`, and the file's expanded body when the file is a
277    /// document.
278    fn expand_file(&mut self, path: &RepoPath) {
279        let model = self.model;
280        model.watch(path);
281        let (knowledge, segments, body, body_text, body_line, is_document) =
282            match model.by_path(path) {
283                Some(crate::Located::Document(k, doc)) => parts_of(k, doc),
284                Some(crate::Located::Schema(k, schema)) => parts_of(k, &schema.doc),
285                Some(crate::Located::Additional(file)) => (
286                    graph::knowledge_of_additional(model, file),
287                    &file.segments,
288                    &file.body,
289                    file.source.text.as_str(),
290                    1,
291                    false,
292                ),
293                _ => {
294                    model.unwatch();
295                    return;
296                }
297            };
298        let mut all_computable = true;
299        for block in &segments.regions {
300            let expected = self.block_interior(knowledge, &block.target);
301            if expected.is_none() {
302                all_computable = false;
303            }
304            let key = (path.clone(), block.open_line);
305            let expected = expected.map(|(interior, kind)| {
306                match kind {
307                    Kind::File(fenced) => self.out.fences.insert(key.clone(), fenced).map(drop),
308                    Kind::Body(name) => self.out.bodies.insert(key.clone(), name).map(drop),
309                };
310                interior
311            });
312            self.out.includes.insert(key, expected);
313        }
314        if is_document {
315            let expansion = if all_computable && !self.out.on_cycle.contains(path) {
316                Some(expand(
317                    body_text, body_line, segments, body, path, &self.out,
318                ))
319            } else {
320                None
321            };
322            self.expansions.insert(path.clone(), expansion);
323        }
324        model.unwatch();
325    }
326
327    /// `block_interior` returns the expected interior of an include block
328    /// whose target is `target`, in a file of the knowledge `knowledge`, or
329    /// `None` when the interior can't be computed. With the interior, it
330    /// returns the source of the file that a fence holds, or the file name
331    /// of the document whose body it holds.
332    fn block_interior(&self, knowledge: Option<usize>, target: &str) -> Option<(String, Kind)> {
333        let model = self.model;
334        match &IncludeTarget::parse(target) {
335            IncludeTarget::Document {
336                store,
337                id,
338                fragment,
339            } => {
340                let target = knowledge.and_then(|k| model.document_in(k, store.as_deref(), id));
341                match target {
342                    None => None,
343                    Some((target_k, target))
344                        if graph::includes_body(model, &target.path, fragment.as_deref()) =>
345                    {
346                        let name = crate::compare::name_of(&target.path);
347                        Some(target)
348                            .filter(|t| !self.out.on_cycle.contains(&t.path))
349                            .and_then(|t| {
350                                model.note(Query::Body(t.path.clone()));
351                                self.expansions.get(&t.path).cloned().flatten()
352                            })
353                            .map(|body| match knowledge {
354                                Some(k) if k != target_k => {
355                                    requalify(model, self.keys, target_k, k, &body)
356                                }
357                                _ => body,
358                            })
359                            .map(|body| (interior(&body), Kind::Body(name)))
360                    }
361                    // Otherwise the block holds the content of the
362                    // sidecar's asset, whole or one region of it. An
363                    // include block with a path holds the content of a
364                    // file in the same way (FORMAT-2_AC-5). A plain
365                    // document has no asset, so its block has no
366                    // expected interior.
367                    // sokf-implements: FORMAT-2_AC-5
368                    Some((_, target)) => model
369                        .asset_of(&target.path)
370                        .and_then(|(_, a)| asset_interior(model, &a.path, fragment.as_deref())),
371                }
372            }
373            IncludeTarget::File { path, region } => {
374                file_interior(model, knowledge, path, region.as_deref())
375            }
376        }
377    }
378
379    /// `add_definitions` computes the definition entries of each document,
380    /// schema, and additional file in `only`, or of every file when `only`
381    /// is `None`.
382    // sokf-implements: SOKF_FORMAT_78
383    fn add_definitions(&mut self, only: Option<&BTreeSet<RepoPath>>) {
384        let model = self.model;
385        // Each definition block lists every resolved `sokf:` label in the body
386        // and in each include interior.
387        let documents = model
388            .documents_and_schemas()
389            .map(|(k, d)| (Some(k), &d.path, &d.body.links, &d.segments));
390        let additional = model.additional.iter().map(|f| {
391            (
392                graph::knowledge_of_additional(model, f),
393                &f.path,
394                &f.body.links,
395                &f.segments,
396            )
397        });
398        for (k, path, links, segments) in documents.chain(additional) {
399            let Some(k) = k else { continue };
400            if only.is_some_and(|o| !o.contains(path)) {
401                continue;
402            }
403            model.watch(path);
404            let entries = definition_entries(model, self.keys, k, path, links, segments, &self.out);
405            model.unwatch();
406            self.out.definitions.insert(path.clone(), entries);
407        }
408    }
409}
410
411/// `Parts` holds what the expansion of one file reads: its knowledge, its
412/// segments, its body, the text of its body, the line where its body starts,
413/// and whether the file is a document.
414type Parts<'a> = (Option<usize>, &'a Segments, &'a Body, &'a str, usize, bool);
415
416/// `parts_of` returns the parts of a document of the knowledge `k`.
417fn parts_of(k: usize, doc: &crate::Document) -> Parts<'_> {
418    (
419        Some(k),
420        &doc.segments,
421        &doc.body,
422        doc.body_text(),
423        doc.body_line,
424        true,
425    )
426}
427
428/// `file_interior` returns the interior of an include block whose target is
429/// a path. It returns an interior only when both of these hold:
430///
431/// - The path resolves to a repository file that is neither a document of
432///   any store nor an additional file of the including file's `knowledge`
433///   (`SOKF_FORMAT_88`, `SOKF_FORMAT_89`).
434/// - The region can be extracted from that file.
435///
436/// Otherwise it returns `None`. A path that points to an asset still gets an
437/// interior. Validation reports a finding for that path, but the path and the
438/// id of the asset's sidecar document refer to the same content. So in one
439/// pass `--fix` replaces the path with the id and writes this interior.
440fn file_interior(
441    model: &Model,
442    knowledge: Option<usize>,
443    path: &str,
444    region: Option<&str>,
445) -> Option<(String, Kind)> {
446    let rp = RepoPath::parse(path)?;
447    if model.id_at(&rp).is_some() || model.is_materialized_in(knowledge, &rp) {
448        return None;
449    }
450    asset_interior(model, &rp, region)
451}
452
453/// `asset_interior` returns the interior for the file at `path`, whole or one
454/// region of it, in a fenced code block, with where the code lies in the
455/// file.
456fn asset_interior(model: &Model, path: &RepoPath, region: Option<&str>) -> Option<(String, Kind)> {
457    if !model.exists(path) {
458        return None;
459    }
460    model.note(Query::Body(path.clone()));
461    let text = source::load_text(&model.tree.root, path).ok()?;
462    let extraction = region::extract_lines(&text, region).ok()??;
463    let fenced = Fenced {
464        path: path.clone(),
465        region: region.is_some(),
466        range: extraction.range(),
467        lines: extraction.lines,
468    };
469    Some((
470        interior(&fence::fenced(&extraction.text, path)),
471        Kind::File(fenced),
472    ))
473}
474
475/// A `Kind` says what an include block holds: a file in a fence, or the
476/// body of the document of a path from the root.
477enum Kind {
478    File(Fenced),
479    Body(String),
480}
481
482/// `expand` returns the expanded body of a document. It leaves out the
483/// definition block, the generated anchors, and the include markers. It
484/// replaces each include block with its expected interior. When the expected
485/// interior can't be computed, it keeps the interior on disk instead. Then it
486/// trims the blank lines at both ends. An anchor belongs to the document that
487/// captures its key, so a copy carries no anchors (`SOKF_FORMAT_83`).
488fn expand(
489    body_text: &str,
490    body_line: usize,
491    segments: &Segments,
492    body: &Body,
493    path: &RepoPath,
494    out: &Expected,
495) -> String {
496    let mut lines: Vec<String> = Vec::new();
497    let mut skip_until: Option<usize> = None;
498    let mut after_anchors = false;
499    for (i, line) in body_text.lines().enumerate() {
500        let file_line = body_line + i;
501        if let Some(until) = skip_until {
502            if file_line <= until {
503                continue;
504            }
505            skip_until = None;
506        }
507        // The loop drops a line that holds only anchors, and the blank line
508        // after it.
509        if body.anchors.iter().any(|a| a.line == file_line && a.alone) {
510            after_anchors = true;
511            continue;
512        }
513        if std::mem::take(&mut after_anchors) && line.trim().is_empty() {
514            continue;
515        }
516        let line = &*body.clean_line(file_line, line);
517        if segments
518            .definition
519            .as_ref()
520            .is_some_and(|d| file_line >= d.line)
521        {
522            break;
523        }
524        if let Some(block) = segments.regions.iter().find(|b| b.open_line == file_line) {
525            let content = out.include(path, block.open_line).unwrap_or(&block.content);
526            lines.extend(content.lines().map(str::to_string));
527            skip_until = Some(block.close_line);
528            continue;
529        }
530        lines.push(line.to_string());
531    }
532    let start = lines
533        .iter()
534        .position(|l| !l.trim().is_empty())
535        .unwrap_or(lines.len());
536    let end = lines
537        .iter()
538        .rposition(|l| !l.trim().is_empty())
539        .map_or(0, |i| i + 1);
540    if start >= end {
541        return String::new();
542    }
543    lines[start..end].join("\n")
544}
545
546/// `definition_entries` returns the definition entries of one file: the
547/// labels that its own body cites, and the labels inside each include
548/// interior. It lists each entry as `--fix` writes it in the same pass: a
549/// fragment written as the text of a key becomes the key's slug, a label
550/// takes its canonical store prefix, and a path link to a document or an
551/// asset of any store becomes its canonical label (`SOKF_VALIDATION_24`,
552/// `SOKF_VALIDATION_32`). It returns `None` when a label doesn't resolve.
553// sokf-implements: SOKF_FORMAT_80
554// sokf-implements: SOKF_FORMAT_81
555// sokf-implements: FORMAT-2_AC-2
556// sokf-implements: FORMAT-2_AC-3
557fn definition_entries(
558    model: &Model,
559    keys: &KeyIndex,
560    knowledge: usize,
561    path: &RepoPath,
562    links: &[Link],
563    segments: &Segments,
564    out: &Expected,
565) -> Option<Vec<DefinitionEntry>> {
566    let mut labels: Vec<String> = Vec::new();
567    for link in links {
568        if let Some(label) = sokf_label(link) {
569            labels.push(label);
570        } else if let Some((label, true)) = path_link_label(model, keys, knowledge, path, link) {
571            labels.push(label);
572        }
573    }
574    for block in &segments.regions {
575        let content = out.include(path, block.open_line).unwrap_or(&block.content);
576        let inner_segments = Segments::default();
577        let body = markdown::parse(content, 1, &inner_segments);
578        labels.extend(body.links.iter().filter_map(sokf_label));
579    }
580    labels.sort();
581    labels.dedup();
582    let mut entries = Vec::new();
583    for label in labels {
584        let parts = markdown::label_parts(&label)?;
585        let (resolved, slug) = keys::resolve_slugged(model, keys, knowledge, parts);
586        let resolved = resolved.ok()?;
587        let parts = parts.with_fragment(slug.as_deref().or(parts.fragment));
588        let label = model
589            .canonical_label(knowledge, resolved.knowledge, parts.id, parts.fragment)
590            .unwrap_or_else(|| label.clone());
591        // A bare label refers to the content, which for a sidecar is its
592        // asset (FORMAT-2_AC-2). A label with any fragment, even an empty
593        // one, refers to the file itself.
594        let path = if parts.fragment.is_none() {
595            model.content_path(&resolved.path)
596        } else {
597            resolved.path
598        };
599        entries.push(DefinitionEntry {
600            label,
601            path,
602            slug: resolved.slug,
603        });
604    }
605    entries.sort();
606    entries.dedup();
607    Some(entries)
608}
609
610/// `path_link_label` returns the canonical label of a path link in `path`,
611/// when the link points to a document or an asset of any store. When the
612/// fragment is the text of a key, the label uses the key's slug instead. It
613/// also returns whether `--fix` writes the label. `--fix` writes the label of
614/// an inline link when the label resolves (`SOKF_VALIDATION_24`). It returns `None` for a
615/// link to any other file, for a link that ends with `/`, which names only a
616/// directory (`SOKF_FORMAT_157`), and for an image link whose target is not an
617/// asset.
618pub fn path_link_label(
619    model: &Model,
620    keys: &KeyIndex,
621    knowledge: usize,
622    path: &RepoPath,
623    link: &Link,
624) -> Option<(String, bool)> {
625    let (target, fragment) = match &link.target {
626        markdown::LinkTarget::Repo {
627            path,
628            fragment,
629            dir: false,
630        } => (path.clone(), fragment.as_deref()),
631        markdown::LinkTarget::Relative { target, fragment } => {
632            (path.resolve_relative(target)?, fragment.as_deref())
633        }
634        _ => return None,
635    };
636    // An image refers to an asset, so a link to a document written as an
637    // image gets no label (SOKF_FORMAT_67).
638    if link.is_image && model.asset_at(&target).is_none() {
639        return None;
640    }
641    let label = model.path_label(knowledge, &target, fragment)?;
642    let parts = markdown::label_parts(&label)?;
643    let (label, resolves) = match keys::resolve_slugged(model, keys, knowledge, parts) {
644        (Ok(_), None) => (label, true),
645        (Ok(r), Some(slug)) => {
646            match model.canonical_label(knowledge, r.knowledge, parts.id, Some(&slug)) {
647                Some(slugged) => (slugged, true),
648                None => (label, false),
649            }
650        }
651        (Err(_), _) => (label, false),
652    };
653    Some((label, resolves && link.inline.is_some()))
654}
655
656/// `requalify` returns `body`, the expanded body of a document of the store
657/// `from`, with each `sokf:` label rewritten the way a document of the store
658/// `to` would write it. The rewrite makes an included copy mean what its
659/// source means (format specification ยง9.3).
660fn requalify(model: &Model, keys: &KeyIndex, from: usize, to: usize, body: &str) -> String {
661    let parsed = markdown::parse(body, 1, &Segments::default());
662    // The loop respells each label only on the lines of its link and never
663    // in a code span, so an example of a label written as code stays as
664    // written.
665    let mut renames: Vec<((usize, usize), String, String)> = Vec::new();
666    for link in &parsed.links {
667        let (Some(label), Some(parts)) = (sokf_label(link), keys::Label::of(&link.target)) else {
668            continue;
669        };
670        let Ok(resolved) = keys::resolve(model, keys, from, parts) else {
671            continue;
672        };
673        if let Some(new) = model.canonical_label(to, resolved.knowledge, parts.id, parts.fragment)
674            && new != label
675        {
676            renames.push((link.lines(), format!("[{label}]"), format!("[{new}]")));
677        }
678    }
679    renames.sort();
680    renames.dedup();
681    let mut lines: Vec<String> = body.lines().map(str::to_string).collect();
682    for ((first, last), old, new) in renames {
683        for line in first..=last {
684            let Some(text) = lines.get_mut(line - 1) else {
685                continue;
686            };
687            let at: Vec<usize> = text
688                .match_indices(old.as_str())
689                .map(|(pos, _)| pos)
690                .filter(|&pos| !parsed.in_code_span(line, pos))
691                .collect();
692            for pos in at.into_iter().rev() {
693                text.replace_range(pos..pos + old.len(), &new);
694            }
695        }
696    }
697    lines.join("\n")
698}
699
700#[cfg(test)]
701mod tests;