documented-toml 0.4.0

Format-preserving merge of a person's TOML configuration with the documented defaults an application ships.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
//! The merge itself: what runs it, and what comes out.

use std::collections::BTreeSet;

use toml_edit::{ArrayOfTables, Decor, DocumentMut, Item, Key, Table, Value};

use crate::align::align_sections;
use crate::decor::{DefaultEcho, DocBlock, Marker, Prefix, PrefixLine, Sample};
use crate::error::Error;
use crate::options::{MergeOptions, ResolvedMigration};
use crate::path::DottedPath;
use crate::report::{Diagnostic, DiagnosticKind, Position, Report, SpanIndex, TomlType};
use crate::source::SourceDocument;
use crate::template::{Template, comment_out};

/// The merged document and its report.
///
/// The document holds what the person set. A default they left alone is a `#:`
/// line above the place it would go, which is a comment, so the document does
/// not hold it: ask [`Merged::user_set`] which keys are theirs, and take the
/// values for the rest from the defaults you passed in.
///
/// With [`MergeOptions::defaults_commented`] off, every default is materialised
/// as a live key instead, and the document is the effective configuration.
#[derive(Debug, Clone)]
pub struct Merged {
    /// Everything the merge noticed.
    pub report: Report,
    pub(crate) document: DocumentMut,
    /// The line ending the person's file was written with.
    pub(crate) newline: Newline,
    /// The defaults this came from, kept so [`Merged::set`] can merge again
    /// and put a newly set value where the defaults say it goes.
    pub(crate) defaults: String,
    /// The options that produced it, kept for the same reason.
    pub(crate) options: MergeOptions,
}

/// How a file ends its lines.
///
/// The comment machinery works in lines and writes them back joined with `\n`,
/// so a file written with `\r\n` would come back rewritten from top to bottom.
/// The person's own ending is recorded here and restored on the way out.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Newline {
    #[default]
    Lf,
    CrLf,
}

impl Newline {
    /// The ending the person used. A file holding one `\r\n` is a CRLF file:
    /// mixed endings are what an editor leaves behind, not a choice.
    pub(crate) fn of(src: &str) -> Self {
        if src.contains("\r\n") {
            Self::CrLf
        } else {
            Self::Lf
        }
    }

    /// Rewrites every line ending in `text` as this one.
    pub(crate) fn apply(self, text: String) -> String {
        match self {
            Self::Lf => text,
            Self::CrLf => text.replace("\r\n", "\n").replace('\n', "\r\n"),
        }
    }
}

impl Merged {
    /// The merged document, for callers that want to deserialize it.
    pub fn document(&self) -> &DocumentMut {
        &self.document
    }

    /// The merged document, taken by value.
    pub fn into_document(self) -> DocumentMut {
        self.document
    }

    /// The file to write back, with the person's own line ending.
    pub fn to_toml_string(&self) -> String {
        self.newline.apply(self.document.to_string())
    }

    /// The line ending the person's file was written with, which is the one
    /// [`Merged::to_toml_string`] writes.
    pub fn newline(&self) -> Newline {
        self.newline
    }

    /// Sets a value in the person's file, where the defaults say it goes.
    ///
    /// A key that was a `#:` line becomes a live key under it, in the section
    /// and the order the defaults gave it, with the shipped default recorded
    /// above when the two differ. A key they already set is rewritten in
    /// place, keeping their comments and the blank lines around them. A key
    /// the defaults do not declare is kept too, and reported as
    /// [`DiagnosticKind::UnknownKey`].
    ///
    /// The path is read as a TOML key path, so a quoted segment holding a dot
    /// is one segment. Tables above it are created as needed.
    ///
    /// This merges again, so [`Merged::report`] afterwards describes the
    /// document as it now stands: setting a value of the wrong type leaves it
    /// in the file and reports [`DiagnosticKind::TypeMismatch`], the same as
    /// if the person had written it there themselves.
    ///
    /// ```
    /// # use documented_toml::merge;
    /// let mut merged = merge("##: How many.\ncount = 1\nother = 2\n", "other = 5\n")?;
    /// merged.set("count", 7)?;
    /// assert_eq!(
    ///     merged.to_toml_string(),
    ///     "##: How many.\n#: count = 1\ncount = 7\n#: other = 2\nother = 5\n"
    /// );
    /// # Ok::<(), documented_toml::Error>(())
    /// ```
    pub fn set(&mut self, path: &str, value: impl Into<Value>) -> Result<(), Error> {
        let parsed = DottedPath::parse(path).map_err(|source| Error::SetPath { source })?;
        let mut document = self.document.clone();
        if !assign(document.as_table_mut(), &parsed, value.into()) {
            return Err(Error::NotAValue {
                path: path.to_owned(),
            });
        }
        let text = self.newline.apply(document.to_string());
        *self = self.options.merge(&self.defaults, &text)?;
        Ok(())
    }

