mbook 0.3.6

Read, edit and create mbook files: Markdown chapters and AVIF pictures in one indexed container
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
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
//! A whole book in memory.

#[cfg(feature = "write")]
use crate::error::{Error, LandmarkError, Result, SourceError};
use crate::meta::Meta;
use crate::types::{Anchor, Size};
#[cfg(feature = "write")]
use crate::{analysis, avif, path, text};
use std::collections::HashMap;

#[cfg(feature = "read")]
mod load;
#[cfg(feature = "write")]
mod write;

/// A whole book in memory: metadata, chapters in reading order, pictures,
/// diagrams, formulas and the table of contents.
///
/// A `Book` is how a book is created and how an existing one is changed.
/// Chapters, pictures, diagrams and formulas are addressed by path. Nothing in it is a byte
/// offset the caller has to keep correct: anchors are computed from the text
/// of each chapter, and contents items name their target the way a link
/// does.
///
/// # Examples
///
/// Creating a book:
///
/// ```no_run
/// # #[cfg(feature = "write")]
/// # fn main() -> mbook::Result<()> {
/// use mbook::Book;
/// use std::fs;
///
/// let mut book = Book::new("The Example", "en")?;
/// book.meta_mut().add_author("A. Writer")?;
/// book.set_cover("img/cover.avif", fs::read("img/cover.avif")?)?;
/// book.add_chapter("ch01.md", fs::read_to_string("ch01.md")?)?;
/// book.add_picture("img/fig-1.avif", fs::read("img/fig-1.avif")?)?;
/// book.save("example.mbook")?;
/// # Ok(())
/// # }
/// # #[cfg(not(feature = "write"))]
/// # fn main() {}
/// ```
///
/// Changing an existing one:
///
/// ```no_run
/// # #[cfg(all(feature = "read", feature = "write"))]
/// # fn main() -> mbook::Result<()> {
/// use mbook::Book;
///
/// let mut book = Book::open("example.mbook")?;
/// book.meta_mut().set_title("The Example, 2nd edition")?;
/// if let Some(chapter) = book.chapter_mut("ch02.md") {
///     let fixed = chapter.text().replace("teh", "the");
///     chapter.set_text(fixed)?;
/// }
/// book.remove_picture("img/unused.avif");
/// book.save("example.mbook")?;
/// # Ok(())
/// # }
/// # #[cfg(not(all(feature = "read", feature = "write")))]
/// # fn main() {}
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Book {
    meta: Meta,
    chapters: Vec<Chapter>,
    pictures: Vec<Picture>,
    diagrams: Vec<Diagram>,
    formulas: Vec<Formula>,
    toc: Toc,
    /// The notable places of the book, in the order they are listed.
    landmarks: Vec<Landmark>,
    /// Where each path lives; paths are unique across chapters, pictures,
    /// diagrams and formulas.
    slots: HashMap<String, Slot>,
}

/// The place of a path in a `Book`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Slot {
    Chapter(usize),
    Picture(usize),
    Diagram(usize),
    Formula(usize),
}

/// One chapter of a [`Book`]: a path, Markdown text, the anchors of its
/// headings and the extra anchors of the lines it names.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Chapter {
    path: String,
    text: String,
    /// The anchors of the headings, sorted by offset.
    anchors: Vec<Anchor>,
    /// The anchors of the chapter's own table, sorted by offset.
    extra_anchors: Vec<Anchor>,
}

/// One picture of a [`Book`]: a path and an AVIF file.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Picture {
    path: String,
    size: Size,
    data: Vec<u8>,
}

/// One diagram of a [`Book`]: a path and a description in Mermaid notation.
///
/// A chapter shows it the way it shows a picture:
/// `![The flow of a request](dia/flow.mmd)`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Diagram {
    path: String,
    source: String,
}

/// One formula of a [`Book`]: a path and a formula in the notation of
/// `KaTeX`, without the `$` that surround one in running text.
///
/// A chapter shows it the way it shows a picture: `![E = mc^2](math/e.tex)`.
/// Alone in a paragraph it is set as a display formula, and inside a line as
/// a part of that line.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Formula {
    path: String,
    source: String,
}

/// The table of contents of a [`Book`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Toc {
    /// Built from the headings of every chapter when the book is written.
    FromHeadings {
        /// The deepest heading level to list; 6 lists every heading.
        max_level: u8,
    },
    /// Written as given. Every item must lead somewhere when the book is
    /// written.
    Explicit(Vec<TocItem>),
}

impl Default for Toc {
    /// Every heading of every chapter.
    fn default() -> Self {
        Self::FromHeadings { max_level: 6 }
    }
}

/// One item of an explicit table of contents.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TocItem {
    /// Depth in the tree, starting at 1.
    pub level: u8,
    /// The title, as plain text.
    pub title: String,
    /// The path of the chapter the item leads to.
    pub chapter: String,
    /// The anchor inside that chapter; `None` is the start of the chapter.
    pub anchor: Option<String>,
}

impl TocItem {
    /// An item that leads where a link with this destination would.
    ///
    /// `href` is a chapter path with an optional anchor after `#`. It is
    /// taken as written: nothing is percent-decoded.
    ///
    /// # Examples
    ///
    /// ```
    /// use mbook::TocItem;
    ///
    /// let item = TocItem::new(2, "The station", "ch01.md#the-station");
    /// assert_eq!(item.chapter, "ch01.md");
    /// assert_eq!(item.anchor.as_deref(), Some("the-station"));
    /// ```
    #[must_use]
    pub fn new(level: u8, title: impl Into<String>, href: &str) -> Self {
        let (chapter, anchor) = split_href(href);
        Self {
            level,
            title: title.into(),
            chapter,
            anchor,
        }
    }
}

/// One landmark of a [`Book`]: a notable place, such as the start of the
/// text, the glossary or the index.
///
/// A landmark names its target the way a link does: by the path of a chapter
/// and, for a place inside it, by an anchor. The kinds the format defines
/// are listed in RFC 0001; a kind that begins with `x-` is private.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Landmark {
    /// What the place is: `start`, `glossary`, `index`, …
    pub kind: String,
    /// The title to show, as plain text. An application names the kind
    /// itself when it is empty.
    pub title: String,
    /// The path of the chapter the landmark leads to.
    pub chapter: String,
    /// The anchor inside that chapter, of a heading or an extra one; `None`
    /// is the start of the chapter.
    pub anchor: Option<String>,
}

