excelerate 0.12.3

Read, write and recalculate spreadsheets: xlsx, xls, ods, csv, html, and a 518-function formula engine
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
//! Writing xls (BIFF8).
//!
//! The records are the ones [`crate::reader::xls`] reads: the globals carry the
//! fonts, the number formats, the cell formats and the shared strings, and each
//! sheet is a substream of its own whose position the `BOUNDSHEET` record
//! names - which is why the sheets are laid out first and their positions
//! patched in afterwards.
//!
//! What is written: values of every type, shared strings (split over
//! `CONTINUE` records where they do not fit), the whole cell format - number
//! format, font, fill, borders, alignment and protection - merges, column
//! widths and row heights, and the workbook's base date.
//!
//! Colours go through the 56-entry palette ([`crate::shared::palette`]): a
//! colour the default palette has keeps its entry, one it lacks takes over an
//! entry no other colour of the workbook uses and a `PALETTE` record is
//! written, and past 56 distinct colours the rest get the nearest entry. Theme
//! colours are resolved through the workbook's theme first.
//!
//! Formulas are compiled into tokens ([`super::xls_formula`]) and written
//! with their result, and defined names go out as `NAME` records. A formula
//! BIFF8 cannot hold - a structured reference, a reference past row 65536 or
//! column IV - is written as its result, so the file still says what the sheet
//! showed.
//!
//! What is not:
//!
//! - Everything the model carries for xlsx and the old format has no room for:
//!   conditional formatting, data validation, rich text inside a cell, opaque
//!   parts.

use super::xls_formula::{self, Compiled, Links, Place};
use crate::error::{Error, Result};
use crate::formula::eval::{Engine, Origin};
use crate::formula::value::Value as FormulaValue;
use crate::model::{CellValue, PanePosition, PaneState, SheetView, Spreadsheet, Worksheet};
use crate::shared::date::Epoch;
use crate::shared::palette;
use crate::style::{
    BorderStyle, Color, DiagonalDirection, HorizontalAlign, NumberFormat, Pattern, ProtectionState,
    Script, Style, VerticalAlign,
};
use crate::{CellRef, Col, Row};
use std::collections::HashMap;
use std::io::Write;

/// The largest payload one record may carry; anything longer continues in a
/// `CONTINUE` record.
const MAX_PAYLOAD: usize = 8224;

/// The first index a format of our own may take; below it the format numbers
/// are Excel's own.
const FIRST_CUSTOM_FORMAT: u16 = 164;

/// Writes a workbook as an xls file.
///
/// # Errors
/// [`Error::Xls`] if the workbook has no sheets or the file cannot be written.
pub fn write_xls(book: &Spreadsheet, path: impl AsRef<std::path::Path>) -> Result<()> {
    let file = std::fs::File::create(path).map_err(|e| Error::Xls(e.to_string()))?;
    write_xls_to(book, std::io::BufWriter::new(file))
}

/// The same, to any sink.
///
/// # Errors
/// As [`write_xls`].
pub fn write_xls_to<W: Write>(book: &Spreadsheet, mut sink: W) -> Result<()> {
    let bytes = workbook_stream(book)?;
    let container = super::ole::container("Workbook", &bytes);
    sink.write_all(&container)
        .map_err(|e| Error::Xls(e.to_string()))?;
    sink.flush().map_err(|e| Error::Xls(e.to_string()))
}

/// Builds the whole `Workbook` stream: globals first, then one substream per
/// sheet.
fn workbook_stream(book: &Spreadsheet) -> Result<Vec<u8>> {
    if book.sheets().is_empty() {
        return Err(Error::Xls("a workbook needs at least one sheet".to_owned()));
    }
    let mut engine = Engine::new(book);
    let mut plan = Plan::new(book, &mut engine);

    // The sheets are built first: the globals name where each one starts, and
    // that is only known once the globals have their own length.
    let sheets: Vec<Vec<u8>> = (0..book.sheets().len())
        .filter_map(|i| book.sheet(i).map(|sheet| substream(sheet, i, &plan)))
        .collect();

    let mut globals = plan.globals(book);
    // `BOUNDSHEET` holds a position each; the placeholders are patched once the
    // globals are as long as they are going to be.
    let mut at = globals.len() + 4;
    let mut positions = Vec::with_capacity(sheets.len());
    for sheet in &sheets {
        positions.push(at);
        at += sheet.len();
    }
    for (offset, position) in plan.boundsheet_offsets.iter().zip(&positions) {
        let value = u32::try_from(*position).unwrap_or(0);
        globals[*offset..*offset + 4].copy_from_slice(&value.to_le_bytes());
    }
    record(&mut globals, 0x000A, &[]);

    let mut out = globals;
    for sheet in sheets {
        out.extend_from_slice(&sheet);
    }
    Ok(out)
}

/// What the globals hold, worked out before anything is written.
struct Plan {
    /// The palette every colour index refers to.
    palette: Colors,
    /// Every font of the style table, in the order they are written.
    fonts: Vec<crate::style::Font>,
    /// The font index of each style, by style id.
    font_of: Vec<u16>,
    /// The format index of each style, by style id.
    format_of: Vec<u16>,
    /// Format codes to spell out, with the index each takes.
    formats: Vec<(u16, String)>,
    /// Every distinct string, in the order the table holds them.
    strings: Vec<String>,
    /// Where each string sits in the table.
    string_index: HashMap<String, u32>,
    /// How many string cells there are altogether.
    string_uses: u32,
    /// What each formula cell works out to. A formula is written as its
    /// result, so the result has to be known before the string table is, and
    /// working it out twice would mean two passes of the engine.
    resolved: HashMap<(usize, CellRef), CellValue>,
    /// The formulas that compiled, by cell.
    compiled: HashMap<(usize, CellRef), Compiled>,
    /// Each defined name's tokens, in book order; `None` for one that did not
    /// compile, which is still declared so the numbering holds.
    names: Vec<Option<Compiled>>,
    /// The sheets, books and names the formulas refer to.
    links: Links,
    /// Where in the globals each `BOUNDSHEET` keeps its sheet's position.
    boundsheet_offsets: Vec<usize>,
}