    /// Whether the person set a value at this dotted path.
    ///
    /// The path is read as a TOML key path, so a quoted segment holding a dot
    /// is one segment. A path that does not parse is not set.
    ///
    /// A default they left alone is a `#:` line, which answers `false`; a
    /// default they wrote out unchanged is a value they chose, which answers
    /// `true`. With [`MergeOptions::defaults_commented`] off every declared
    /// key is live, so this answers `true` for defaults too and tells you
    /// nothing.
    ///
    /// A section whose keys are all commented is written as a live but empty
    /// `[table]`, so that setting one of them is uncommenting one line. Such a
    /// table holds nothing the person chose and answers `false`.
    pub fn user_set(&self, path: &str) -> bool {
        let Ok(path) = DottedPath::parse(path) else {
            return false;
        };
        lookup(self.document.as_table(), &path).is_some_and(|item| match item {
            Item::None => false,
            Item::Table(table) => !table.is_empty(),
            Item::ArrayOfTables(array) => !array.is_empty(),
            Item::Value(_) => true,
        })
    }
}

/// Walks the default document as the spine and transplants user values.
///
/// The defaults give the shape and the order; the user gives the values.
#[derive(Debug, Clone)]
pub struct MergeEngine {
    /// The shipped document, which gives the shape and the order.
    pub(crate) defaults: SourceDocument,
    /// The person's document, which gives the values.
    pub(crate) user: SourceDocument,
    /// The text the spans point into, needed to turn a byte offset into a line
    /// and a column.
    pub(crate) user_src: String,
    pub(crate) options: MergeOptions,
    pub(crate) migrations: Vec<ResolvedMigration>,
    pub(crate) spans: SpanIndex,
    pub(crate) report: Report,
    /// The keys the defaults document without declaring.
    pub(crate) template: Template,
    /// Optional keys the person has not set, written back as `#:` lines and
    /// waiting for something to sit above.
    pub(crate) pending: Vec<String>,
    /// Whether what is waiting wants a blank line between itself and the key
    /// above it. It is what the defaults wrote above the first waiting key.
    pub(crate) pending_spaced: bool,
    /// The dotted keys the walk has descended through, which the `[table]`
    /// header above does not supply. A recorded default is TOML, so it names
    /// its key the way the line under it does.
    pub(crate) dotted: Vec<String>,
}

impl MergeEngine {
    pub(crate) fn new(
        defaults: SourceDocument,
        user: SourceDocument,
        user_src: &str,
        options: MergeOptions,
        migrations: Vec<ResolvedMigration>,
        spans: SpanIndex,
    ) -> Self {
        Self {
            defaults,
            user,
            user_src: user_src.to_owned(),
            options,
            migrations,
            spans,
            report: Report::default(),
            template: Template::default(),
            pending: Vec::new(),
            pending_spaced: true,
            dotted: Vec::new(),
        }
    }

    /// Runs the merge.
    pub(crate) fn run(mut self) -> Merged {
        self.apply_migrations();
        self.template = Template::of(&self.defaults, self.marker());

        let empty = Table::new();
        let defaults = self.defaults.root().unwrap_or(&empty).clone();
        let user = self.user.root().unwrap_or(&empty).clone();

        let mut root = Table::new();
        self.merge_table(&defaults, &user, &mut root, None);
        renumber_tables(&mut root, &mut 0);
        space_sections(&mut root, &mut false, false);
        if self.options.align {
            align_sections(&mut root);
        }

        let mut document = DocumentMut::new();
        *document.as_table_mut() = root;
        let keys = !document.as_table().is_empty();
        document.set_trailing(self.merged_trailing(keys));

        Merged {
            report: self.report,
            document,
            newline: Newline::of(&self.user_src),
            defaults: String::new(),
            options: self.options,
        }
    }

    fn marker(&self) -> &Marker {
        &self.options.marker
    }

    /// Where a key sits in the person's file.
    fn position(&self, path: &DottedPath) -> Position {
        self.spans.position(&self.user_src, path)
    }

    // -- migrations ------------------------------------------------------

    /// Moves values the rename rules name, before the merge walk, so a migrated
    /// value takes part in the merge as if the person had written it in place.
    fn apply_migrations(&mut self) {
        let migrations = std::mem::take(&mut self.migrations);
        for migration in &migrations {
            let Some(root) = self.user.root_mut() else {
                break;
            };
            if lookup(root, &migration.to).is_some() {
                // The user's explicit new-path value wins; the old path falls
                // through to the unknown-key rule.
                continue;
            }
            let Some((key, item)) = take(root, &migration.from) else {
                continue;
            };
            let renamed = Key::new(migration.to.leaf()).with_leaf_decor(key.leaf_decor().clone());
            if !place(root, &migration.to, renamed, item) {
                continue;
            }
            let at = self.position(&migration.from);
            self.report.push(Diagnostic::new(
                DiagnosticKind::Migrated {
                    from: migration.from.clone(),
                },
                migration.to.clone(),
                at,
            ));
        }
        self.migrations = migrations;
    }

    // -- the walk --------------------------------------------------------