impl Landmark {
    /// A landmark that leads where a link with this destination would.
    ///
    /// `href` is a chapter path with an optional anchor after `#`. It is
    /// taken as written: nothing is percent-decoded.
    ///
    /// # Examples
    ///
    /// ```
    /// use mbook::Landmark;
    ///
    /// let landmark = Landmark::new("index", "", "back/index.md#index");
    /// assert_eq!(landmark.chapter, "back/index.md");
    /// assert_eq!(landmark.anchor.as_deref(), Some("index"));
    /// ```
    #[must_use]
    pub fn new(kind: impl Into<String>, title: impl Into<String>, href: &str) -> Self {
        let (chapter, anchor) = split_href(href);
        Self {
            kind: kind.into(),
            title: title.into(),
            chapter,
            anchor,
        }
    }
}

/// A link destination as a chapter path and an anchor; an empty anchor is
/// none.
fn split_href(href: &str) -> (String, Option<String>) {
    match href.split_once('#') {
        Some((chapter, anchor)) if !anchor.is_empty() => {
            (chapter.to_owned(), Some(anchor.to_owned()))
        }
        Some((chapter, _)) => (chapter.to_owned(), None),
        None => (href.to_owned(), None),
    }
}

impl Chapter {
    /// Normalises the text and computes its anchors.
    #[cfg(feature = "write")]
    fn new(path: String, text: String) -> Result<Self> {
        let (text, anchors, extra_anchors) = stored(text)?;
        Ok(Self {
            path,
            text,
            anchors,
            extra_anchors,
        })
    }

    /// The path of the chapter inside the book.
    #[must_use]
    pub fn path(&self) -> &str {
        &self.path
    }

    /// The Markdown text, in the form it is stored in.
    #[must_use]
    pub fn text(&self) -> &str {
        &self.text
    }

    /// The anchors of the headings of the chapter, sorted by offset.
    ///
    /// A chapter loaded from a file keeps the anchors stored in that file
    /// until its text is replaced.
    #[must_use]
    pub fn anchors(&self) -> &[Anchor] {
        &self.anchors
    }

    /// The anchors of the lines the chapter gives a name to, sorted by
    /// offset.
    ///
    /// A line gets a name from an *anchor definition* in front of it: a link
    /// reference definition that names itself, `[fig-1]: #fig-1`. A Markdown
    /// renderer shows nothing for it. A link reaches the line the same way
    /// as a heading: `ch01.md#fig-1`.
    ///
    /// A chapter loaded from a file keeps the extra anchors stored in that
    /// file until its text is replaced.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "write")]
    /// # fn main() -> mbook::Result<()> {
    /// let mut book = mbook::Book::new("The Example", "en")?;
    /// let chapter = book.add_chapter(
    ///     "ch01.md",
    ///     "# One\n\n[remark]: #remark\nA remark worth a link.\n",
    /// )?;
    ///
    /// let extra: Vec<_> = chapter
    ///     .extra_anchors()
    ///     .iter()
    ///     .map(|anchor| (anchor.name.as_str(), anchor.offset))
    ///     .collect();
    /// assert_eq!(extra, [("remark", 7)]);
    /// # Ok(())
    /// # }
    /// # #[cfg(not(feature = "write"))]
    /// # fn main() {}
    /// ```
    #[must_use]
    pub fn extra_anchors(&self) -> &[Anchor] {
        &self.extra_anchors
    }

    /// Replaces the text and rebuilds the anchors from it: those of its
    /// headings and those of its anchor definitions.
    ///
    /// CRLF and lone CR become a line feed and a leading byte order mark is
    /// dropped. On error the chapter is unchanged.
    ///
    /// # Errors
    ///
    /// The text contains a control character other than line feed and tab.
    #[cfg(feature = "write")]
    pub fn set_text(&mut self, text: impl Into<String>) -> Result<()> {
        (self.text, self.anchors, self.extra_anchors) = stored(text.into())?;
        Ok(())
    }

    /// Tells whether a fragment with this name leads into the chapter.
    #[cfg(feature = "write")]
    fn has_anchor(&self, name: &str) -> bool {
        self.anchor_offset(name).is_some()
    }

    /// Where a fragment with this name leads: the offset of the anchor of a
    /// heading or of an extra one.
    #[cfg(feature = "write")]
    fn anchor_offset(&self, name: &str) -> Option<u32> {
        self.anchors
            .iter()
            .chain(&self.extra_anchors)
            .find(|anchor| anchor.name == name)
            .map(|anchor| anchor.offset)
    }
}

/// The stored form of chapter text, the anchors of its headings and its
/// extra anchors.
#[cfg(feature = "write")]
fn stored(text: String) -> Result<(String, Vec<Anchor>, Vec<Anchor>)> {
    let text = text::normalize(text)?;
    // Positions inside a chapter are 32-bit offsets.
    if u32::try_from(text.len()).is_err() {
        return Err(Error::Limit("a chapter must be smaller than 4 GiB"));
    }
    let analysis = analysis::analyse(&text);
    let anchors = analysis::anchors(&analysis.headings);
    let extra_anchors = analysis::extra_anchors(&analysis.named_lines, &anchors);
    Ok((text, anchors, extra_anchors))
}

impl Picture {
    /// Reads the pixel size from the AVIF file.
    #[cfg(feature = "write")]
    fn new(path: String, data: Vec<u8>) -> Result<Self> {
        let size = avif::displayed_size(&data).map_err(Error::InvalidPicture)?;
        Ok(Self { path, size, data })
    }

    /// The path of the picture inside the book.
    #[must_use]
    pub fn path(&self) -> &str {
        &self.path
    }

    /// The size in pixels, as displayed.
    #[must_use]
    pub fn size(&self) -> Size {
        self.size
    }

    /// The AVIF file.
    #[must_use]
    pub fn data(&self) -> &[u8] {
        &self.data
    }
}

/// The stored form of the source of a diagram or of a formula.
///
/// The encoding is that of a chapter: CRLF and lone CR become a line feed and
/// a leading byte order mark is dropped. A source without a character that is
/// not white space describes nothing and is refused.
#[cfg(feature = "write")]
fn stored_source(source: String) -> Result<String, SourceError> {
    let source = text::normalize(source)?;
    if source.trim().is_empty() {
        return Err(SourceError::Empty);
    }
    Ok(source)
}