impl Plan {
    /// Walks the workbook once, collecting what the globals have to declare.
    fn new(book: &Spreadsheet, engine: &mut Engine<'_>) -> Self {
        let mut plan = Self {
            palette: Colors::plan(book),
            fonts: Vec::new(),
            font_of: Vec::new(),
            format_of: Vec::new(),
            formats: Vec::new(),
            strings: Vec::new(),
            string_index: HashMap::new(),
            string_uses: 0,
            resolved: HashMap::new(),
            compiled: HashMap::new(),
            names: Vec::new(),
            links: Links::new(
                book.sheets().iter().map(|s| s.title().to_owned()).collect(),
                book.defined_names
                    .iter()
                    .map(|n| (n.name.clone(), n.sheet))
                    .collect(),
            ),
            boundsheet_offsets: Vec::new(),
        };
        for style in book.styles.all() {
            plan.font_of.push(plan_font(&mut plan.fonts, &style.font));
            plan.format_of.push(plan_format(&mut plan.formats, style));
        }
        // Excel treats font 4 as absent, so a workbook needs four fonts before
        // the numbering can skip it.
        while plan.fonts.len() < 4 {
            let first = plan.fonts.first().cloned().unwrap_or_default();
            plan.fonts.push(first);
        }
        for (index, sheet) in book.sheets().iter().enumerate() {
            for (at, cell) in sheet.iter() {
                let value = match &cell.value {
                    CellValue::Formula { formula, cached } => {
                        let value = match cached {
                            Some(cached) => (**cached).clone(),
                            None => from_formula(engine.eval(Origin::new(index, at), formula)),
                        };
                        plan.resolved.insert((index, at), value.clone());
                        let compiled =
                            crate::formula::parser::parse(formula)
                                .ok()
                                .and_then(|expr| {
                                    xls_formula::compile(&expr, Place::Cell(index), &mut plan.links)
                                });
                        if let Some(compiled) = compiled {
                            // A formula's text result waits in a `STRING`
                            // record, not in the shared table.
                            plan.compiled.insert((index, at), compiled);
                            continue;
                        }
                        value
                    }
                    other => other.clone(),
                };
                if let Some(text) = string_of(&value) {
                    plan.string_uses += 1;
                    if !plan.string_index.contains_key(&text) {
                        let index = u32::try_from(plan.strings.len()).unwrap_or(0);
                        plan.string_index.insert(text.clone(), index);
                        plan.strings.push(text);
                    }
                }
            }
        }
        for name in &book.defined_names {
            let compiled = crate::formula::parser::parse(&name.formula)
                .ok()
                .and_then(|expr| {
                    xls_formula::compile(&expr, Place::Name(name.sheet), &mut plan.links)
                });
            plan.names.push(compiled);
        }
        plan
    }

    /// The globals substream, up to but not including its `EOF`.
    fn globals(&mut self, book: &Spreadsheet) -> Vec<u8> {
        let mut out = Vec::new();
        record(
            &mut out,
            0x0809,
            &[
                0x00, 0x06, // BIFF8
                0x05, 0x00, // the globals substream
                0xBB, 0x0D, 0xCC, 0x07, // build and year, as Excel writes them
                0xC9, 0x80, 0x00, 0x00, 0x06, 0x06, 0x00, 0x00,
            ],
        );
        // The strings are Unicode, which is what this code page says.
        record(&mut out, 0x0042, &0x04B0u16.to_le_bytes());
        let mode = u16::from(book.epoch == Epoch::Mac1904);
        record(&mut out, 0x0022, &mode.to_le_bytes());

        for font in &self.fonts {
            record(&mut out, 0x0031, &font_record(font, &self.palette));
        }
        for (index, code) in &self.formats {
            let mut data = index.to_le_bytes().to_vec();
            data.extend_from_slice(&unicode_string(code));
            record(&mut out, 0x041E, &data);
        }
        // Excel wants fifteen style formats before the first cell one, and a
        // cell format's parent is the first of them.
        for _ in 0..15 {
            record(
                &mut out,
                0x00E0,
                &xf_record(&Style::default(), 0, 0, true, &self.palette),
            );
        }
        for (id, style) in book.styles.all().iter().enumerate() {
            let font = self.font_of.get(id).copied().unwrap_or(0);
            let format = self.format_of.get(id).copied().unwrap_or(0);
            record(
                &mut out,
                0x00E0,
                &xf_record(style, font, format, false, &self.palette),
            );
        }
        // The `Normal` style, which every cell format hangs off.
        record(&mut out, 0x0293, &[0x00, 0x80, 0x00, 0xFF]);
        if let Some(colors) = self.palette.builder.custom() {
            let mut data = 56u16.to_le_bytes().to_vec();
            for rgb in colors {
                let [_, r, g, b] = rgb.to_be_bytes();
                data.extend_from_slice(&[r, g, b, 0]);
            }
            record(&mut out, 0x0092, &data);
        }

        for sheet in book.sheets() {
            let mut data = vec![0, 0, 0, 0, 0, 0];
            data.extend_from_slice(&short_string(sheet.title()));
            // The position sits four bytes past the record's own header, and
            // is patched once the globals are complete.
            self.boundsheet_offsets.push(out.len() + 4);
            record(&mut out, 0x0085, &data);
        }
        self.links_and_names(book, &mut out);
        self.shared_strings(&mut out);
        out
    }