    fn merge_table(
        &mut self,
        defaults: &Table,
        user: &Table,
        out: &mut Table,
        path: Option<&DottedPath>,
    ) {
        let optional = self.template.under(path).cloned().unwrap_or_default();
        let mut done: BTreeSet<String> = defaults.iter().map(|(name, _)| name.to_owned()).collect();

        for (name, default_item) in defaults.iter() {
            if matches!(default_item, Item::None) {
                continue;
            }
            let default_key = defaults.key(name).expect("a name iterated has a key");
            let child = child_path(path, name);
            // Anything the defaults documented above this key was written to be
            // read above it, so it goes out first.
            self.merge_optional(&optional, &mut done, user, out, path, Some(&child));
            match user.get_key_value(name) {
                None => {
                    if self.options.commented && !opens_section(default_item) {
                        self.comment_default(default_key, default_item, &child);
                    } else {
                        let first = out.is_empty();
                        let (key, item) =
                            self.default_entry(default_key, default_item, &child, first);
                        out.insert_formatted(&key, item);
                    }
                }
                Some((user_key, user_item)) => {
                    self.merge_item(default_key, default_item, user_key, user_item, out, &child);
                }
            }
        }

        self.merge_optional(&optional, &mut done, user, out, path, None);

        for (name, user_item) in user.iter() {
            if done.contains(name) || matches!(user_item, Item::None) {
                continue;
            }
            let user_key = user.key(name).expect("a name iterated has a key");
            let child = child_path(path, name);
            if !self.template.knows(&child) {
                let at = self.position(&child);
                self.report.push(Diagnostic::new(
                    DiagnosticKind::UnknownKey,
                    child.clone(),
                    at,
                ));
            }
            let (key, item) = self.keep_unknown(user_key, user_item, &child);
            out.insert_formatted(&key, item);
        }
    }

    /// Writes out the keys the defaults document without declaring, the ones
    /// due at this point in the order.
    ///
    /// A key the person has set merges like any other, its `#:` line being the
    /// default the defaults wrote by hand because there was no live value to
    /// take one from. A key they have not set stays a `#:` line.
    fn merge_optional(
        &mut self,
        optional: &Table,
        done: &mut BTreeSet<String>,
        user: &Table,
        out: &mut Table,
        path: Option<&DottedPath>,
        above: Option<&DottedPath>,
    ) {
        for (name, item) in optional.iter() {
            if done.contains(name) || matches!(item, Item::None) {
                continue;
            }
            let child = child_path(path, name);
            let due = match above {
                Some(next) => self.template.written_before(&child) == Some(next),
                // Whatever is left was written below the last key of its table,
                // or below a key this table does not have.
                None => true,
            };
            if !due {
                continue;
            }
            let Some(key) = optional.key(name) else {
                continue;
            };
            done.insert(name.to_owned());
            match user.get_key_value(name) {
                Some((user_key, user_item)) => {
                    self.optional_set(key, item, user_key, user_item, out, &child);
                }
                None => {
                    // Nothing to sit above yet. It waits for whatever the walk
                    // reaches next, and for the end of the file if nothing.
                    if self.pending.is_empty() {
                        self.pending_spaced = true;
                    } else {
                        self.pending.push(String::new());
                    }
                    self.pending
                        .extend(comment_out(&child, key, item, self.marker()));
                }
            }
        }
    }

    /// An optional key the person has set.
    fn optional_set(
        &mut self,
        key: &Key,
        item: &Item,
        user_key: &Key,
        user_item: &Item,
        out: &mut Table,
        path: &DottedPath,
    ) {
        let first = out.is_empty();
        let mut block = DocBlock::default();
        block.keep_user_text(&Prefix::of(decor_of(user_key, user_item)), self.marker());
        let (_, touching) = Prefix::of(decor_of(key, item)).split(self.marker());
        block.take_docs(&touching);
        block.floating = std::mem::take(&mut self.pending);
        if !block.floating.is_empty() {
            block.floating.insert(0, String::new());
            block.floating.push(String::new());
        }

        let mut merged = match (item, user_item) {
            (Item::Value(_), Item::Value(user_value)) => {
                self.record_default(&mut block, key, item, Some(user_value));
                Item::Value(user_value.clone())
            }
            (_, Item::Table(user_table)) => {
                let mut merged = Table::new();
                merged.set_dotted(user_table.is_dotted());
                self.descend(user_key, user_table, |engine| {
                    engine.merge_table(&Table::new(), user_table, &mut merged, Some(path));
                });
                Item::Table(merged)
            }
            (_, Item::ArrayOfTables(user_array)) => {
                // The template describes one entry's shape. It documents the
                // first, which is where a person reads what the rest may hold.
                let mut array = user_array.clone();
                if let Some(entry) = array.get_mut(0) {
                    let mut merged = Table::new();
                    self.merge_table(&Table::new(), entry, &mut merged, Some(path));
                    *entry = merged;
                }
                // What the first entry documents and nobody set belongs to that
                // entry, so it is written above the header of the next one.
                // The tool's lines already there are written again.
                let unset = std::mem::take(&mut self.pending);
                for (index, entry) in array.iter_mut().enumerate().skip(1) {
                    let mut block = DocBlock::default();
                    block.keep_user_text(&Prefix::of(entry.decor()), self.marker());
                    if index == 1 && !unset.is_empty() {
                        block.floating = unset.clone();
                        if self.pending_spaced {
                            block.floating.insert(0, String::new());
                        }
                        block.floating.push(String::new());
                    }
                    entry.decor_mut().set_prefix(block.render(self.marker()));
                }
                if array.len() < 2 {
                    self.pending = unset;
                }
                // Entries the template has beyond the first are further
                // examples, not the shape of what is already there. They stay
                // written out, like any optional key nobody has set.
                if let Item::ArrayOfTables(template_array) = item {
                    for extra in template_array.iter().skip(1) {
                        let mut single = ArrayOfTables::new();
                        single.push(extra.clone());
                        if !self.pending.is_empty() {
                            self.pending.push(String::new());
                        }
                        let lines =
                            comment_out(path, key, &Item::ArrayOfTables(single), self.marker());
                        self.pending.extend(lines);
                    }
                }
                Item::ArrayOfTables(array)
            }
            _ => user_item.clone(),
        };

        // A documented key is set apart from the one before it. A key with
        // nothing written above it needs no setting apart.
        let documented = !block.prose.is_empty() || !matches!(block.sample, Sample::None);
        if block.leading_blanks.is_empty() && !first && documented {
            block.leading_blanks = vec![String::new()];
        }

        let mut key = user_key.clone();
        set_prefix(&mut key, &mut merged, block.render(self.marker()));
        out.insert_formatted(&key, merged);
    }