impl Diagram {
    /// Normalises the source.
    #[cfg(feature = "write")]
    fn new(path: String, source: String) -> Result<Self> {
        let source = stored_source(source).map_err(Error::InvalidDiagram)?;
        Ok(Self { path, source })
    }

    /// The path of the diagram inside the book.
    #[must_use]
    pub fn path(&self) -> &str {
        &self.path
    }

    /// The description of the diagram in Mermaid notation, in the form it is
    /// stored in.
    #[must_use]
    pub fn source(&self) -> &str {
        &self.source
    }

    /// Replaces the description of the diagram.
    ///
    /// CRLF and lone CR become a line feed and a leading byte order mark is
    /// dropped. On error the diagram is unchanged.
    ///
    /// # Errors
    ///
    /// The source is empty, or contains a control character other than line
    /// feed and tab.
    #[cfg(feature = "write")]
    pub fn set_source(&mut self, source: impl Into<String>) -> Result<()> {
        self.source = stored_source(source.into()).map_err(Error::InvalidDiagram)?;
        Ok(())
    }
}

impl Formula {
    /// Normalises the source.
    #[cfg(feature = "write")]
    fn new(path: String, source: String) -> Result<Self> {
        let source = stored_source(source).map_err(Error::InvalidFormula)?;
        Ok(Self { path, source })
    }

    /// The path of the formula inside the book.
    #[must_use]
    pub fn path(&self) -> &str {
        &self.path
    }

    /// The formula in the notation of `KaTeX`, in the form it is stored in.
    #[must_use]
    pub fn source(&self) -> &str {
        &self.source
    }

    /// Replaces the formula.
    ///
    /// CRLF and lone CR become a line feed and a leading byte order mark is
    /// dropped. On error the formula is unchanged.
    ///
    /// # Errors
    ///
    /// The source is empty, or contains a control character other than line
    /// feed and tab.
    #[cfg(feature = "write")]
    pub fn set_source(&mut self, source: impl Into<String>) -> Result<()> {
        self.source = stored_source(source.into()).map_err(Error::InvalidFormula)?;
        Ok(())
    }
}

/// Looking at a book.
impl Book {
    /// The metadata.
    #[must_use]
    pub fn meta(&self) -> &Meta {
        &self.meta
    }

    /// The chapters, in reading order.
    #[must_use]
    pub fn chapters(&self) -> &[Chapter] {
        &self.chapters
    }

    /// The chapter with this path.
    #[must_use]
    pub fn chapter(&self, path: &str) -> Option<&Chapter> {
        match self.slots.get(path)? {
            Slot::Chapter(index) => self.chapters.get(*index),
            _ => None,
        }
    }

    /// The pictures, in the order they were added.
    #[must_use]
    pub fn pictures(&self) -> &[Picture] {
        &self.pictures
    }

    /// The picture with this path.
    #[must_use]
    pub fn picture(&self, path: &str) -> Option<&Picture> {
        match self.slots.get(path)? {
            Slot::Picture(index) => self.pictures.get(*index),
            _ => None,
        }
    }

    /// The diagrams, in the order they were added.
    #[must_use]
    pub fn diagrams(&self) -> &[Diagram] {
        &self.diagrams
    }

    /// The diagram with this path.
    #[must_use]
    pub fn diagram(&self, path: &str) -> Option<&Diagram> {
        match self.slots.get(path)? {
            Slot::Diagram(index) => self.diagrams.get(*index),
            _ => None,
        }
    }

    /// The formulas, in the order they were added.
    #[must_use]
    pub fn formulas(&self) -> &[Formula] {
        &self.formulas
    }

    /// The formula with this path.
    #[must_use]
    pub fn formula(&self, path: &str) -> Option<&Formula> {
        match self.slots.get(path)? {
            Slot::Formula(index) => self.formulas.get(*index),
            _ => None,
        }
    }

    /// The table of contents.
    #[must_use]
    pub fn toc(&self) -> &Toc {
        &self.toc
    }

    /// The landmarks: the notable places of the book, in the order an
    /// application lists them. Empty for a book that has none.
    #[must_use]
    pub fn landmarks(&self) -> &[Landmark] {
        &self.landmarks
    }
}

/// Bookkeeping shared by loading and editing.
impl Book {
    /// A book that holds only its metadata.
    fn empty(meta: Meta) -> Self {
        Self {
            meta,
            chapters: Vec::new(),
            pictures: Vec::new(),
            diagrams: Vec::new(),
            formulas: Vec::new(),
            toc: Toc::default(),
            landmarks: Vec::new(),
            slots: HashMap::new(),
        }
    }

    /// Puts a chapter with a free path at a valid position.
    fn place_chapter(&mut self, index: usize, chapter: Chapter) -> &mut Chapter {
        self.slots
            .insert(chapter.path.clone(), Slot::Chapter(index));
        self.chapters.insert(index, chapter);
        self.renumber_chapters(index + 1);
        &mut self.chapters[index]
    }

    /// Puts a picture with a free path after the others.
    fn place_picture(&mut self, picture: Picture) -> &Picture {
        let index = self.pictures.len();
        self.slots
            .insert(picture.path.clone(), Slot::Picture(index));
        self.pictures.push(picture);
        &self.pictures[index]
    }

    /// Puts a diagram with a free path after the others.
    fn place_diagram(&mut self, diagram: Diagram) -> &mut Diagram {
        let index = self.diagrams.len();
        self.slots
            .insert(diagram.path.clone(), Slot::Diagram(index));
        self.diagrams.push(diagram);
        &mut self.diagrams[index]
    }

    /// Puts a formula with a free path after the others.
    fn place_formula(&mut self, formula: Formula) -> &mut Formula {
        let index = self.formulas.len();
        self.slots
            .insert(formula.path.clone(), Slot::Formula(index));
        self.formulas.push(formula);
        &mut self.formulas[index]
    }

    /// Updates the slots of the chapters from `from` on after a shift.
    fn renumber_chapters(&mut self, from: usize) {
        let paths = self.chapters.iter().map(|chapter| chapter.path.as_str());
        renumber(&mut self.slots, paths, from, Slot::Chapter);
    }
}

/// Points the slots of the items from `from` on at their places after a
/// shift. `paths` holds the path of every item, in order.
fn renumber<'a>(
    slots: &mut HashMap<String, Slot>,
    paths: impl Iterator<Item = &'a str>,
    from: usize,
    slot_of: impl Fn(usize) -> Slot,
) {
    for (index, path) in paths.enumerate().skip(from) {
        if let Some(slot) = slots.get_mut(path) {
            *slot = slot_of(index);
        }
    }
}