    /// The books references go through, the table of them, and the defined
    /// names, in the order the format wants them: `SUPBOOK` records with their
    /// `EXTERNNAME`s, then `EXTERNSHEET`, then `NAME`.
    fn links_and_names(&self, book: &Spreadsheet, out: &mut Vec<u8>) {
        let links = &self.links;
        if !links.externs.is_empty() {
            let sheets = u16::try_from(book.sheets().len()).unwrap_or(u16::MAX);
            let mut data = sheets.to_le_bytes().to_vec();
            data.extend_from_slice(&[0x01, 0x04]);
            record(out, 0x01AE, &data);
        }
        if !links.add_ins.is_empty() {
            record(out, 0x01AE, &[0x01, 0x00, 0x01, 0x3A]);
            for name in &links.add_ins {
                let mut data = vec![0, 0, 0, 0, 0, 0];
                data.extend_from_slice(&short_string(name));
                // The name's own formula, which for a function is `#REF!`.
                data.extend_from_slice(&[0x02, 0x00, 0x1C, 0x17]);
                record(out, 0x0023, &data);
            }
        }
        if !links.externs.is_empty() {
            let count = u16::try_from(links.externs.len()).unwrap_or(u16::MAX);
            let mut data = count.to_le_bytes().to_vec();
            for (book, first, last) in &links.externs {
                data.extend_from_slice(&book.to_le_bytes());
                data.extend_from_slice(&first.to_le_bytes());
                data.extend_from_slice(&last.to_le_bytes());
            }
            record(out, 0x0017, &data);
        }
        for (name, compiled) in book.defined_names.iter().zip(&self.names) {
            record(out, 0x0018, &name_record(name, compiled.as_ref()));
        }
    }

    /// The shared string table, split across `CONTINUE` records where a record
    /// cannot hold it all.
    fn shared_strings(&self, out: &mut Vec<u8>) {
        let mut chunks: Vec<Vec<u8>> = vec![Vec::new()];
        // The first chunk carries the two counts before any string.
        let unique = u32::try_from(self.strings.len()).unwrap_or(0);
        if let Some(first) = chunks.first_mut() {
            first.extend_from_slice(&self.string_uses.to_le_bytes());
            first.extend_from_slice(&unique.to_le_bytes());
        }
        for text in &self.strings {
            write_sst_string(&mut chunks, text);
        }
        let mut chunks = chunks.into_iter();
        if let Some(first) = chunks.next() {
            record(out, 0x00FC, &first);
        }
        for chunk in chunks {
            record(out, 0x003C, &chunk);
        }
    }
}

/// Adds a font to the list if it is new, and returns the index a cell format
/// refers to it by. Index 4 is skipped: Excel has never used it.
fn plan_font(fonts: &mut Vec<crate::style::Font>, font: &crate::style::Font) -> u16 {
    let position = fonts.iter().position(|f| f == font).unwrap_or_else(|| {
        fonts.push(font.clone());
        fonts.len() - 1
    });
    let position = u16::try_from(position).unwrap_or(0);
    if position < 4 { position } else { position + 1 }
}

/// The number format index of a style, spelling the code out if Excel has no
/// number of its own for it.
fn plan_format(formats: &mut Vec<(u16, String)>, style: &Style) -> u16 {
    match &style.number_format {
        NumberFormat::General => 0,
        NumberFormat::Builtin(id) => *id,
        NumberFormat::Custom(code) => {
            if let Some((index, _)) = formats.iter().find(|(_, known)| known == code) {
                return *index;
            }
            let index = FIRST_CUSTOM_FORMAT + u16::try_from(formats.len()).unwrap_or(0);
            formats.push((index, code.clone()));
            index
        }
    }
}

/// One formula result as a cell value.
fn from_formula(value: FormulaValue) -> CellValue {
    match value {
        FormulaValue::Number(n) => CellValue::Number(n),
        FormulaValue::Text(t) => CellValue::Text(t.into()),
        FormulaValue::Bool(b) => CellValue::Bool(b),
        FormulaValue::Error(e) => CellValue::Error(e),
        // A cell cannot hold a function; Excel shows `#CALC!`.
        FormulaValue::Lambda(_) => CellValue::Error(crate::error::CellError::Calc),
        // An array shows its top-left value, as everywhere else a cell holds
        // one value and the format has no spill.
        FormulaValue::Array(rows) => rows
            .first()
            .and_then(|line| line.first())
            .cloned()
            .map_or(CellValue::Empty, from_formula),
        FormulaValue::Blank => CellValue::Empty,
    }
}

/// The text a cell is stored as a shared string for. Rich text loses its runs
/// on the way: the old format keeps them in the string table, and the model
/// keeps them on the cell.
fn string_of(value: &CellValue) -> Option<String> {
    match value {
        CellValue::Text(text) => Some(text.to_string()),
        CellValue::RichText(runs) => Some(runs.iter().map(|run| run.text.as_str()).collect()),
        _ => None,
    }
}

/// COLINFO: width, visibility and outline of each run of columns.
fn column_records(out: &mut Vec<u8>, sheet: &Worksheet) {
    for run in &sheet.columns {
        let mut data = Vec::with_capacity(12);
        data.extend_from_slice(&run.first.index_u16().to_le_bytes());
        data.extend_from_slice(&run.last.index_u16().to_le_bytes());
        // The width is in 256ths of a character.
        #[expect(
            clippy::cast_possible_truncation,
            clippy::cast_sign_loss,
            reason = "a column width is a small positive number"
        )]
        let width = (run.width.unwrap_or(8.43) * 256.0).round().max(0.0) as u32;
        data.extend_from_slice(&u16::try_from(width).unwrap_or(u16::MAX).to_le_bytes());
        data.extend_from_slice(&0u16.to_le_bytes());
        let options = u16::from(run.hidden)
            | (u16::from(run.outline_level.min(7)) << 8)
            | (u16::from(run.collapsed) << 12);
        data.extend_from_slice(&options.to_le_bytes());
        data.extend_from_slice(&0u16.to_le_bytes());
        record(out, 0x007D, &data);
    }
}

/// GUTS and WSBOOL: the outline depths and where group summaries sit.
fn outline_records(out: &mut Vec<u8>, sheet: &Worksheet) {
    // GUTS: without the outline depths Excel draws no outline bar; the
    // widths are left for it to work out.
    let depth = |levels: &mut dyn Iterator<Item = u8>| {
        levels
            .max()
            .filter(|&l| l > 0)
            .map_or(0, |l| u16::from(l) + 1)
    };
    let mut guts = [0u8; 8];
    guts[4..6]
        .copy_from_slice(&depth(&mut sheet.rows.values().map(|r| r.outline_level)).to_le_bytes());
    guts[6..8]
        .copy_from_slice(&depth(&mut sheet.columns.iter().map(|c| c.outline_level)).to_le_bytes());
    record(out, 0x0080, &guts);

    // WSBOOL: automatic page breaks and the outline symbols shown, and where
    // group summaries sit.
    let mut wsbool = 0x0401u16;
    if sheet.properties.summary_below {
        wsbool |= 0x40;
    }
    if sheet.properties.summary_right {
        wsbool |= 0x80;
    }
    if sheet.properties.fit_to_page {
        wsbool |= 0x100;
    }
    record(out, 0x0081, &wsbool.to_le_bytes());
}