    /// Merges one key present in both documents.
    fn merge_item(
        &mut self,
        default_key: &Key,
        default_item: &Item,
        user_key: &Key,
        user_item: &Item,
        out: &mut Table,
        path: &DottedPath,
    ) {
        let first = out.is_empty();
        let mut block = self.block(
            decor_of(default_key, default_item),
            decor_of(user_key, user_item),
        );
        self.flush_pending(&mut block, first);
        let expected = TomlType::of(default_item);
        let found = TomlType::of(user_item);

        let compatible = expected == found
            || matches!(
                (expected, found),
                (Some(TomlType::Float), Some(TomlType::Integer))
            );
        let mut item = if !compatible {
            if let (Some(expected), Some(found)) = (expected, found) {
                let at = self.position(path);
                self.report.push(Diagnostic::new(
                    DiagnosticKind::TypeMismatch { expected, found },
                    path.clone(),
                    at,
                ));
            }
            // The person's value stays exactly as they wrote it. Only the block
            // above it is rebuilt, because that text belongs to the tool.
            self.record_default(&mut block, default_key, default_item, None);
            user_item.clone()
        } else {
            match (default_item, user_item) {
                (Item::Value(_), Item::Value(user_value)) => {
                    self.record_default(&mut block, default_key, default_item, Some(user_value));
                    Item::Value(user_value.clone())
                }
                (Item::Table(default_table), Item::Table(user_table)) => {
                    let mut merged = Table::new();
                    merged.set_dotted(user_table.is_dotted());
                    merged.set_implicit(default_table.is_implicit() && user_table.is_implicit());
                    self.descend(user_key, user_table, |engine| {
                        engine.merge_table(default_table, user_table, &mut merged, Some(path));
                    });
                    Item::Table(merged)
                }
                (Item::ArrayOfTables(_), Item::ArrayOfTables(user_array)) => {
                    // The person's set is complete: the defaults contribute no
                    // entries and no fields. Only the documentation is refreshed.
                    Item::ArrayOfTables(user_array.clone())
                }
                _ => unreachable!("equal TOML types have matching item shapes"),
            }
        };

        let mut key = user_key.clone();
        set_prefix(&mut key, &mut item, block.render(self.marker()));
        out.insert_formatted(&key, item);
    }

    /// Walks the keys of `table` with `key` on the dotted prefix when the table
    /// is written dotted, and off it when the table has a header of its own.
    fn descend(&mut self, key: &Key, table: &Table, walk: impl FnOnce(&mut Self)) {
        let dotted = table.is_dotted();
        if dotted {
            self.dotted.push(key.display_repr().into_owned());
        }
        walk(self);
        if dotted {
            self.dotted.pop();
        }
    }

    /// Moves any optional keys waiting to be written above whatever comes next.
    ///
    /// `first` says the block opens its table, where there is nothing to be set
    /// apart from. Anywhere else the waiting lines are separated from the key
    /// above them, the way the defaults separated them.
    fn flush_pending(&mut self, block: &mut DocBlock, first: bool) {
        if self.pending.is_empty() {
            return;
        }
        let mut waiting = std::mem::take(&mut self.pending);
        if !first && self.pending_spaced {
            waiting.insert(0, String::new());
        }
        // The defaults' own spacing says whether the key below opens something
        // of its own. A key written against the one above it reads as the next
        // line of the same run, and a blank here would break the run up.
        if !self.options.commented || block.spaced {
            waiting.push(String::new());
        }
        waiting.append(&mut block.floating);
        block.floating = waiting;
    }

    /// The doc block for a key present in both documents: the defaults' standing
    /// text and prose, the person's blanks and comments.
    fn block(&self, default_decor: &Decor, user_decor: &Decor) -> DocBlock {
        let (floating, touching) = Prefix::of(default_decor).split(self.marker());
        let mut block = DocBlock {
            spaced: spaced(&floating),
            ..DocBlock::default()
        };
        block.keep_user_text(&Prefix::of(user_decor), self.marker());
        block.take_docs(&touching);
        block.floating = self.standing_text(&floating);
        if block.leading_blanks.is_empty() && block.floating.is_empty() {
            // The person wrote nothing above this key, so the separation the
            // defaults put there is what keeps the file readable.
            block.leading_blanks = leading_blanks(&floating);
        }
        block
    }