/// Creating, changing and saving a book.
#[cfg(feature = "write")]
impl Book {
    /// A book with a title and a main language, and nothing else.
    ///
    /// The book gets a new UUID version 7 as its identifier; replace it with
    /// [`Meta::set_id`] when the source has a stable one. The table of
    /// contents is built from the headings unless [`set_toc`](Self::set_toc)
    /// says otherwise.
    ///
    /// # Errors
    ///
    /// The title is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// let book = mbook::Book::new("The Example", "en")?;
    /// assert!(book.meta().id().starts_with("urn:uuid:"));
    /// # Ok::<(), mbook::Error>(())
    /// ```
    pub fn new(title: impl Into<String>, language: impl Into<String>) -> Result<Self> {
        let id = format!("urn:uuid:{}", uuid::Uuid::now_v7());
        Ok(Self::empty(Meta::new(title.into(), language.into(), id)?))
    }

    /// The metadata, for changing it.
    pub fn meta_mut(&mut self) -> &mut Meta {
        &mut self.meta
    }

    /// The chapter with this path, for changing its text.
    pub fn chapter_mut(&mut self, path: &str) -> Option<&mut Chapter> {
        match self.slots.get(path)? {
            Slot::Chapter(index) => self.chapters.get_mut(*index),
            _ => None,
        }
    }

    /// Adds a chapter at the end of the reading order.
    ///
    /// CRLF and lone CR in the text become a line feed and a leading byte
    /// order mark is dropped.
    ///
    /// # Errors
    ///
    /// The path is not valid or is already used, or the text contains a
    /// control character other than line feed and tab.
    pub fn add_chapter(
        &mut self,
        path: impl Into<String>,
        text: impl Into<String>,
    ) -> Result<&mut Chapter> {
        self.insert_chapter(self.chapters.len(), path, text)
    }

    /// Adds a chapter at a position in the reading order; the chapters from
    /// that position on move one place later.
    ///
    /// # Errors
    ///
    /// As [`add_chapter`](Self::add_chapter), or `index` is greater than the
    /// number of chapters.
    pub fn insert_chapter(
        &mut self,
        index: usize,
        path: impl Into<String>,
        text: impl Into<String>,
    ) -> Result<&mut Chapter> {
        self.check_position(index, self.chapters.len())?;
        let path = self.free_path(path.into())?;
        let chapter = Chapter::new(path, text.into())?;
        Ok(self.place_chapter(index, chapter))
    }

    /// Moves a chapter to another position in the reading order.
    ///
    /// # Errors
    ///
    /// No chapter has this path, or `index` is not less than the number of
    /// chapters.
    pub fn move_chapter(&mut self, path: &str, index: usize) -> Result<()> {
        let Some(Slot::Chapter(from)) = self.slots.get(path).copied() else {
            return Err(Error::NoSuchPath(path.to_owned()));
        };
        self.check_position(index, self.chapters.len() - 1)?;
        let chapter = self.chapters.remove(from);
        self.chapters.insert(index, chapter);
        self.renumber_chapters(from.min(index));
        Ok(())
    }

    /// Removes a chapter and returns it.
    ///
    /// Links to it from other chapters are reported when the book is written.
    pub fn remove_chapter(&mut self, path: &str) -> Option<Chapter> {
        let Slot::Chapter(index) = self.slots.get(path).copied()? else {
            return None;
        };
        self.slots.remove(path);
        let chapter = self.chapters.remove(index);
        self.renumber_chapters(index);
        Some(chapter)
    }

    /// Adds a picture. The pixel size is read from the AVIF file.
    ///
    /// # Errors
    ///
    /// The path is not valid or is already used, or the bytes are not an AVIF
    /// file with a primary image.
    pub fn add_picture(
        &mut self,
        path: impl Into<String>,
        avif: impl Into<Vec<u8>>,
    ) -> Result<&Picture> {
        let path = self.free_path(path.into())?;
        let picture = Picture::new(path, avif.into())?;
        Ok(self.place_picture(picture))
    }

    /// Removes a picture and returns it.
    ///
    /// References to it from chapters, and from the `cover` key, are reported
    /// when the book is written.
    pub fn remove_picture(&mut self, path: &str) -> Option<Picture> {
        let Slot::Picture(index) = self.slots.get(path).copied()? else {
            return None;
        };
        self.slots.remove(path);
        let picture = self.pictures.remove(index);
        let paths = self.pictures.iter().map(|picture| picture.path.as_str());
        renumber(&mut self.slots, paths, index, Slot::Picture);
        Some(picture)
    }

    /// The diagram with this path, for changing its source.
    pub fn diagram_mut(&mut self, path: &str) -> Option<&mut Diagram> {
        match self.slots.get(path)? {
            Slot::Diagram(index) => self.diagrams.get_mut(*index),
            _ => None,
        }
    }

    /// Adds a diagram, described in Mermaid notation.
    ///
    /// A chapter shows it the way it shows a picture, by its path:
    /// `![The flow of a request](dia/flow.mmd)`. CRLF and lone CR in the
    /// source become a line feed and a leading byte order mark is dropped.
    /// The notation itself is not checked: a reading application shows the
    /// alternative text of a diagram it cannot draw.
    ///
    /// # Errors
    ///
    /// The path is not valid or is already used, or the source is empty or
    /// contains a control character other than line feed and tab.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut book = mbook::Book::new("The Example", "en")?;
    /// book.add_diagram("dia/flow.mmd", "flowchart LR\n  A --> B\n")?;
    /// book.add_chapter("ch01.md", "![From A to B](dia/flow.mmd)\n")?;
    /// assert!(book.check().is_ok());
    /// # Ok::<(), mbook::Error>(())
    /// ```
    pub fn add_diagram(
        &mut self,
        path: impl Into<String>,
        source: impl Into<String>,
    ) -> Result<&mut Diagram> {
        let path = self.free_path(path.into())?;
        let diagram = Diagram::new(path, source.into())?;
        Ok(self.place_diagram(diagram))
    }

    /// Removes a diagram and returns it.
    ///
    /// References to it from chapters are reported when the book is written.
    pub fn remove_diagram(&mut self, path: &str) -> Option<Diagram> {
        let Slot::Diagram(index) = self.slots.get(path).copied()? else {
            return None;
        };
        self.slots.remove(path);
        let diagram = self.diagrams.remove(index);
        let paths = self.diagrams.iter().map(|diagram| diagram.path.as_str());
        renumber(&mut self.slots, paths, index, Slot::Diagram);
        Some(diagram)
    }