/// One sheet substream.
fn substream(sheet: &Worksheet, index: usize, plan: &Plan) -> Vec<u8> {
    let mut out = Vec::new();
    record(
        &mut out,
        0x0809,
        &[
            0x00, 0x06, // BIFF8
            0x10, 0x00, // a worksheet substream
            0xBB, 0x0D, 0xCC, 0x07, 0xC9, 0x80, 0x00, 0x00, 0x06, 0x06, 0x00, 0x00,
        ],
    );

    let used = sheet.dimension();
    let (first_row, last_row, first_col, last_col) = used.map_or((0, 0, 0, 0), |range| {
        (
            range.start.row.index(),
            range.end.row.index() + 1,
            range.start.col.index(),
            range.end.col.index() + 1,
        )
    });
    let mut dimension = Vec::with_capacity(14);
    dimension.extend_from_slice(&first_row.to_le_bytes());
    dimension.extend_from_slice(&last_row.to_le_bytes());
    dimension.extend_from_slice(&u16::try_from(first_col).unwrap_or(0).to_le_bytes());
    dimension.extend_from_slice(&u16::try_from(last_col).unwrap_or(0).to_le_bytes());
    dimension.extend_from_slice(&0u16.to_le_bytes());
    outline_records(&mut out, sheet);

    record(&mut out, 0x0200, &dimension);

    column_records(&mut out, sheet);

    for (row, properties) in &sheet.rows {
        let mut data = Vec::with_capacity(16);
        data.extend_from_slice(&row.index_u16().to_le_bytes());
        data.extend_from_slice(&0u16.to_le_bytes());
        data.extend_from_slice(&0u16.to_le_bytes());
        #[expect(
            clippy::cast_possible_truncation,
            clippy::cast_sign_loss,
            reason = "a row height in twips is a small positive number"
        )]
        let height = match properties.height {
            Some(points) => ((points * 20.0).round().max(0.0) as u32).min(0x7FFF),
            // Bit 15 says the row keeps the default height.
            None => 0x8000,
        };
        data.extend_from_slice(&u16::try_from(height).unwrap_or(0x8000).to_le_bytes());
        data.extend_from_slice(&0u32.to_le_bytes());
        let mut flags = 0x0000_0100u32;
        if properties.hidden {
            flags |= 0x20;
        }
        if properties.height.is_some() {
            flags |= 0x40;
        }
        if properties.collapsed {
            flags |= 0x10;
        }
        flags |= u32::from(properties.outline_level) & 0x07;
        data.extend_from_slice(&flags.to_le_bytes());
        record(&mut out, 0x0208, &data);
    }

    cells(&mut out, sheet, index, plan);

    // A record holds 1027 merges at most.
    for chunk in sheet.merges.chunks(1027) {
        let mut data = u16::try_from(chunk.len())
            .unwrap_or(0)
            .to_le_bytes()
            .to_vec();
        for range in chunk {
            data.extend_from_slice(&range.start.row.index_u16().to_le_bytes());
            data.extend_from_slice(&range.end.row.index_u16().to_le_bytes());
            data.extend_from_slice(&range.start.col.index_u16().to_le_bytes());
            data.extend_from_slice(&range.end.col.index_u16().to_le_bytes());
        }
        record(&mut out, 0x00E5, &data);
    }

    window(&mut out, &sheet.view);

    record(&mut out, 0x000A, &[]);
    out
}

/// `WINDOW2`, and `PANE` after it when the sheet is split. Without the window
/// record Excel opens the sheet with no gridlines and no headings, which is
/// not what the model said.
fn window(out: &mut Vec<u8>, view: &SheetView) {
    // Default gridline colour, outline symbols, selected, in page view off.
    let mut flags = 0x06A0u16;
    for (on, bit) in [
        (view.show_grid_lines, 0x0002),
        (view.show_row_col_headers, 0x0004),
        (view.show_zeros, 0x0010),
        (view.right_to_left, 0x0040),
    ] {
        if on {
            flags |= bit;
        }
    }
    match view.pane.as_ref().map(|pane| pane.state) {
        Some(PaneState::Frozen) => flags |= 0x0108,
        Some(PaneState::FrozenSplit) => flags |= 0x0008,
        Some(PaneState::Split) | None => {}
    }
    let (top, left) = view
        .top_left_cell
        .map_or((0, 0), |at| (at.row.index_u16(), at.col.index_u16()));
    let mut data = flags.to_le_bytes().to_vec();
    data.extend_from_slice(&top.to_le_bytes());
    data.extend_from_slice(&left.to_le_bytes());
    data.extend_from_slice(&0x0000_0040u32.to_le_bytes());
    data.extend_from_slice(&0u16.to_le_bytes());
    data.extend_from_slice(&0u16.to_le_bytes());
    data.extend_from_slice(&0u32.to_le_bytes());
    record(out, 0x023E, &data);

    let Some(pane) = &view.pane else {
        selections(out, view);
        return;
    };
    let (top, left) = pane
        .top_left_cell
        .map_or((0, 0), |at| (at.row.index_u16(), at.col.index_u16()));
    let mut data = u16::try_from(pane.x_split)
        .unwrap_or(u16::MAX)
        .to_le_bytes()
        .to_vec();
    data.extend_from_slice(
        &u16::try_from(pane.y_split)
            .unwrap_or(u16::MAX)
            .to_le_bytes(),
    );
    data.extend_from_slice(&top.to_le_bytes());
    data.extend_from_slice(&left.to_le_bytes());
    data.push(pane_number(pane.active_pane));
    data.push(0);
    record(out, 0x0041, &data);
    selections(out, view);
}