    /// The defaults' text that stands a blank line away from the key, with the
    /// maintainers' own notes dropped and the blocks that have travelled left
    /// out. Documentation anchored on this key arrives here.
    fn standing_text(&self, floating: &[PrefixLine]) -> Vec<String> {
        let mut out: Vec<String> = Vec::new();
        for run in standing_runs(floating, self.marker()) {
            match run {
                Standing::Blanks(lines) => out.extend(lines),
                Standing::Block(lines) => {
                    let text: Vec<String> = lines
                        .iter()
                        .filter(|line| !matches!(line, PrefixLine::User { .. }))
                        .map(|line| line.text().to_owned())
                        .collect();
                    if self.template.read.contains(&text.join("\n")) {
                        while out.last().is_some_and(|line| line.trim().is_empty()) {
                            out.pop();
                        }
                        continue;
                    }
                    out.extend(text);
                }
            }
        }
        if out.iter().all(|line| line.trim().is_empty()) {
            out.clear();
        }
        out
    }

    /// Records the shipped default above the key when the person's value
    /// differs from it. A generated line replaces whatever samples the defaults
    /// wrote for the same key: both occupy the slot under the prose.
    fn record_default(
        &self,
        block: &mut DocBlock,
        default_key: &Key,
        default_item: &Item,
        user_value: Option<&Value>,
    ) {
        let Item::Value(default_value) = default_item else {
            return;
        };
        let default_text = rendered(default_value);
        if let Some(user_value) = user_value
            && rendered(user_value) == default_text
        {
            return;
        }
        block.sample = Sample::Echo(DefaultEcho {
            key: self.dotted_name(default_key),
            value: default_text,
        });
    }

    /// The key a recorded default names: the leaf under every dotted key the
    /// walk descended through, which is the same path the line below it takes.
    fn dotted_name(&self, key: &Key) -> String {
        let mut name = String::new();
        for segment in &self.dotted {
            name.push_str(segment);
            name.push('.');
        }
        name.push_str(&key.display_repr());
        name
    }

    // -- keys only on one side -------------------------------------------

    /// A key the person does not have yet, taken from the defaults with the
    /// maintainers' own notes stripped out.
    ///
    /// Optional keys waiting to be written arrive here too. The block above a
    /// key is where the defaults put it, and that is where it goes, whether or
    /// not the person has written the key it belongs above.
    fn default_entry(
        &mut self,
        key: &Key,
        item: &Item,
        path: &DottedPath,
        first: bool,
    ) -> (Key, Item) {
        let prefix = Prefix::of(decor_of(key, item));
        let (floating, touching) = prefix.split(self.marker());
        let mut block = DocBlock {
            leading_blanks: leading_blanks(&floating),
            indent: prefix.indent().to_owned(),
            spaced: spaced(&floating),
            ..DocBlock::default()
        };
        block.take_docs(&touching);
        block.floating = self.standing_text(&floating);
        self.flush_pending(&mut block, first);

        let mut key = key.clone();
        let mut item = self.docs_only(item, path);
        set_prefix(&mut key, &mut item, block.render(self.marker()));
        (key, item)
    }

    /// A default the person has not set, written back as the `#:` lines it
    /// would be set from.
    ///
    /// It joins whatever is already waiting rather than being separated from
    /// it: the spacing between two defaults is the spacing the defaults were
    /// written with, which each entry carries above itself.
    fn comment_default(&mut self, key: &Key, item: &Item, path: &DottedPath) {
        // Nothing waiting, so the entry builds its block against the start of
        // its own text and adds no separator of its own.
        let waiting = std::mem::take(&mut self.pending);
        // A table is commented out whole, header and keys together, so its
        // keys are built as the live entries they would be inside it rather
        // than each waiting on its own.
        let commented = std::mem::replace(&mut self.options.commented, false);
        let (key, item) = self.default_entry(key, item, path, true);
        self.options.commented = commented;

        let mut lines = comment_out(path, &key, &item, self.marker());
        // Optional keys the table documents below its last key have nothing
        // after them to sit above, so they close the block they belong to.
        let inner = std::mem::take(&mut self.pending);
        if !inner.is_empty() {
            lines.push(String::new());
            lines.extend(inner);
        }

        if waiting.is_empty() {
            // The first thing to wait says how the whole of it is set apart
            // from the key above. The blank lines the defaults put above this
            // key are that separation, and one of them is kept.
            let text = lines
                .iter()
                .position(|line| !line.trim().is_empty())
                .unwrap_or(lines.len());
            self.pending_spaced = text > 0;
            lines.drain(..text);
        }
        self.pending = waiting;
        self.pending.extend(lines);
    }

    /// The same stripping, applied through a table or an array of tables.
    ///
    /// An array of tables documents its first entry, which is where a person
    /// reads what the rest may hold, so the optional keys are due there and in
    /// no entry after it.
    fn docs_only(&mut self, item: &Item, path: &DottedPath) -> Item {
        match item {
            Item::Table(table) => Item::Table(self.docs_only_table(table, path, true)),
            Item::ArrayOfTables(array) => {
                let mut out = ArrayOfTables::new();
                for (index, entry) in array.iter().enumerate() {
                    out.push(self.docs_only_table(entry, path, index == 0));
                }
                Item::ArrayOfTables(out)
            }
            other => other.clone(),
        }
    }