    /// The formula with this path, for changing its source.
    pub fn formula_mut(&mut self, path: &str) -> Option<&mut Formula> {
        match self.slots.get(path)? {
            Slot::Formula(index) => self.formulas.get_mut(*index),
            _ => None,
        }
    }

    /// Adds a formula, written in the notation of `KaTeX` without the `$`
    /// that surround a formula in running text.
    ///
    /// A chapter shows it the way it shows a picture, by its path:
    /// `![E = mc^2](math/e.tex)`. CRLF and lone CR in the source become a
    /// line feed and a leading byte order mark is dropped. The notation
    /// itself is not checked: a reading application shows the alternative
    /// text of a formula it cannot set.
    ///
    /// # Errors
    ///
    /// The path is not valid or is already used, or the source is empty or
    /// contains a control character other than line feed and tab.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut book = mbook::Book::new("The Example", "en")?;
    /// book.add_formula("math/e.tex", "E = mc^2")?;
    /// book.add_chapter("ch01.md", "Mass is energy: ![E = mc^2](math/e.tex).\n")?;
    /// assert!(book.check().is_ok());
    /// # Ok::<(), mbook::Error>(())
    /// ```
    pub fn add_formula(
        &mut self,
        path: impl Into<String>,
        source: impl Into<String>,
    ) -> Result<&mut Formula> {
        let path = self.free_path(path.into())?;
        let formula = Formula::new(path, source.into())?;
        Ok(self.place_formula(formula))
    }

    /// Removes a formula and returns it.
    ///
    /// References to it from chapters are reported when the book is written.
    pub fn remove_formula(&mut self, path: &str) -> Option<Formula> {
        let Slot::Formula(index) = self.slots.get(path).copied()? else {
            return None;
        };
        self.slots.remove(path);
        let formula = self.formulas.remove(index);
        let paths = self.formulas.iter().map(|formula| formula.path.as_str());
        renumber(&mut self.slots, paths, index, Slot::Formula);
        Some(formula)
    }

    /// Adds a picture and makes it the cover.
    ///
    /// A picture that was the cover before stays in the book.
    ///
    /// # Errors
    ///
    /// As [`add_picture`](Self::add_picture).
    pub fn set_cover(
        &mut self,
        path: impl Into<String>,
        avif: impl Into<Vec<u8>>,
    ) -> Result<&Picture> {
        let path = self.free_path(path.into())?;
        let picture = Picture::new(path.clone(), avif.into())?;
        self.meta.set_cover(path)?;
        Ok(self.place_picture(picture))
    }

    /// Replaces the table of contents.
    pub fn set_toc(&mut self, toc: Toc) {
        self.toc = toc;
    }

    /// Replaces the landmarks. An empty list removes them.
    ///
    /// Whether every landmark leads somewhere is checked when the book is
    /// written, like the items of the contents. On error the book is
    /// unchanged.
    ///
    /// # Errors
    ///
    /// A kind does not match `[a-z0-9]+(-[a-z0-9]+)*`, or more than one
    /// landmark has the kind `start`.
    ///
    /// # Examples
    ///
    /// ```
    /// use mbook::{Book, Landmark};
    ///
    /// let mut book = Book::new("The Example", "en")?;
    /// book.add_chapter("ch01.md", "# Arrival\n")?;
    /// book.set_landmarks(vec![Landmark::new("start", "", "ch01.md")])?;
    /// assert_eq!(book.landmarks().len(), 1);
    /// # Ok::<(), mbook::Error>(())
    /// ```
    pub fn set_landmarks(&mut self, landmarks: Vec<Landmark>) -> Result<()> {
        let invalid = landmarks
            .iter()
            .find(|landmark| !crate::meta::is_key(&landmark.kind));
        if let Some(landmark) = invalid {
            return Err(LandmarkError::InvalidKind(landmark.kind.clone()).into());
        }
        if landmarks.iter().filter(|l| l.kind == "start").count() > 1 {
            return Err(LandmarkError::RepeatedStart.into());
        }
        self.landmarks = landmarks;
        Ok(())
    }

    /// An index into the reading order must not be greater than `max`.
    fn check_position(&self, index: usize, max: usize) -> Result<()> {
        if index > max {
            return Err(Error::IndexOutOfRange {
                index,
                len: self.chapters.len(),
            });
        }
        Ok(())
    }

    /// Checks that a path is valid and not used yet, and hands it back.
    fn free_path(&self, path: String) -> Result<String> {
        if let Err(reason) = path::validate(&path) {
            return Err(Error::InvalidPath { path, reason });
        }
        if self.slots.contains_key(&path) {
            return Err(Error::DuplicatePath(path));
        }
        Ok(path)
    }
}

#[cfg(test)]
#[cfg(feature = "write")]
mod tests {
    use super::{Book, Chapter, Diagram, Formula, Landmark, Picture, Toc, TocItem};
    use crate::error::{Error, LandmarkError, PathError, SourceError};
    use crate::types::Size;

    /// A chapter with one heading and two paragraphs, the first of them
    /// named.
    const TEXT: &str = "# One\n\n[remark]: #remark\nA remark.\n\nMore.\n";

    fn analysed(text: &str) -> Chapter {
        Chapter::new("ch01.md".to_owned(), text.to_owned()).unwrap()
    }

    fn extra(chapter: &Chapter) -> Vec<(&str, u32)> {
        let anchors = chapter.extra_anchors().iter();
        anchors
            .map(|anchor| (anchor.name.as_str(), anchor.offset))
            .collect()
    }

    #[test]
    fn an_anchor_definition_names_its_line() {
        assert_eq!(extra(&analysed(TEXT)), [("remark", 7)]);
    }

    #[test]
    fn an_anchor_definition_leaves_the_anchors_of_headings_alone() {
        let chapter = analysed(TEXT);
        let names: Vec<_> = chapter.anchors().iter().map(|a| a.name.as_str()).collect();
        assert_eq!(names, ["one"]);
    }

    #[test]
    fn a_chapter_without_anchor_definitions_has_no_extra_anchors() {
        assert_eq!(analysed("# One\n\nText.\n").extra_anchors(), []);
    }