/// One `SELECTION` per selection the model holds. BIFF8 has one byte for a
/// column, so an area past column IV is cut at it.
fn selections(out: &mut Vec<u8>, view: &SheetView) {
    for selection in &view.selections {
        let areas = &selection.sqref[..selection.sqref.len().min(1000)];
        let (row, col) = selection
            .active_cell
            .map_or((0, 0), |at| (at.row.index_u16(), at.col.index_u16()));
        let mut data = vec![pane_number(selection.pane.unwrap_or_default())];
        data.extend_from_slice(&row.to_le_bytes());
        data.extend_from_slice(&col.to_le_bytes());
        // Which area holds the cursor: the first one that does.
        let holding = selection
            .active_cell
            .and_then(|at| areas.iter().position(|r| r.contains(at)));
        data.extend_from_slice(
            &u16::try_from(holding.unwrap_or(0))
                .unwrap_or(0)
                .to_le_bytes(),
        );
        data.extend_from_slice(&u16::try_from(areas.len()).unwrap_or(0).to_le_bytes());
        for range in areas {
            data.extend_from_slice(&range.start.row.index_u16().to_le_bytes());
            data.extend_from_slice(&range.end.row.index_u16().to_le_bytes());
            data.push(u8::try_from(range.start.col.index_u16()).unwrap_or(u8::MAX));
            data.push(u8::try_from(range.end.col.index_u16()).unwrap_or(u8::MAX));
        }
        record(out, 0x001D, &data);
    }
}

/// The number BIFF gives a pane.
const fn pane_number(pane: PanePosition) -> u8 {
    match pane {
        PanePosition::BottomRight => 0,
        PanePosition::TopRight => 1,
        PanePosition::BottomLeft => 2,
        PanePosition::TopLeft => 3,
    }
}

/// Every cell of the sheet, in the order the records go out.
fn cells(out: &mut Vec<u8>, sheet: &Worksheet, index: usize, plan: &Plan) {
    for (at, cell) in sheet.iter() {
        // Every cell of an array holds a formula record pointing at the top
        // left of it; the expression itself is said once, in the `ARRAY`
        // record beside that first cell. A value record inside the area
        // instead - which is what this wrote at first - crashes Excel 2019.
        let area = sheet
            .array_formulas
            .iter()
            .find(|r| r.contains(at))
            .copied();
        cell_record(out, index, at, cell, plan, area);
    }
}

/// One cell, as whichever record carries its kind of value.
fn cell_record(
    out: &mut Vec<u8>,
    sheet: usize,
    at: CellRef,
    cell: &crate::model::Cell,
    plan: &Plan,
    array: Option<crate::coordinate::Range>,
) {
    let xf = cell_format(plan, cell.style);
    let head = |data: &mut Vec<u8>| {
        data.extend_from_slice(&at.row.index_u16().to_le_bytes());
        data.extend_from_slice(&at.col.index_u16().to_le_bytes());
        data.extend_from_slice(&xf.to_le_bytes());
    };

    let inside = array.filter(|area| area.start != at);
    if let Some(compiled) = plan.compiled.get(&(sheet, at)).filter(|_| inside.is_none()) {
        let result = plan.resolved.get(&(sheet, at)).unwrap_or(&CellValue::Empty);
        formula_record(out, at, xf, result, compiled, array);
        return;
    }
    if let Some(area) = inside {
        // Inside the area: the same pointer, no expression of its own.
        let result = plan
            .resolved
            .get(&(sheet, at))
            .cloned()
            .unwrap_or_else(|| cell.value.clone());
        formula_record(out, at, xf, &result, &Compiled::default(), Some(area));
        return;
    }

    // A formula that did not compile is written as what it worked out to. The
    // result was worked out while the string table was being planned.
    let value = match &cell.value {
        CellValue::Formula { .. } => plan
            .resolved
            .get(&(sheet, at))
            .cloned()
            .unwrap_or(CellValue::Empty),
        other => other.clone(),
    };

    let mut data = Vec::with_capacity(16);
    match &value {
        CellValue::Number(n) => {
            head(&mut data);
            data.extend_from_slice(&n.to_le_bytes());
            record(out, 0x0203, &data);
        }
        CellValue::Text(text) => {
            head(&mut data);
            let index = plan.string_index.get(text.as_ref()).copied().unwrap_or(0);
            data.extend_from_slice(&index.to_le_bytes());
            record(out, 0x00FD, &data);
        }
        CellValue::Bool(b) => {
            head(&mut data);
            data.push(u8::from(*b));
            data.push(0);
            record(out, 0x0205, &data);
        }
        CellValue::Error(e) => {
            head(&mut data);
            data.push(xls_formula::error_code(*e));
            data.push(1);
            record(out, 0x0205, &data);
        }
        // Rich text keeps only its text; the old format holds the runs in the
        // string table rather than on the cell.
        CellValue::RichText(_) => {
            let text = string_of(&value).unwrap_or_default();
            head(&mut data);
            let index = plan.string_index.get(&text).copied().unwrap_or(0);
            data.extend_from_slice(&index.to_le_bytes());
            record(out, 0x00FD, &data);
        }
        CellValue::Empty | CellValue::Formula { .. } => {
            head(&mut data);
            record(out, 0x0201, &data);
        }
    }
}