    /// The keys of a table the person has not written.
    ///
    /// `documented` walks it as a merge against an empty table, so the keys the
    /// defaults document without declaring are written out at the point in the
    /// order they were written. A person who has not opened a section still
    /// reads what it may hold.
    fn docs_only_table(&mut self, table: &Table, path: &DottedPath, documented: bool) -> Table {
        let mut out = Table::new();
        out.set_dotted(table.is_dotted());
        out.set_implicit(table.is_implicit());
        if documented {
            self.merge_table(table, &Table::new(), &mut out, Some(path));
            return out;
        }
        for (name, item) in table.iter() {
            let key = table.key(name).expect("a name iterated has a key");
            let first = out.is_empty();
            let (key, item) = self.default_entry(key, item, &path.child(name), first);
            out.insert_formatted(&key, item);
        }
        out
    }

    /// A key the defaults do not declare. It is never deleted and never
    /// rewritten, but the marker lines above it go: their key has left the
    /// defaults, so the tool no longer has anything to say about it. Unless the
    /// defaults anchored documentation on it, which arrives here.
    fn keep_unknown(&self, key: &Key, item: &Item, path: &DottedPath) -> (Key, Item) {
        let mut block = DocBlock::default();
        block.keep_user_text(&Prefix::of(decor_of(key, item)), self.marker());
        block.floating = Vec::new();

        let mut key = key.clone();
        let mut item = match item {
            Item::Table(table) => Item::Table(self.keep_unknown_table(table, path)),
            Item::ArrayOfTables(array) => {
                let mut out = ArrayOfTables::new();
                for entry in array.iter() {
                    out.push(self.keep_unknown_table(entry, path));
                }
                Item::ArrayOfTables(out)
            }
            other => other.clone(),
        };
        set_prefix(&mut key, &mut item, block.render(self.marker()));
        (key, item)
    }

    fn keep_unknown_table(&self, table: &Table, path: &DottedPath) -> Table {
        let mut out = Table::new();
        out.set_dotted(table.is_dotted());
        out.set_implicit(table.is_implicit());
        *out.decor_mut() = table.decor().clone();
        for (name, item) in table.iter() {
            let key = table.key(name).expect("a name iterated has a key");
            let (key, item) = self.keep_unknown(key, item, &path.child(name));
            out.insert_formatted(&key, item);
        }
        out
    }

    // -- the end of the file ---------------------------------------------

    /// The text after the last key belongs to no key, so it is not a doc block.
    /// The same ownership holds: the tool's lines there come from the defaults,
    /// and everything else is the person's and is kept as written.
    /// `keys` says the document has a key above this text to be set apart
    /// from. A document of nothing but `#:` lines has none, so the text opens
    /// the file.
    fn merged_trailing(&mut self, keys: bool) -> String {
        let waiting = std::mem::take(&mut self.pending);
        let marker = self.marker();
        let prefix = Prefix::from_text(self.defaults.trailing());
        let (mut lines, touching) = prefix.split(marker);
        lines.extend(touching);
        let mut docs = self.standing_text(&lines);
        // Optional keys nothing came after belong at the end of the last table
        // they were written in, which is here.
        let mut waiting = waiting;
        // Waiting lines carry the spacing the defaults gave the keys they came
        // from, so what they open with is the separation they want. The
        // defaults' own trailing text carries none, and is set apart from the
        // last key by one blank line whatever it was written with.
        let separated = waiting.is_empty() || self.pending_spaced;
        if !waiting.is_empty() {
            if !docs.is_empty() {
                waiting.push(String::new());
            }
            waiting.append(&mut docs);
            docs = waiting;
        }
        if separated {
            let first = docs
                .iter()
                .position(|line| !line.trim().is_empty())
                .unwrap_or(docs.len());
            docs.drain(..first);
        }

        let user = Prefix::from_text(self.user.trailing());
        let user_lines = user.lines(marker);
        let first = user_lines
            .iter()
            .position(|line| !matches!(line, PrefixLine::Blank { .. }))
            .unwrap_or(user_lines.len());
        // The tool's lines here are written again from the defaults. Taking
        // them out leaves the blank lines that separated them, which have
        // nothing left to separate.
        let mut mine: Vec<&str> = Vec::new();
        for line in &user_lines[first..] {
            if marker.owns(line.text()) {
                continue;
            }
            let blank = line.text().trim().is_empty();
            if blank && mine.last().is_none_or(|last| last.trim().is_empty()) {
                continue;
            }
            mine.push(line.text());
        }
        while mine.last().is_some_and(|line| line.trim().is_empty()) {
            mine.pop();
        }

        let content = docs.iter().any(|line| !line.trim().is_empty())
            || mine.iter().any(|line| !line.trim().is_empty());
        if !content {
            return String::new();
        }

        let mut out = String::from(if keys && separated { "\n" } else { "" });
        for line in docs.iter().map(String::as_str).chain(mine) {
            out.push_str(line);
            out.push('\n');
        }
        out
    }
}

/// The blocks in a stretch of standing text.
pub(crate) fn blocks<'a>(lines: &'a [PrefixLine], marker: &Marker) -> Vec<&'a [PrefixLine]> {
    standing_runs(lines, marker)
        .into_iter()
        .filter_map(|run| match run {
            Standing::Block(lines) => Some(lines),
            Standing::Blanks(_) => None,
        })
        .collect()
}

enum Standing<'a> {
    Blanks(Vec<String>),
    Block(&'a [PrefixLine]),
}