    #[test]
    fn set_text_moves_an_extra_anchor_with_its_line() {
        let mut chapter = analysed(TEXT);
        let edited = chapter.text().replace("# One", "# One and a half");
        chapter.set_text(edited).unwrap();
        assert_eq!(extra(&chapter), [("remark", 18)]);
    }

    #[test]
    fn set_text_drops_an_extra_anchor_whose_definition_is_gone() {
        let mut chapter = analysed(TEXT);
        chapter.set_text("# One\n\nA remark.\n").unwrap();
        assert_eq!(chapter.extra_anchors(), []);
    }

    #[test]
    fn set_text_finds_a_new_anchor_definition() {
        let mut chapter = analysed("# One\n\nMore.\n");
        chapter.set_text("# One\n\n[more]: #more\nMore.\n").unwrap();
        assert_eq!(extra(&chapter), [("more", 7)]);
    }

    #[test]
    fn a_text_that_is_refused_keeps_the_extra_anchors() {
        let mut chapter = analysed(TEXT);
        assert!(chapter.set_text("bad \u{1b} text").is_err());
        assert_eq!(extra(&chapter), [("remark", 7)]);
    }

    /// A chapter built by hand, for the tests that only move chapters.
    fn chapter(path: &str) -> Chapter {
        Chapter {
            path: path.to_owned(),
            text: format!("# {path}\n"),
            anchors: Vec::new(),
            extra_anchors: Vec::new(),
        }
    }

    fn picture(path: &str) -> Picture {
        Picture {
            path: path.to_owned(),
            size: Size {
                width: 1,
                height: 1,
            },
            data: Vec::new(),
        }
    }

    /// A book with three chapters and two pictures.
    fn book() -> Book {
        let mut book = Book::new("The Example", "en").unwrap();
        for path in ["ch01.md", "ch02.md", "ch03.md"] {
            book.place_chapter(book.chapters.len(), chapter(path));
        }
        for path in ["img/a.avif", "img/b.avif"] {
            book.place_picture(picture(path));
        }
        book
    }

    fn reading_order(book: &Book) -> Vec<&str> {
        book.chapters().iter().map(Chapter::path).collect()
    }

    /// Every path finds the item that carries it.
    fn slots_agree(book: &Book) -> bool {
        let chapters = book
            .chapters()
            .iter()
            .all(|c| book.chapter(c.path()) == Some(c));
        let pictures = book
            .pictures()
            .iter()
            .all(|p| book.picture(p.path()) == Some(p));
        let diagrams = book
            .diagrams()
            .iter()
            .all(|d| book.diagram(d.path()) == Some(d));
        let formulas = book
            .formulas()
            .iter()
            .all(|f| book.formula(f.path()) == Some(f));
        let items =
            book.chapters.len() + book.pictures.len() + book.diagrams.len() + book.formulas.len();
        chapters && pictures && diagrams && formulas && book.slots.len() == items
    }

    /// The example with two diagrams and two formulas.
    fn illustrated() -> Book {
        let mut book = book();
        for path in ["dia/a.mmd", "dia/b.mmd"] {
            book.add_diagram(path, "flowchart LR\n  A --> B\n").unwrap();
        }
        for path in ["math/a.tex", "math/b.tex"] {
            book.add_formula(path, "E = mc^2").unwrap();
        }
        book
    }

    #[test]
    fn a_diagram_exposes_its_path_and_source() {
        let book = illustrated();
        let diagram = book.diagram("dia/a.mmd").unwrap();
        assert_eq!(
            (diagram.path(), diagram.source()),
            ("dia/a.mmd", "flowchart LR\n  A --> B\n")
        );
    }

    #[test]
    fn a_formula_exposes_its_path_and_source() {
        let book = illustrated();
        let formula = book.formula("math/b.tex").unwrap();
        assert_eq!(
            (formula.path(), formula.source()),
            ("math/b.tex", "E = mc^2")
        );
    }

    #[test]
    fn diagrams_and_formulas_are_listed_in_the_order_they_were_added() {
        let book = illustrated();
        let diagrams: Vec<_> = book.diagrams().iter().map(Diagram::path).collect();
        let formulas: Vec<_> = book.formulas().iter().map(Formula::path).collect();
        assert_eq!(
            (diagrams, formulas),
            (
                vec!["dia/a.mmd", "dia/b.mmd"],
                vec!["math/a.tex", "math/b.tex"]
            )
        );
        assert!(slots_agree(&book));
    }

    #[test]
    fn a_path_of_another_kind_is_neither_a_diagram_nor_a_formula() {
        let mut book = illustrated();
        assert!(book.diagram("math/a.tex").is_none());
        assert!(book.diagram("ch01.md").is_none());
        assert!(book.formula("dia/a.mmd").is_none());
        assert!(book.formula("img/a.avif").is_none());
        assert!(book.diagram_mut("math/a.tex").is_none());
        assert!(book.formula_mut("dia/a.mmd").is_none());
        assert!(book.picture("dia/a.mmd").is_none());
        assert!(book.chapter("math/a.tex").is_none());
        assert!(book.chapter_mut("dia/a.mmd").is_none());
    }

    #[test]
    fn a_source_is_stored_with_line_feeds_and_without_a_byte_order_mark() {
        let mut book = book();
        let diagram = book.add_diagram("d.mmd", "\u{feff}flowchart LR\r\n  A --> B\r");
        assert_eq!(
            diagram.map(|diagram| diagram.source().to_owned()).unwrap(),
            "flowchart LR\n  A --> B\n"
        );
        let formula = book.add_formula("f.tex", "a\r\n+ b");
        assert_eq!(
            formula.map(|formula| formula.source().to_owned()).unwrap(),
            "a\n+ b"
        );
    }

    #[test]
    fn a_source_without_a_visible_character_is_refused() {
        let mut book = book();
        let diagram = book.add_diagram("d.mmd", " \n\t\n");
        assert!(matches!(
            diagram,
            Err(Error::InvalidDiagram(SourceError::Empty))
        ));
        let formula = book.add_formula("f.tex", "");
        assert!(matches!(
            formula,
            Err(Error::InvalidFormula(SourceError::Empty))
        ));
        assert!(slots_agree(&book));
    }

    #[test]
    fn a_source_with_a_control_character_is_refused_with_its_place() {
        let mut book = book();
        let diagram = book.add_diagram("d.mmd", "flow\u{1b}chart");
        assert!(matches!(
            diagram,
            Err(Error::InvalidDiagram(SourceError::ForbiddenCharacter(found)))
                if (found.offset, found.character) == (4, '\u{1b}')
        ));
        let formula = book.add_formula("f.tex", "\0");
        assert!(matches!(
            formula,
            Err(Error::InvalidFormula(SourceError::ForbiddenCharacter(found)))
                if found.offset == 0
        ));
    }