/// A `FORMULA` record, and the `STRING` record after it when the result is
/// text.
fn formula_record(
    out: &mut Vec<u8>,
    at: CellRef,
    xf: u16,
    result: &CellValue,
    compiled: &Compiled,
    array: Option<crate::coordinate::Range>,
) {
    let mut data = Vec::with_capacity(22 + compiled.tokens.len() + compiled.extra.len());
    data.extend_from_slice(&at.row.index_u16().to_le_bytes());
    data.extend_from_slice(&at.col.index_u16().to_le_bytes());
    data.extend_from_slice(&xf.to_le_bytes());
    // A result that is not a number says what it is in its first byte and
    // marks itself with 0xFFFF in its last two.
    let special = |kind: u8, value: u8| [kind, 0, value, 0, 0, 0, 0xFF, 0xFF];
    let text = match result {
        CellValue::Number(n) => {
            data.extend_from_slice(&n.to_le_bytes());
            None
        }
        CellValue::Text(_) | CellValue::RichText(_) => {
            data.extend_from_slice(&special(0, 0));
            string_of(result)
        }
        CellValue::Bool(b) => {
            data.extend_from_slice(&special(1, u8::from(*b)));
            None
        }
        CellValue::Error(e) => {
            data.extend_from_slice(&special(2, xls_formula::error_code(*e)));
            None
        }
        CellValue::Empty | CellValue::Formula { .. } => {
            data.extend_from_slice(&special(3, 0));
            None
        }
    };
    // Options, then the chain cookie Excel fills in itself.
    data.extend_from_slice(&[0, 0, 0, 0, 0, 0]);
    // An array formula does not hold its own expression: the cell points at
    // the top left of the array, and the expression follows in an `ARRAY`
    // record, which is how BIFF says what xlsx says with `<f t="array" ref>`.
    let pointer = array.map(|area| {
        let mut tokens = vec![0x01];
        tokens.extend_from_slice(&area.start.row.index_u16().to_le_bytes());
        tokens.extend_from_slice(&area.start.col.index_u16().to_le_bytes());
        tokens
    });
    let tokens = pointer.as_ref().unwrap_or(&compiled.tokens);
    let length = u16::try_from(tokens.len()).unwrap_or(0);
    data.extend_from_slice(&length.to_le_bytes());
    data.extend_from_slice(tokens);
    if pointer.is_none() {
        data.extend_from_slice(&compiled.extra);
    }
    record(out, 0x0006, &data);
    // The expression is said once, beside the cell the array starts in.
    if let Some(area) = array.filter(|area| area.start == at) {
        record(out, 0x0221, &array_record(area, compiled));
    }
    if let Some(text) = text {
        record(out, 0x0207, &unicode_string(&text));
    }
}

/// An `ARRAY` record: the area the formula fills, and the expression itself.
fn array_record(area: crate::coordinate::Range, compiled: &Compiled) -> Vec<u8> {
    let mut data = Vec::with_capacity(14 + compiled.tokens.len() + compiled.extra.len());
    data.extend_from_slice(&area.start.row.index_u16().to_le_bytes());
    data.extend_from_slice(&area.end.row.index_u16().to_le_bytes());
    data.push(u8::try_from(area.start.col.index()).unwrap_or(u8::MAX));
    data.push(u8::try_from(area.end.col.index()).unwrap_or(u8::MAX));
    // Flags and the chain cookie Excel fills in itself.
    data.extend_from_slice(&[0, 0, 0, 0, 0, 0]);
    let length = u16::try_from(compiled.tokens.len()).unwrap_or(0);
    data.extend_from_slice(&length.to_le_bytes());
    data.extend_from_slice(&compiled.tokens);
    data.extend_from_slice(&compiled.extra);
    data
}

/// A `NAME` record. A built-in name (`_xlnm.Print_Area`) is stored as a
/// single character code rather than spelled out.
fn name_record(name: &crate::model::DefinedName, compiled: Option<&Compiled>) -> Vec<u8> {
    const BUILTIN: [&str; 14] = [
        "Consolidate_Area",
        "Auto_Open",
        "Auto_Close",
        "Extract",
        "Database",
        "Criteria",
        "Print_Area",
        "Print_Titles",
        "Recorder",
        "Data_Form",
        "Auto_Activate",
        "Auto_Deactivate",
        "Sheet_Title",
        "_FilterDatabase",
    ];
    let builtin = name
        .name
        .strip_prefix("_xlnm.")
        .and_then(|rest| BUILTIN.iter().position(|b| b.eq_ignore_ascii_case(rest)));
    let mut flags = u16::from(name.hidden);
    let units: Vec<u16> = match builtin {
        Some(code) => {
            flags |= 0x20;
            vec![u16::try_from(code).unwrap_or(0)]
        }
        None => name.name.encode_utf16().take(255).collect(),
    };
    let wide = units.iter().any(|&u| u > 0xFF);
    let (tokens, extra): (&[u8], &[u8]) = compiled.map_or((&[], &[]), |c| (&c.tokens, &c.extra));
    let mut data = flags.to_le_bytes().to_vec();
    data.push(0);
    data.push(u8::try_from(units.len()).unwrap_or(0));
    data.extend_from_slice(&u16::try_from(tokens.len()).unwrap_or(0).to_le_bytes());
    data.extend_from_slice(&[0, 0]);
    let sheet = name.sheet.map_or(0, |s| s + 1);
    data.extend_from_slice(&u16::try_from(sheet).unwrap_or(0).to_le_bytes());
    data.extend_from_slice(&[0, 0, 0, 0]);
    data.push(u8::from(wide));
    push_units(&mut data, &units, wide);
    data.extend_from_slice(tokens);
    data.extend_from_slice(extra);
    data
}

/// The `XF` index of a style: the fifteen style formats come first.
fn cell_format(plan: &Plan, style: crate::style::StyleId) -> u16 {
    let index = u16::try_from(style.index()).unwrap_or(0);
    if usize::from(index) < plan.format_of.len() {
        15 + index
    } else {
        15
    }
}