/// Standing text split into its blocks, keeping the blank lines between them.
///
/// A blank line ends a block. So does a sample line opening a `[table]`
/// header: it names a key of its own, so what follows documents that key and
/// not the last one. Prose written directly above such a header introduces it,
/// and goes with the block the header opens.
fn standing_runs<'a>(lines: &'a [PrefixLine], marker: &Marker) -> Vec<Standing<'a>> {
    let blank = |line: &PrefixLine| matches!(line, PrefixLine::Blank { .. });
    let mut out = Vec::new();
    let mut at = 0;
    while at < lines.len() {
        let start = at;
        if blank(&lines[at]) {
            while at < lines.len() && blank(&lines[at]) {
                at += 1;
            }
            out.push(Standing::Blanks(
                lines[start..at]
                    .iter()
                    .map(|line| line.text().to_owned())
                    .collect(),
            ));
        } else {
            while at < lines.len() && !blank(&lines[at]) {
                at += 1;
            }
            out.extend(
                split_at_headers(&lines[start..at], marker)
                    .into_iter()
                    .map(Standing::Block),
            );
        }
    }
    out
}

/// One run of the tool's lines, cut where a new `[table]` header takes over.
fn split_at_headers<'a>(run: &'a [PrefixLine], marker: &Marker) -> Vec<&'a [PrefixLine]> {
    let mut starts = vec![0usize];
    for (at, line) in run.iter().enumerate().skip(1) {
        if !opens_table(line, marker) {
            continue;
        }
        let mut start = at;
        while start > 0 && matches!(run[start - 1], PrefixLine::Prose { .. }) {
            start -= 1;
        }
        if start > *starts.last().expect("starts is never empty") {
            starts.push(start);
        }
    }
    starts
        .iter()
        .enumerate()
        .map(|(n, &start)| {
            let end = starts.get(n + 1).copied().unwrap_or(run.len());
            &run[start..end]
        })
        .collect()
}

fn opens_table(line: &PrefixLine, marker: &Marker) -> bool {
    match line {
        PrefixLine::Sample { text } => marker.undress(text).trim_start().starts_with('['),
        _ => false,
    }
}

/// The blank lines a key has above it in the defaults, which is what separates
/// one documented option from the last when the person wrote no blanks of their
/// own.
/// Whether a default writes a `[table]` header of its own.
///
/// Such a header is written live even when every key under it is commented
/// out: the header is the place the keys go, and a person setting one of them
/// should not have to uncomment the section first. An empty `[table]` says the
/// same thing as no table at all, which is why this is safe to write.
///
/// An array of tables is not: an empty `[[entry]]` is one entry holding
/// nothing, not the absence of entries, so its header stays commented.
fn opens_section(item: &Item) -> bool {
    matches!(item, Item::Table(table) if !table.is_dotted())
}

/// Whether the defaults left a blank line anywhere above the key, which is how
/// they say the key opens something rather than continuing what is above it.
fn spaced(floating: &[PrefixLine]) -> bool {
    floating
        .iter()
        .any(|line| matches!(line, PrefixLine::Blank { .. }))
}

fn leading_blanks(floating: &[PrefixLine]) -> Vec<String> {
    floating
        .iter()
        .take_while(|line| matches!(line, PrefixLine::Blank { .. }))
        .map(|line| line.text().to_owned())
        .collect()
}

fn child_path(path: Option<&DottedPath>, name: &str) -> DottedPath {
    match path {
        Some(path) => path.child(name),
        None => DottedPath::new(name),
    }
}

/// Where the text above a key lives.
///
/// For a key-value pair it is the key's own leaf decor. A standalone table
/// carries it in its own decor, and an array of tables in that of its first
/// entry, because that is what sits under the comment in the file.
pub(crate) fn decor_of<'a>(key: &'a Key, item: &'a Item) -> &'a Decor {
    match item {
        Item::Table(table) if !table.is_dotted() => table.decor(),
        Item::ArrayOfTables(array) => match array.get(0) {
            Some(first) => first.decor(),
            None => key.leaf_decor(),
        },
        _ => key.leaf_decor(),
    }
}

/// Writes a rebuilt block back where [`decor_of`] found it, leaving nothing
/// behind in the place it did not use.
fn set_prefix(key: &mut Key, item: &mut Item, prefix: String) {
    match item {
        Item::Table(table) if !table.is_dotted() => {
            key.leaf_decor_mut().set_prefix("");
            table.decor_mut().set_prefix(prefix);
        }
        Item::ArrayOfTables(array) => {
            key.leaf_decor_mut().set_prefix("");
            if let Some(first) = array.get_mut(0) {
                first.decor_mut().set_prefix(prefix);
            }
        }
        _ => {
            key.leaf_decor_mut().set_prefix(prefix);
        }
    }
}

/// A value's text with every scrap of formatting whitespace removed, which is
/// what "does the user's value differ from the default" compares. Comparing the
/// text keeps float equality out of it and treats `1_000` and `1000` as the
/// different text they are.
fn rendered(value: &Value) -> String {
    let mut value = value.clone();
    strip(&mut value);
    value.to_string().trim().to_owned()
}

fn strip(value: &mut Value) {
    match value {
        Value::Array(array) => {
            for element in array.iter_mut() {
                strip(element);
            }
            array.set_trailing("");
            array.set_trailing_comma(false);
        }
        Value::InlineTable(table) => {
            for (mut key, element) in table.iter_mut() {
                key.leaf_decor_mut().clear();
                key.dotted_decor_mut().clear();
                strip(element);
            }
            table.set_trailing("");
            table.set_trailing_comma(false);
        }
        _ => {}
    }
    value.decor_mut().clear();
}