    #[test]
    fn a_diagram_and_a_formula_need_a_free_and_valid_path() {
        let mut book = illustrated();
        assert!(matches!(
            book.add_diagram("ch01.md", "flowchart LR"),
            Err(Error::DuplicatePath(path)) if path == "ch01.md"
        ));
        assert!(matches!(
            book.add_formula("dia/a.mmd", "x"),
            Err(Error::DuplicatePath(path)) if path == "dia/a.mmd"
        ));
        assert!(matches!(
            book.add_diagram("/d.mmd", "flowchart LR"),
            Err(Error::InvalidPath {
                reason: PathError::EmptySegment,
                ..
            })
        ));
        assert!(matches!(
            book.add_formula("", "x"),
            Err(Error::InvalidPath {
                reason: PathError::Empty,
                ..
            })
        ));
        assert!(matches!(
            book.add_chapter("math/a.tex", "text"),
            Err(Error::DuplicatePath(path)) if path == "math/a.tex"
        ));
    }

    #[test]
    fn set_source_replaces_the_source_of_a_diagram_and_of_a_formula() {
        let mut book = illustrated();
        let diagram = book.diagram_mut("dia/b.mmd").unwrap();
        diagram
            .set_source("sequenceDiagram\r\n  A->>B: hi")
            .unwrap();
        assert_eq!(diagram.source(), "sequenceDiagram\n  A->>B: hi");
        let formula = book.formula_mut("math/a.tex").unwrap();
        formula.set_source("a^2 + b^2 = c^2").unwrap();
        assert_eq!(formula.source(), "a^2 + b^2 = c^2");
    }

    #[test]
    fn a_source_that_is_refused_keeps_the_one_before() {
        let mut book = illustrated();
        let diagram = book.diagram_mut("dia/a.mmd").unwrap();
        assert!(matches!(
            diagram.set_source("  "),
            Err(Error::InvalidDiagram(SourceError::Empty))
        ));
        assert_eq!(diagram.source(), "flowchart LR\n  A --> B\n");
        let formula = book.formula_mut("math/a.tex").unwrap();
        assert!(matches!(
            formula.set_source("x\u{7}"),
            Err(Error::InvalidFormula(SourceError::ForbiddenCharacter(_)))
        ));
        assert_eq!(formula.source(), "E = mc^2");
    }

    #[test]
    fn slots_follow_a_removed_diagram_and_a_removed_formula() {
        let mut book = illustrated();
        let diagram = book.remove_diagram("dia/a.mmd");
        let formula = book.remove_formula("math/a.tex");
        assert_eq!(diagram.as_ref().map(Diagram::path), Some("dia/a.mmd"));
        assert_eq!(formula.as_ref().map(Formula::path), Some("math/a.tex"));
        assert_eq!(
            book.diagram("dia/b.mmd").map(Diagram::path),
            Some("dia/b.mmd")
        );
        assert_eq!(
            book.formula("math/b.tex").map(Formula::path),
            Some("math/b.tex")
        );
        assert!(slots_agree(&book));
    }

    #[test]
    fn removing_ignores_a_path_of_another_kind() {
        let mut book = illustrated();
        assert!(book.remove_diagram("math/a.tex").is_none());
        assert!(book.remove_diagram("nothing.mmd").is_none());
        assert!(book.remove_formula("dia/a.mmd").is_none());
        assert!(book.remove_picture("dia/a.mmd").is_none());
        assert!(book.remove_chapter("math/a.tex").is_none());
        assert!(slots_agree(&book));
    }

    #[test]
    fn a_chapter_exposes_its_path_text_and_anchors() {
        let chapter = chapter("ch01.md");
        assert_eq!(
            (chapter.path(), chapter.text(), chapter.anchors().len()),
            ("ch01.md", "# ch01.md\n", 0)
        );
    }

    #[test]
    fn a_picture_exposes_its_path_size_and_data() {
        let picture = picture("img/a.avif");
        let size = Size {
            width: 1,
            height: 1,
        };
        assert_eq!(
            (picture.path(), picture.size(), picture.data()),
            ("img/a.avif", size, &[][..])
        );
    }

    #[test]
    fn pictures_are_found_by_path() {
        let book = book();
        assert_eq!(
            book.picture("img/b.avif").map(Picture::path),
            Some("img/b.avif")
        );
    }

    #[test]
    fn a_chapter_path_is_not_a_picture() {
        assert!(book().picture("ch01.md").is_none());
    }

    #[test]
    fn chapter_mut_finds_the_chapter_to_change() {
        let mut book = book();
        assert_eq!(
            book.chapter_mut("ch03.md").map(|c| c.path().to_owned()),
            Some("ch03.md".to_owned())
        );
    }

    #[test]
    fn chapter_mut_ignores_a_picture_path() {
        assert!(book().chapter_mut("img/a.avif").is_none());
    }

    #[test]
    fn remove_picture_returns_the_picture() {
        let removed = book().remove_picture("img/a.avif");
        assert_eq!(removed.as_ref().map(Picture::path), Some("img/a.avif"));
    }

    #[test]
    fn remove_picture_ignores_a_chapter_path() {
        assert!(book().remove_picture("ch01.md").is_none());
    }

    #[test]
    fn new_book_lists_every_heading_in_its_contents() {
        let book = Book::new("The Example", "en").unwrap();
        assert_eq!(book.toc(), &Toc::FromHeadings { max_level: 6 });
    }

    #[test]
    fn new_book_gets_a_version_7_uuid() {
        let book = Book::new("The Example", "en").unwrap();
        let id = book.meta().id().strip_prefix("urn:uuid:").unwrap();
        assert_eq!(id.as_bytes()[14], b'7');
    }

    #[test]
    fn new_rejects_an_empty_title() {
        assert!(matches!(Book::new("", "en"), Err(Error::InvalidMeta(_))));
    }

    #[test]
    fn chapters_are_found_by_path() {
        let book = book();
        assert_eq!(book.chapter("ch02.md").map(Chapter::path), Some("ch02.md"));
    }

    #[test]
    fn a_picture_path_is_not_a_chapter() {
        assert!(book().chapter("img/a.avif").is_none());
    }