/// A `FONT` record.
fn font_record(font: &crate::style::Font, palette: &Colors) -> Vec<u8> {
    let mut data = Vec::with_capacity(24);
    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        reason = "a font size in twips is a small positive number"
    )]
    let height = (font.size_points() * 20.0).round().max(0.0) as u32;
    data.extend_from_slice(&u16::try_from(height).unwrap_or(220).to_le_bytes());
    // Bit 0 says bold beside the weight; older readers look only at it.
    let mut flags = u16::from(font.bold);
    if font.italic {
        flags |= 0x0002;
    }
    if font.strike {
        flags |= 0x0008;
    }
    data.extend_from_slice(&flags.to_le_bytes());
    data.extend_from_slice(&palette.index(&font.color, 0x7FFF).to_le_bytes());
    data.extend_from_slice(&if font.bold { 700u16 } else { 400u16 }.to_le_bytes());
    let escapement: u16 = match font.script {
        Script::Baseline => 0,
        Script::Superscript => 1,
        Script::Subscript => 2,
    };
    data.extend_from_slice(&escapement.to_le_bytes());
    data.push(match font.underline {
        crate::style::Underline::None => 0x00,
        crate::style::Underline::Double => 0x02,
        crate::style::Underline::SingleAccounting => 0x21,
        crate::style::Underline::DoubleAccounting => 0x22,
        crate::style::Underline::Single => 0x01,
    });
    let small = |value: Option<u32>| value.and_then(|v| u8::try_from(v).ok()).unwrap_or(0);
    data.extend_from_slice(&[small(font.family), small(font.charset), 0]);
    data.extend_from_slice(&short_string(&font.name));
    data
}

/// An `XF` record: which font, which format, how the text sits, and the
/// borders, fill and protection.
fn xf_record(style: &Style, font: u16, format: u16, is_style: bool, palette: &Colors) -> Vec<u8> {
    let mut data = Vec::with_capacity(20);
    data.extend_from_slice(&font.to_le_bytes());
    data.extend_from_slice(&format.to_le_bytes());
    // Bit 0 locks the cell, bit 1 hides its formula, bit 2 marks a style
    // format; a style format has no parent and says so with 0xFFF, a cell
    // format points at the first style format.
    let mut protection: u16 = if is_style { 0xFFF4 } else { 0x0000 };
    if style.protection.locked != ProtectionState::Off {
        protection |= 0x01;
    }
    if style.protection.hidden == ProtectionState::On {
        protection |= 0x02;
    }
    data.extend_from_slice(&protection.to_le_bytes());

    let mut align = match style.alignment.horizontal {
        HorizontalAlign::General => 0u8,
        HorizontalAlign::Left => 1,
        HorizontalAlign::Center => 2,
        HorizontalAlign::Right => 3,
        HorizontalAlign::Fill => 4,
        HorizontalAlign::Justify => 5,
        HorizontalAlign::CenterContinuous => 6,
        HorizontalAlign::Distributed => 7,
    };
    if style.alignment.wrap_text {
        align |= 0x08;
    }
    align |= match style.alignment.vertical {
        VerticalAlign::Top => 0u8,
        VerticalAlign::Center => 1,
        VerticalAlign::Bottom => 2,
        VerticalAlign::Justify => 3,
        VerticalAlign::Distributed => 4,
    } << 4;
    data.push(align);
    // The rotation byte counts the way the model does: 0 to 180, 255 stacked.
    data.push(u8::try_from(style.alignment.text_rotation).unwrap_or(0));
    let mut options = u8::try_from(style.alignment.indent & 0x0F).unwrap_or(0);
    if style.alignment.shrink_to_fit {
        options |= 0x10;
    }
    options |= u8::try_from(style.alignment.reading_order & 0x03).unwrap_or(0) << 6;
    data.push(options);

    let borders = &style.borders;
    let fill = &style.fill;
    let has_borders = [&borders.left, &borders.right, &borders.top, &borders.bottom]
        .iter()
        .any(|side| side.style != BorderStyle::None)
        || borders.diagonal_direction != DiagonalDirection::None;
    let has_alignment = style.alignment != crate::style::Alignment::default();
    // Which groups of attributes this format sets, rather than inheriting.
    let mut used = 0u8;
    if format != 0 {
        used |= 0x04;
    }
    if font != 0 {
        used |= 0x08;
    }
    if has_alignment {
        used |= 0x10;
    }
    if has_borders {
        used |= 0x20;
    }
    if fill.pattern != Pattern::None {
        used |= 0x40;
    }
    if style.protection != crate::style::Protection::default() {
        used |= 0x80;
    }
    data.push(used);

    data.extend_from_slice(&borders_and_fill(style, palette));
    data
}

/// The last ten bytes of an `XF` record: line styles and colours of the four
/// sides and the diagonal, then the fill pattern and its two colours.
fn borders_and_fill(style: &Style, palette: &Colors) -> Vec<u8> {
    let borders = &style.borders;
    let fill = &style.fill;
    let mut data = Vec::with_capacity(10);
    // A side with no line keeps colour 0, which is what Excel writes.
    let side = |border: &crate::style::Border| {
        let line = border_code(border.style);
        let color = if line == 0 {
            0
        } else {
            palette.index(&border.color, 0x40)
        };
        (u32::from(line), u32::from(color))
    };
    let (left, left_color) = side(&borders.left);
    let (right, right_color) = side(&borders.right);
    let (top, top_color) = side(&borders.top);
    let (bottom, bottom_color) = side(&borders.bottom);
    let (diagonal, diagonal_color) = if borders.diagonal_direction == DiagonalDirection::None {
        (0, 0)
    } else {
        side(&borders.diagonal)
    };
    let mut sides = left | (right << 4) | (top << 8) | (bottom << 12);
    sides |= (left_color << 16) | (right_color << 23);
    if matches!(
        borders.diagonal_direction,
        DiagonalDirection::Down | DiagonalDirection::Both
    ) {
        sides |= 1 << 30;
    }
    if matches!(
        borders.diagonal_direction,
        DiagonalDirection::Up | DiagonalDirection::Both
    ) {
        sides |= 1 << 31;
    }
    data.extend_from_slice(&sides.to_le_bytes());

    let pattern = pattern_code(fill.pattern);
    let more = top_color
        | (bottom_color << 7)
        | (diagonal_color << 14)
        | (diagonal << 21)
        | (u32::from(pattern) << 26);
    data.extend_from_slice(&more.to_le_bytes());
    // An unfilled cell keeps the system foreground and background.
    let (foreground, background) = if pattern == 0 {
        (0x40, 0x41)
    } else {
        (
            palette.index(&fill.foreground, 0x40),
            palette.index(&fill.background, 0x41),
        )
    };
    data.extend_from_slice(&((foreground & 0x7F) | ((background & 0x7F) << 7)).to_le_bytes());
    data
}