/// Separates visible section headers, including their documentation, from
/// preceding values or sections. Implicit parents emit no header.
/// Whether a header's prefix already holds the blank line that sets the
/// section apart from what is above it.
///
/// The blank belongs above the doc block that touches the header, not at the
/// top of the prefix: text flushed there can belong to the section before this
/// one, and putting the blank above it would read as if it opened this one.
fn separated(raw: &str) -> bool {
    let mut lines: Vec<&str> = raw.split('\n').collect();
    // What follows the last newline is the header's own indentation.
    lines.pop();
    while lines.last().is_some_and(|line| !line.trim().is_empty()) {
        lines.pop();
    }
    lines.last().is_some_and(|line| line.trim().is_empty())
}

fn space_sections(table: &mut Table, emitted: &mut bool, header: bool) {
    let has_values = !table.get_values().is_empty();
    if header {
        if *emitted {
            let prefix = Prefix::of(table.decor());
            if !separated(&prefix.raw) {
                table.decor_mut().set_prefix(format!("\n{}", prefix.raw));
            }
        }
        *emitted = true;
    }
    *emitted |= has_values;
    for (_, item) in table.iter_mut() {
        match item {
            Item::Table(sub) => {
                let visible =
                    !sub.is_dotted() && (!sub.is_implicit() || !sub.get_values().is_empty());
                space_sections(sub, emitted, visible);
            }
            Item::ArrayOfTables(array) => {
                for entry in array.iter_mut() {
                    space_sections(entry, emitted, true);
                }
            }
            _ => {}
        }
    }
}

/// Renumbers standalone tables in emission order.
///
/// `DocumentMut` sorts tables by their recorded position, and a table
/// transplanted from either input carries a position from a document it is no
/// longer in. Numbering them as the walk reaches them makes the output follow
/// the defaults' declaration order.
fn renumber_tables(table: &mut Table, next: &mut isize) {
    for (_, item) in table.iter_mut() {
        match item {
            Item::Table(sub) => {
                if !sub.is_dotted() {
                    *next += 1;
                    sub.set_position(Some(*next));
                }
                renumber_tables(sub, next);
            }
            Item::ArrayOfTables(array) => {
                for entry in array.iter_mut() {
                    *next += 1;
                    entry.set_position(Some(*next));
                    renumber_tables(entry, next);
                }
            }
            _ => {}
        }
    }
}

// -- path navigation, for migrations and anchors ------------------------

fn lookup<'t>(root: &'t Table, path: &DottedPath) -> Option<&'t Item> {
    let mut table = root;
    let mut segments = path.segments().peekable();
    while let Some(segment) = segments.next() {
        let item = table.get(segment)?;
        if segments.peek().is_none() {
            return Some(item);
        }
        table = match item {
            Item::Table(sub) => sub,
            Item::ArrayOfTables(array) => array.get(0)?,
            _ => return None,
        };
    }
    None
}

fn take(root: &mut Table, path: &DottedPath) -> Option<(Key, Item)> {
    let mut table = root;
    let mut segments = path.segments().peekable();
    while let Some(segment) = segments.next() {
        if segments.peek().is_none() {
            return table.remove_entry(segment);
        }
        table = table.get_mut(segment)?.as_table_mut()?;
    }
    None
}

/// Writes a value at a path, creating the tables above it as implicit ones.
/// Answers whether the path names somewhere a value can go.
///
/// An existing value is replaced through its slot, so the key keeps the
/// person's comments and the blank lines around it. Where the spacing around
/// the `=` is concerned the merge that follows lines it up again.
fn assign(root: &mut Table, path: &DottedPath, value: Value) -> bool {
    let mut table = root;
    let mut segments = path.segments().peekable();
    while let Some(segment) = segments.next() {
        if segments.peek().is_none() {
            return match table.get_mut(segment) {
                Some(item) if matches!(item, Item::Value(_) | Item::None) => {
                    *item = Item::Value(value);
                    true
                }
                // A table or an array of tables is there instead, and
                // overwriting it would throw away everything under it.
                Some(_) => false,
                None => {
                    table.insert(segment, Item::Value(value));
                    true
                }
            };
        }
        let entry = table.entry(segment).or_insert_with(|| {
            let mut created = Table::new();
            created.set_implicit(true);
            Item::Table(created)
        });
        match entry.as_table_mut() {
            Some(sub) => table = sub,
            None => return false,
        }
    }
    false
}

/// Inserts at a path, creating the tables above it as implicit ones. Answers
/// whether the path could be reached at all.
fn place(root: &mut Table, path: &DottedPath, key: Key, item: Item) -> bool {
    let mut table = root;
    let mut segments = path.segments().peekable();
    while let Some(segment) = segments.next() {
        if segments.peek().is_none() {
            table.insert_formatted(&key, item);
            return true;
        }
        let entry = table.entry(segment).or_insert_with(|| {
            let mut created = Table::new();
            created.set_implicit(true);
            Item::Table(created)
        });
        match entry.as_table_mut() {
            Some(sub) => table = sub,
            None => return false,
        }
    }
    false
}