    #[test]
    fn placing_a_chapter_in_the_middle_shifts_the_later_ones() {
        let mut book = book();
        book.place_chapter(1, chapter("intro.md"));
        assert_eq!(
            reading_order(&book),
            ["ch01.md", "intro.md", "ch02.md", "ch03.md"]
        );
    }

    #[test]
    fn slots_follow_a_chapter_placed_in_the_middle() {
        let mut book = book();
        book.place_chapter(1, chapter("intro.md"));
        assert!(slots_agree(&book));
    }

    #[test]
    fn remove_chapter_returns_the_chapter() {
        let removed = book().remove_chapter("ch02.md");
        assert_eq!(removed.as_ref().map(Chapter::path), Some("ch02.md"));
    }

    #[test]
    fn slots_follow_a_removed_chapter() {
        let mut book = book();
        book.remove_chapter("ch01.md");
        assert!(slots_agree(&book));
    }

    #[test]
    fn remove_chapter_ignores_a_picture_path() {
        let mut book = book();
        assert!(book.remove_chapter("img/a.avif").is_none());
    }

    #[test]
    fn move_chapter_to_the_end_changes_the_reading_order() {
        let mut book = book();
        book.move_chapter("ch01.md", 2).unwrap();
        assert_eq!(reading_order(&book), ["ch02.md", "ch03.md", "ch01.md"]);
    }

    #[test]
    fn move_chapter_to_the_start_changes_the_reading_order() {
        let mut book = book();
        book.move_chapter("ch03.md", 0).unwrap();
        assert_eq!(reading_order(&book), ["ch03.md", "ch01.md", "ch02.md"]);
    }

    #[test]
    fn slots_follow_a_moved_chapter() {
        let mut book = book();
        book.move_chapter("ch03.md", 0).unwrap();
        assert!(slots_agree(&book));
    }

    #[test]
    fn move_chapter_rejects_a_position_past_the_end() {
        let result = book().move_chapter("ch01.md", 3);
        assert!(matches!(
            result,
            Err(Error::IndexOutOfRange { index: 3, len: 3 })
        ));
    }

    #[test]
    fn move_chapter_rejects_an_unknown_path() {
        let result = book().move_chapter("nope.md", 0);
        assert!(matches!(result, Err(Error::NoSuchPath(path)) if path == "nope.md"));
    }

    #[test]
    fn slots_follow_a_removed_picture() {
        let mut book = book();
        book.remove_picture("img/a.avif");
        assert!(slots_agree(&book));
    }

    #[test]
    fn add_chapter_rejects_a_path_used_by_a_picture() {
        let mut book = book();
        let result = book.add_chapter("img/a.avif", "text");
        assert!(matches!(result, Err(Error::DuplicatePath(path)) if path == "img/a.avif"));
    }

    #[test]
    fn add_picture_rejects_an_invalid_path() {
        let mut book = book();
        let result = book.add_picture("../cover.avif", Vec::new());
        let reason = PathError::DotSegment;
        assert!(matches!(result, Err(Error::InvalidPath { reason: r, .. }) if r == reason));
    }

    #[test]
    fn insert_chapter_rejects_a_position_past_the_end() {
        let mut book = book();
        let result = book.insert_chapter(4, "ch04.md", "text");
        assert!(matches!(
            result,
            Err(Error::IndexOutOfRange { index: 4, len: 3 })
        ));
    }

    #[test]
    fn a_landmark_is_built_from_a_link_destination() {
        let whole = Landmark::new("start", "", "ch01.md");
        let inside = Landmark::new("index", "The Index", "back.md#index");
        assert_eq!(
            (whole.kind.as_str(), whole.chapter.as_str(), whole.anchor),
            ("start", "ch01.md", None)
        );
        assert_eq!(
            (inside.title.as_str(), inside.anchor.as_deref()),
            ("The Index", Some("index"))
        );
    }

    #[test]
    fn set_landmarks_replaces_the_landmarks() {
        let mut book = book();
        book.set_landmarks(vec![Landmark::new("start", "", "ch01.md")])
            .unwrap();
        book.set_landmarks(vec![
            Landmark::new("appendix", "A", "ch02.md"),
            Landmark::new("appendix", "B", "ch03.md"),
            Landmark::new("x-maps", "Maps", "ch03.md"),
        ])
        .unwrap();
        let kinds: Vec<_> = book.landmarks().iter().map(|l| l.kind.as_str()).collect();
        assert_eq!(kinds, ["appendix", "appendix", "x-maps"]);
    }

    #[test]
    fn set_landmarks_rejects_a_kind_that_is_not_a_key() {
        let mut book = book();
        let result = book.set_landmarks(vec![Landmark::new("The Index", "", "ch01.md")]);
        assert!(matches!(
            result,
            Err(Error::InvalidLandmark(LandmarkError::InvalidKind(kind))) if kind == "The Index"
        ));
    }

    #[test]
    fn set_landmarks_rejects_a_second_start() {
        let mut book = book();
        let result = book.set_landmarks(vec![
            Landmark::new("start", "", "ch01.md"),
            Landmark::new("start", "", "ch02.md"),
        ]);
        assert!(matches!(
            result,
            Err(Error::InvalidLandmark(LandmarkError::RepeatedStart))
        ));
    }

    #[test]
    fn refused_landmarks_leave_the_book_as_it_was() {
        let mut book = book();
        book.set_landmarks(vec![Landmark::new("start", "", "ch01.md")])
            .unwrap();
        assert!(
            book.set_landmarks(vec![Landmark::new("", "", "ch01.md")])
                .is_err()
        );
        assert_eq!(book.landmarks().len(), 1);
    }

    #[test]
    fn a_new_book_has_no_landmarks() {
        assert_eq!(Book::new("The Example", "en").unwrap().landmarks(), []);
    }

    #[test]
    fn toc_item_without_a_fragment_leads_to_the_chapter_start() {
        assert_eq!(TocItem::new(1, "Arrival", "ch01.md").anchor, None);
    }

    #[test]
    fn toc_item_with_an_empty_fragment_leads_to_the_chapter_start() {
        assert_eq!(TocItem::new(1, "Arrival", "ch01.md#").anchor, None);
    }

    #[test]
    fn toc_item_splits_at_the_first_hash() {
        let item = TocItem::new(2, "Odd", "ch01.md#a#b");
        assert_eq!(
            (item.chapter.as_str(), item.anchor.as_deref()),
            ("ch01.md", Some("a#b"))
        );
    }
}