/// A line style as BIFF numbers it.
fn border_code(style: BorderStyle) -> u8 {
    match style.as_str() {
        "thin" => 1,
        "medium" => 2,
        "dashed" => 3,
        "dotted" => 4,
        "thick" => 5,
        "double" => 6,
        "hair" => 7,
        "mediumDashed" => 8,
        "dashDot" => 9,
        "mediumDashDot" => 10,
        "dashDotDot" => 11,
        "mediumDashDotDot" => 12,
        _ => 0,
    }
}

/// A fill pattern as BIFF numbers it.
fn pattern_code(pattern: Pattern) -> u8 {
    match pattern.as_str() {
        "solid" => 1,
        "mediumGray" => 2,
        "darkGray" => 3,
        "lightGray" => 4,
        "darkHorizontal" => 5,
        "darkVertical" => 6,
        "darkDown" => 7,
        "darkUp" => 8,
        "darkGrid" => 9,
        "darkTrellis" => 10,
        "lightHorizontal" => 11,
        "lightVertical" => 12,
        "lightDown" => 13,
        "lightUp" => 14,
        "lightGrid" => 15,
        "lightTrellis" => 16,
        "gray125" => 17,
        "gray0625" => 18,
        _ => 0,
    }
}

/// The workbook's colours laid out in a palette, with the theme that resolves
/// its theme colours.
struct Colors {
    builder: palette::Builder,
    theme: Option<String>,
}

impl Colors {
    /// Collects every colour the style table uses, in style order.
    fn plan(book: &Spreadsheet) -> Self {
        let theme = book.theme.clone();
        let mut used = Vec::new();
        for style in book.styles.all() {
            let borders = &style.borders;
            let mut colors = vec![&style.font.color];
            if style.fill.pattern != Pattern::None {
                colors.extend([&style.fill.foreground, &style.fill.background]);
            }
            for side in [
                &borders.left,
                &borders.right,
                &borders.top,
                &borders.bottom,
                &borders.diagonal,
            ] {
                if side.style != BorderStyle::None {
                    colors.push(&side.color);
                }
            }
            used.extend(
                colors
                    .into_iter()
                    .filter_map(|c| palette::rgb_of(c, theme.as_deref())),
            );
        }
        Self {
            builder: palette::Builder::plan(&used),
            theme,
        }
    }

    /// The palette index for a colour, or `automatic` for one with no value.
    fn index(&self, color: &Color, automatic: u16) -> u16 {
        palette::rgb_of(color, self.theme.as_deref())
            .map_or(automatic, |rgb| self.builder.index_of(rgb))
    }
}

/// A string with a one-byte character count, as `BOUNDSHEET` and `FONT` write
/// it.
fn short_string(text: &str) -> Vec<u8> {
    let units: Vec<u16> = text.encode_utf16().take(255).collect();
    let wide = units.iter().any(|&u| u > 0xFF);
    let mut out = Vec::with_capacity(units.len() * 2 + 2);
    out.push(u8::try_from(units.len()).unwrap_or(0));
    out.push(u8::from(wide));
    push_units(&mut out, &units, wide);
    out
}

/// A string with a two-byte character count, as `FORMAT` writes it.
fn unicode_string(text: &str) -> Vec<u8> {
    let units: Vec<u16> = text.encode_utf16().take(0xFFFF).collect();
    let wide = units.iter().any(|&u| u > 0xFF);
    let mut out = Vec::with_capacity(units.len() * 2 + 3);
    out.extend_from_slice(&u16::try_from(units.len()).unwrap_or(0).to_le_bytes());
    out.push(u8::from(wide));
    push_units(&mut out, &units, wide);
    out
}

/// The characters themselves, one byte each or two.
fn push_units(out: &mut Vec<u8>, units: &[u16], wide: bool) {
    for &unit in units {
        if wide {
            out.extend_from_slice(&unit.to_le_bytes());
        } else {
            out.push(u8::try_from(unit).unwrap_or(b'?'));
        }
    }
}

/// One string of the shared table, continuing into another record when the
/// current one is full.
///
/// A record that runs out mid-string is continued by a `CONTINUE` whose first
/// byte says the width of what follows - the same rule the reader takes apart.
fn write_sst_string(chunks: &mut Vec<Vec<u8>>, text: &str) {
    let units: Vec<u16> = text.encode_utf16().take(0xFFFF).collect();
    let wide = units.iter().any(|&u| u > 0xFF);
    let size = if wide { 2 } else { 1 };

    // The header is never split: a chunk with no room for it starts a new one.
    if chunks
        .last()
        .is_none_or(|chunk| chunk.len() + 3 + size > MAX_PAYLOAD)
    {
        chunks.push(Vec::new());
    }
    if let Some(chunk) = chunks.last_mut() {
        chunk.extend_from_slice(&u16::try_from(units.len()).unwrap_or(0).to_le_bytes());
        chunk.push(u8::from(wide));
    }

    let mut written = 0;
    while written < units.len() {
        let room = match chunks.last() {
            Some(chunk) => MAX_PAYLOAD.saturating_sub(chunk.len()) / size,
            None => 0,
        };
        if room == 0 {
            chunks.push(vec![u8::from(wide)]);
            continue;
        }
        let take = room.min(units.len() - written);
        if let Some(chunk) = chunks.last_mut() {
            push_units(chunk, &units[written..written + take], wide);
        }
        written += take;
    }
}

/// Appends one record: its number, its length, and its payload.
fn record(out: &mut Vec<u8>, id: u16, data: &[u8]) {
    out.extend_from_slice(&id.to_le_bytes());
    out.extend_from_slice(&u16::try_from(data.len()).unwrap_or(0).to_le_bytes());
    out.extend_from_slice(data);
}

/// The zero-based index a record writes, as two bytes.
trait IndexU16 {
    fn index_u16(self) -> u16;
}

impl IndexU16 for Row {
    fn index_u16(self) -> u16 {
        u16::try_from(self.index()).unwrap_or(u16::MAX)
    }
}

impl IndexU16 for Col {
    fn index_u16(self) -> u16 {
        u16::try_from(self.index()).unwrap_or(u16::MAX)
    }
}