rdocx 0.16.2

High-level API for reading, writing, and converting DOCX documents
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
//! Style access and manipulation for documents.

use std::collections::{HashMap, HashSet};

use rdocx_oxml::borders::CT_BorderEdge;
use rdocx_oxml::properties::{CT_PPr, CT_RPr};
use rdocx_oxml::shared::{ST_Border, ST_Jc};
use rdocx_oxml::styles::{CT_Style, CT_Styles, CT_TblStylePr, StyleType, TableStyleRegion};
use rdocx_oxml::table::{CT_TblBorders, CT_TblCellMar, CT_TblPr, CT_TcPr, CT_TrPr};
use rdocx_oxml::units::{HalfPoint, Twips};

use crate::Length;
use crate::paragraph::Alignment;
use crate::{Error, Result};

/// An immutable reference to a style definition.
pub struct Style<'a> {
    pub(crate) inner: &'a CT_Style,
}

impl<'a> Style<'a> {
    /// The style ID (used to reference this style).
    pub fn style_id(&self) -> &str {
        &self.inner.style_id
    }

    /// The display name of the style.
    pub fn name(&self) -> Option<&str> {
        self.inner.name.as_deref()
    }

    /// The style ID this style is based on.
    pub fn based_on(&self) -> Option<&str> {
        self.inner.based_on.as_deref()
    }

    /// The kind of content this style formats.
    pub fn style_type(&self) -> StyleType {
        self.inner.style_type
    }

    /// The reciprocal paragraph or character style linked to this style.
    pub fn linked_style(&self) -> Option<&str> {
        self.inner.linked_style.as_deref()
    }

    /// The style selected for the paragraph following this paragraph style.
    pub fn next_style(&self) -> Option<&str> {
        self.inner.next_style.as_deref()
    }

    /// The user-interface ordering priority for this style.
    pub fn priority(&self) -> Option<u32> {
        self.inner.ui_priority
    }

    /// Whether Word may redefine the style from direct formatting.
    pub fn auto_redefine(&self) -> Option<bool> {
        self.inner.auto_redefine
    }

    /// Whether the style is hidden from all user-interface lists.
    pub fn hidden(&self) -> Option<bool> {
        self.inner.hidden
    }

    /// Whether the style is hidden from the main style gallery.
    pub fn semi_hidden(&self) -> Option<bool> {
        self.inner.semi_hidden
    }

    /// Whether applying the style makes it visible in the user interface.
    pub fn unhide_when_used(&self) -> Option<bool> {
        self.inner.unhide_when_used
    }

    /// Whether the style appears in the quick style gallery.
    pub fn quick_format(&self) -> Option<bool> {
        self.inner.quick_format
    }

    /// Whether the style is locked against application in the user interface.
    pub fn locked(&self) -> Option<bool> {
        self.inner.locked
    }

    /// The style's paragraph properties.
    pub fn paragraph_properties(&self) -> Option<&CT_PPr> {
        self.inner.ppr.as_ref()
    }

    /// The style's run properties.
    pub fn run_properties(&self) -> Option<&CT_RPr> {
        self.inner.rpr.as_ref()
    }

    /// The style's base table properties.
    pub fn table_properties(&self) -> Option<&CT_TblPr> {
        self.inner.table_properties.as_ref()
    }

    /// The style's base table row properties.
    pub fn table_row_properties(&self) -> Option<&CT_TrPr> {
        self.inner.table_row_properties.as_deref()
    }

    /// The style's base table cell properties.
    pub fn table_cell_properties(&self) -> Option<&CT_TcPr> {
        self.inner.table_cell_properties.as_deref()
    }

    /// Conditional table regions in source order.
    ///
    /// A region whose `w:type` this workspace does not recognise reports
    /// `None` from [`ConditionalTableStyle::region`]. It round-trips from its
    /// preserved bytes and takes no part in resolution.
    pub fn conditional_table_styles(&self) -> Vec<ConditionalTableStyle<'a>> {
        self.inner
            .conditional_table_styles
            .iter()
            .map(|inner| ConditionalTableStyle { inner })
            .collect()
    }

    /// Whether this is the default style for its type.
    pub fn is_default(&self) -> bool {
        self.inner.is_default
    }
}

/// One conditional table-style region read back through the facade.
pub struct ConditionalTableStyle<'a> {
    inner: &'a CT_TblStylePr,
}

impl<'a> ConditionalTableStyle<'a> {
    /// The region this layer formats, or `None` for an unrecognised `w:type`.
    pub fn region(&self) -> Option<TableStyleRegion> {
        self.inner.region
    }

    /// The region's paragraph properties.
    pub fn paragraph_properties(&self) -> Option<&'a CT_PPr> {
        self.inner.paragraph_properties.as_ref()
    }

    /// The region's run properties.
    pub fn run_properties(&self) -> Option<&'a CT_RPr> {
        self.inner.run_properties.as_deref()
    }

    /// The region's table properties.
    pub fn table_properties(&self) -> Option<&'a CT_TblPr> {
        self.inner.table_properties.as_ref()
    }

    /// The region's row properties.
    ///
    /// Modeled and round-tripped. Its layout application belongs to F-268a.
    pub fn row_properties(&self) -> Option<&'a CT_TrPr> {
        self.inner.row_properties.as_deref()
    }

    /// The region's cell properties.
    pub fn cell_properties(&self) -> Option<&'a CT_TcPr> {
        self.inner.cell_properties.as_ref()
    }
}

/// Builder for creating a new paragraph style.
pub struct StyleBuilder {
    style: CT_Style,
    cleared: u32,
    removed_regions: Vec<TableStyleRegion>,
}

pub(crate) const CLEAR_BASED_ON: u32 = 1 << 0;
pub(crate) const CLEAR_NEXT_STYLE: u32 = 1 << 1;
pub(crate) const CLEAR_LINKED_STYLE: u32 = 1 << 2;
pub(crate) const CLEAR_PRIORITY: u32 = 1 << 3;
pub(crate) const CLEAR_AUTO_REDEFINE: u32 = 1 << 4;
pub(crate) const CLEAR_HIDDEN: u32 = 1 << 5;
pub(crate) const CLEAR_SEMI_HIDDEN: u32 = 1 << 6;
pub(crate) const CLEAR_UNHIDE_WHEN_USED: u32 = 1 << 7;
pub(crate) const CLEAR_QUICK_FORMAT: u32 = 1 << 8;
pub(crate) const CLEAR_LOCKED: u32 = 1 << 9;
pub(crate) const CLEAR_PARAGRAPH_PROPERTIES: u32 = 1 << 10;
pub(crate) const CLEAR_RUN_PROPERTIES: u32 = 1 << 11;
pub(crate) const CLEAR_TABLE_PROPERTIES: u32 = 1 << 12;
pub(crate) const CLEAR_CONDITIONAL_TABLE_STYLES: u32 = 1 << 13;
pub(crate) const CLEAR_TABLE_ROW_PROPERTIES: u32 = 1 << 14;
pub(crate) const CLEAR_TABLE_CELL_PROPERTIES: u32 = 1 << 15;
pub(crate) const CLEAR_FONT_THEME: u32 = 1 << 16;
pub(crate) const CLEAR_COLOR_THEME: u32 = 1 << 17;
pub(crate) const REPLACE_PARAGRAPH_PROPERTIES: u32 = 1 << 18;

impl StyleBuilder {
    /// Create a new paragraph style builder.
    pub fn paragraph(style_id: &str, name: &str) -> Self {
        StyleBuilder {
            style: CT_Style {
                style_id: style_id.to_string(),
                style_type: StyleType::Paragraph,
                name: Some(name.to_string()),
                based_on: None,
                next_style: None,
                linked_style: None,
                auto_redefine: None,
                hidden: None,
                ui_priority: None,
                semi_hidden: None,
                unhide_when_used: None,
                quick_format: None,
                locked: None,
                is_default: false,
                ppr: None,
                rpr: None,
                table_properties: None,
                table_properties_original: None,
                table_properties_xml: None,
                table_row_properties: None,
                table_cell_properties: None,
                conditional_table_styles: Vec::new(),
                extra_attributes: Vec::new(),
                modeled_xml: Vec::new(),
                extra_xml: Vec::new(),
            },
            cleared: 0,
            removed_regions: Vec::new(),
        }
    }

    /// Create a new character style builder.
    pub fn character(style_id: &str, name: &str) -> Self {
        StyleBuilder {
            style: CT_Style {
                style_id: style_id.to_string(),
                style_type: StyleType::Character,
                name: Some(name.to_string()),
                based_on: None,
                next_style: None,
                linked_style: None,
                auto_redefine: None,
                hidden: None,
                ui_priority: None,
                semi_hidden: None,
                unhide_when_used: None,
                quick_format: None,
                locked: None,
                is_default: false,
                ppr: None,
                rpr: None,
                table_properties: None,
                table_properties_original: None,
                table_properties_xml: None,
                table_row_properties: None,
                table_cell_properties: None,
                conditional_table_styles: Vec::new(),
                extra_attributes: Vec::new(),
                modeled_xml: Vec::new(),
                extra_xml: Vec::new(),
            },
            cleared: 0,
            removed_regions: Vec::new(),
        }
    }

    /// Create a new table style builder.
    pub fn table(style_id: &str, name: &str) -> Self {
        let mut builder = Self::paragraph(style_id, name);
        builder.style.style_type = StyleType::Table;
        builder
    }

    /// Set the parent style this one inherits from.
    pub fn based_on(mut self, style_id: &str) -> Self {
        self.style.based_on = Some(style_id.to_string());
        self.cleared &= !CLEAR_BASED_ON;
        self
    }

    /// Remove the parent style during an update.
    pub fn clear_based_on(mut self) -> Self {
        self.style.based_on = None;
        self.cleared |= CLEAR_BASED_ON;
        self
    }

    /// Set the next style (applied to the following paragraph after pressing Enter).
    pub fn next_style(mut self, style_id: &str) -> Self {
        self.style.next_style = Some(style_id.to_string());
        self.cleared &= !CLEAR_NEXT_STYLE;
        self
    }

    /// Remove the following-paragraph style during an update.
    pub fn clear_next_style(mut self) -> Self {
        self.style.next_style = None;
        self.cleared |= CLEAR_NEXT_STYLE;
        self
    }

    /// Link this paragraph style to a character style, or the reverse.
    pub fn linked_style(mut self, style_id: &str) -> Self {
        self.style.linked_style = Some(style_id.to_string());
        self.cleared &= !CLEAR_LINKED_STYLE;
        self
    }

    /// Remove the reciprocal paragraph or character link during an update.
    pub fn clear_linked_style(mut self) -> Self {
        self.style.linked_style = None;
        self.cleared |= CLEAR_LINKED_STYLE;
        self
    }

    /// Set the style's user-interface ordering priority.
    pub fn priority(mut self, priority: u32) -> Self {
        self.style.ui_priority = Some(priority);
        self.cleared &= !CLEAR_PRIORITY;
        self
    }

    /// Remove the user-interface ordering priority during an update.
    pub fn clear_priority(mut self) -> Self {
        self.style.ui_priority = None;
        self.cleared |= CLEAR_PRIORITY;
        self
    }

    /// Set whether Word may redefine the style from direct formatting.
    pub fn auto_redefine(mut self, value: bool) -> Self {
        self.style.auto_redefine = Some(value);
        self.cleared &= !CLEAR_AUTO_REDEFINE;
        self
    }

    /// Remove the automatic-redefinition setting during an update.
    pub fn clear_auto_redefine(mut self) -> Self {
        self.style.auto_redefine = None;
        self.cleared |= CLEAR_AUTO_REDEFINE;
        self
    }

    /// Set whether the style is hidden from all user-interface lists.
    pub fn hidden(mut self, value: bool) -> Self {
        self.style.hidden = Some(value);
        self.cleared &= !CLEAR_HIDDEN;
        self
    }

    /// Remove the hidden setting during an update.
    pub fn clear_hidden(mut self) -> Self {
        self.style.hidden = None;
        self.cleared |= CLEAR_HIDDEN;
        self
    }

    /// Set whether the style is hidden from the main style gallery.
    pub fn semi_hidden(mut self, value: bool) -> Self {
        self.style.semi_hidden = Some(value);
        self.cleared &= !CLEAR_SEMI_HIDDEN;
        self
    }

    /// Remove the semi-hidden setting during an update.
    pub fn clear_semi_hidden(mut self) -> Self {
        self.style.semi_hidden = None;
        self.cleared |= CLEAR_SEMI_HIDDEN;
        self
    }

    /// Set whether applying the style makes it visible in the user interface.
    pub fn unhide_when_used(mut self, value: bool) -> Self {
        self.style.unhide_when_used = Some(value);
        self.cleared &= !CLEAR_UNHIDE_WHEN_USED;
        self
    }

    /// Remove the unhide-when-used setting during an update.
    pub fn clear_unhide_when_used(mut self) -> Self {
        self.style.unhide_when_used = None;
        self.cleared |= CLEAR_UNHIDE_WHEN_USED;
        self
    }

    /// Set whether the style appears in the quick style gallery.
    pub fn quick_format(mut self, value: bool) -> Self {
        self.style.quick_format = Some(value);
        self.cleared &= !CLEAR_QUICK_FORMAT;
        self
    }

    /// Remove the quick-format setting during an update.
    pub fn clear_quick_format(mut self) -> Self {
        self.style.quick_format = None;
        self.cleared |= CLEAR_QUICK_FORMAT;
        self
    }

    /// Set whether the style is locked against application in the user interface.
    pub fn locked(mut self, value: bool) -> Self {
        self.style.locked = Some(value);
        self.cleared &= !CLEAR_LOCKED;
        self
    }

    /// Remove the locked setting during an update.
    pub fn clear_locked(mut self) -> Self {
        self.style.locked = None;
        self.cleared |= CLEAR_LOCKED;
        self
    }

    /// Set paragraph properties for this style.
    pub fn paragraph_properties(mut self, ppr: CT_PPr) -> Self {
        self.style.ppr = Some(ppr);
        self.cleared &= !(CLEAR_PARAGRAPH_PROPERTIES | REPLACE_PARAGRAPH_PROPERTIES);
        self
    }

    /// Replace the complete, source-preserving paragraph property snapshot.
    /// Unlike an overlay, explicit absent fields clear their direct facts.
    pub fn replace_paragraph_properties(mut self, properties: CT_PPr) -> Self {
        self.style.ppr = Some(properties);
        self.cleared &= !CLEAR_PARAGRAPH_PROPERTIES;
        self.cleared |= REPLACE_PARAGRAPH_PROPERTIES;
        self
    }

    /// Set paragraph alignment, retaining other paragraph properties.
    pub fn alignment(mut self, value: Alignment) -> Self {
        self.style.ppr.get_or_insert_with(CT_PPr::default).jc = Some(value.to_st_jc());
        self.cleared &= !CLEAR_PARAGRAPH_PROPERTIES;
        self
    }

    /// Set paragraph space before using the same twip conversion as `Paragraph`.
    pub fn space_before(mut self, value: Length) -> Self {
        self.style
            .ppr
            .get_or_insert_with(CT_PPr::default)
            .space_before = Some(value.as_twips());
        self.cleared &= !CLEAR_PARAGRAPH_PROPERTIES;
        self
    }

    /// Set paragraph space after using the same twip conversion as `Paragraph`.
    pub fn space_after(mut self, value: Length) -> Self {
        self.style
            .ppr
            .get_or_insert_with(CT_PPr::default)
            .space_after = Some(value.as_twips());
        self.cleared &= !CLEAR_PARAGRAPH_PROPERTIES;
        self
    }

    /// Set left paragraph indentation.
    pub fn indent_left(mut self, value: Length) -> Self {
        self.style.ppr.get_or_insert_with(CT_PPr::default).ind_left = Some(value.as_twips());
        self.cleared &= !CLEAR_PARAGRAPH_PROPERTIES;
        self
    }

    /// Remove all paragraph properties during an update.
    pub fn clear_paragraph_properties(mut self) -> Self {
        self.style.ppr = None;
        self.cleared &= !REPLACE_PARAGRAPH_PROPERTIES;
        self.cleared |= CLEAR_PARAGRAPH_PROPERTIES;
        self
    }

    /// Set run properties for this style.
    pub fn run_properties(mut self, rpr: CT_RPr) -> Self {
        self.style.rpr = Some(rpr);
        self.cleared &= !(CLEAR_RUN_PROPERTIES | CLEAR_FONT_THEME | CLEAR_COLOR_THEME);
        self
    }

    /// Set the explicit font in all four script slots and clear theme fonts.
    pub fn font(mut self, name: &str) -> Self {
        let rpr = self.style.rpr.get_or_insert_with(CT_RPr::default);
        rpr.font_ascii = Some(name.to_owned());
        rpr.font_hansi = Some(name.to_owned());
        rpr.font_east_asia = Some(name.to_owned());
        rpr.font_cs = Some(name.to_owned());
        rpr.font_ascii_theme = None;
        rpr.font_hansi_theme = None;
        rpr.font_east_asia_theme = None;
        rpr.font_cs_theme = None;
        self.cleared &= !CLEAR_RUN_PROPERTIES;
        self.cleared |= CLEAR_FONT_THEME;
        self
    }

    /// Set font size in points for normal and complex-script text.
    pub fn size(mut self, pt: f64) -> Self {
        let size = HalfPoint::from_pt(pt);
        let rpr = self.style.rpr.get_or_insert_with(CT_RPr::default);
        rpr.sz = Some(size);
        rpr.sz_cs = Some(size);
        self.cleared &= !CLEAR_RUN_PROPERTIES;
        self
    }

    /// Set bold formatting for normal and complex-script text.
    pub fn bold(mut self, value: bool) -> Self {
        let rpr = self.style.rpr.get_or_insert_with(CT_RPr::default);
        rpr.bold = Some(value);
        rpr.bold_cs = Some(value);
        self.cleared &= !CLEAR_RUN_PROPERTIES;
        self
    }

    /// Set a literal hex colour and clear its theme colour reference.
    pub fn color(mut self, hex: &str) -> Self {
        let rpr = self.style.rpr.get_or_insert_with(CT_RPr::default);
        rpr.color = Some(hex.to_owned());
        rpr.color_theme = None;
        rpr.color_theme_tint = None;
        rpr.color_theme_shade = None;
        self.cleared &= !CLEAR_RUN_PROPERTIES;
        self.cleared |= CLEAR_COLOR_THEME;
        self
    }

    /// Remove all run properties during an update.
    pub fn clear_run_properties(mut self) -> Self {
        self.style.rpr = None;
        self.cleared =
            (self.cleared | CLEAR_RUN_PROPERTIES) & !(CLEAR_FONT_THEME | CLEAR_COLOR_THEME);
        self
    }

    /// Set base table properties for a table style.
    pub fn table_properties(mut self, properties: CT_TblPr) -> Self {
        self.style.table_properties = Some(properties);
        self.cleared &= !CLEAR_TABLE_PROPERTIES;
        self
    }

    /// Remove all base table properties during an update.
    pub fn clear_table_properties(mut self) -> Self {
        self.style.table_properties = None;
        self.cleared |= CLEAR_TABLE_PROPERTIES;
        self
    }

    /// Set base table row properties for a table style.
    pub fn table_row_properties(mut self, properties: CT_TrPr) -> Self {
        self.style.table_row_properties = Some(Box::new(properties));
        self.cleared &= !CLEAR_TABLE_ROW_PROPERTIES;
        self
    }

    /// Remove all base table row properties during an update.
    pub fn clear_table_row_properties(mut self) -> Self {
        self.style.table_row_properties = None;
        self.cleared |= CLEAR_TABLE_ROW_PROPERTIES;
        self
    }

    /// Set base table cell properties for a table style.
    pub fn table_cell_properties(mut self, properties: CT_TcPr) -> Self {
        self.style.table_cell_properties = Some(Box::new(properties));
        self.cleared &= !CLEAR_TABLE_CELL_PROPERTIES;
        self
    }

    /// Remove all base table cell properties during an update.
    pub fn clear_table_cell_properties(mut self) -> Self {
        self.style.table_cell_properties = None;
        self.cleared |= CLEAR_TABLE_CELL_PROPERTIES;
        self
    }

    /// Remove all conditional table regions during an update.
    pub fn clear_conditional_table_styles(mut self) -> Self {
        self.style.conditional_table_styles.clear();
        self.cleared |= CLEAR_CONDITIONAL_TABLE_STYLES;
        self
    }

    /// Remove one conditional table region during an update.
    ///
    /// Every other region survives, which is what separates this from
    /// [`StyleBuilder::clear_conditional_table_styles`].
    pub fn remove_conditional_table_style(mut self, region: TableStyleRegion) -> Self {
        self.style
            .conditional_table_styles
            .retain(|conditional| conditional.region != Some(region));
        if !self.removed_regions.contains(&region) {
            self.removed_regions.push(region);
        }
        self
    }

    /// Add one conditional table style region in source order.
    ///
    /// The row layer is modeled and round-tripped. Its layout application
    /// belongs to F-268a.
    pub fn conditional_table_style(
        mut self,
        region: TableStyleRegion,
        paragraph_properties: Option<CT_PPr>,
        run_properties: Option<CT_RPr>,
        table_properties: Option<CT_TblPr>,
        row_properties: Option<CT_TrPr>,
        cell_properties: Option<CT_TcPr>,
    ) -> Self {
        self.removed_regions.retain(|removed| *removed != region);
        self.style.conditional_table_styles.push(CT_TblStylePr {
            region: Some(region),
            paragraph_properties,
            run_properties: run_properties.map(Box::new),
            table_properties,
            row_properties: row_properties.map(Box::new),
            cell_properties,
            extra_attributes: Vec::new(),
            raw_xml: Vec::new(),
        });
        self
    }

    /// Build the style (consumed by Document::add_style).
    pub(crate) fn build(self) -> (CT_Style, u32, Vec<TableStyleRegion>) {
        (self.style, self.cleared, self.removed_regions)
    }
}

/// The Word built-in styles `Document::add_common_styles` adds, in order.
///
/// Each carries the ID, name, UI priority, visibility flags and paragraph and
/// run formatting Word writes for it under the Office theme, with the theme
/// colours written as literal values the way the default `Heading1` has them.
/// No font is named, so the text keeps the document default font. `Table Grid`
/// has no `Normal Table` base, which a new document does not define, so it
/// carries that base's cell margins itself.
pub(crate) fn common_styles() -> Vec<CT_Style> {
    let spacing = |before: Option<i32>, after: i32, line: Option<i32>| CT_PPr {
        space_before: before.map(Twips),
        space_after: Some(Twips(after)),
        line_spacing: line.map(Twips),
        line_rule: line.map(|_| "auto".to_owned()),
        ..CT_PPr::default()
    };
    let text = |size: Option<u32>, color: &str, italic: bool| CT_RPr {
        sz: size.map(HalfPoint),
        sz_cs: size.map(HalfPoint),
        italic: italic.then_some(true),
        italic_cs: italic.then_some(true),
        color: Some(color.to_owned()),
        ..CT_RPr::default()
    };
    // Levels 2 to 9: half-point size (inherited when absent), colour, italic.
    let headings = [
        (Some(26), "2F5496", false),
        (Some(24), "1F3763", false),
        (None, "2F5496", true),
        (None, "2F5496", false),
        (None, "1F3763", false),
        (None, "1F3763", true),
        (Some(21), "272727", false),
        (Some(21), "272727", true),
    ];
    let mut styles = Vec::new();
    for (level, (size, color, italic)) in (2u32..).zip(headings) {
        let heading =
            StyleBuilder::paragraph(&format!("Heading{level}"), &format!("heading {level}"))
                .based_on("Normal")
                .next_style("Normal")
                .priority(9)
                .unhide_when_used(true)
                .quick_format(true)
                .paragraph_properties(CT_PPr {
                    keep_next: Some(true),
                    keep_lines: Some(true),
                    outline_lvl: Some(level - 1),
                    ..spacing(Some(40), 0, None)
                })
                .run_properties(text(size, color, italic));
        // Word hides heading 4 and deeper until they are used.
        styles.push(if level >= 4 {
            heading.semi_hidden(true)
        } else {
            heading
        });
    }
    let border = || {
        Some(CT_BorderEdge {
            sz: Some(4),
            space: Some(0),
            color: Some("auto".to_owned()),
            ..CT_BorderEdge::new(ST_Border::Single)
        })
    };
    styles.extend([
        StyleBuilder::paragraph("Title", "Title")
            .based_on("Normal")
            .next_style("Normal")
            .priority(10)
            .quick_format(true)
            .paragraph_properties(CT_PPr {
                contextual_spacing: Some(true),
                ..spacing(None, 0, Some(240))
            })
            .run_properties(CT_RPr {
                sz: Some(HalfPoint(56)),
                sz_cs: Some(HalfPoint(56)),
                spacing: Some(Twips(-10)),
                kern: Some(HalfPoint(28)),
                ..CT_RPr::default()
            }),
        StyleBuilder::paragraph("Subtitle", "Subtitle")
            .based_on("Normal")
            .next_style("Normal")
            .priority(11)
            .quick_format(true)
            .paragraph_properties(spacing(None, 160, None))
            .run_properties(CT_RPr {
                spacing: Some(Twips(15)),
                ..text(Some(22), "5A5A5A", false)
            }),
        StyleBuilder::paragraph("NoSpacing", "No Spacing")
            .priority(1)
            .quick_format(true)
            .paragraph_properties(spacing(None, 0, Some(240))),
        StyleBuilder::paragraph("Quote", "Quote")
            .based_on("Normal")
            .next_style("Normal")
            .priority(29)
            .quick_format(true)
            .paragraph_properties(CT_PPr {
                jc: Some(ST_Jc::Center),
                ind_left: Some(Twips(864)),
                ind_right: Some(Twips(864)),
                ..spacing(Some(200), 160, None)
            })
            .run_properties(text(None, "404040", true)),
        StyleBuilder::paragraph("ListParagraph", "List Paragraph")
            .based_on("Normal")
            .priority(34)
            .quick_format(true)
            .paragraph_properties(CT_PPr {
                ind_left: Some(Twips(720)),
                contextual_spacing: Some(true),
                ..CT_PPr::default()
            }),
        StyleBuilder::paragraph("Caption", "caption")
            .based_on("Normal")
            .next_style("Normal")
            .priority(35)
            .semi_hidden(true)
            .unhide_when_used(true)
            .quick_format(true)
            .paragraph_properties(spacing(None, 200, Some(240)))
            .run_properties(text(Some(18), "44546A", true)),
        StyleBuilder::table("TableGrid", "Table Grid")
            .priority(39)
            .paragraph_properties(spacing(None, 0, Some(240)))
            .table_properties(CT_TblPr {
                borders: Some(CT_TblBorders {
                    top: border(),
                    left: border(),
                    bottom: border(),
                    right: border(),
                    inside_h: border(),
                    inside_v: border(),
                    ..CT_TblBorders::default()
                }),
                cell_margin: Some(CT_TblCellMar {
                    top: Some(Twips(0)),
                    left: Some(Twips(108)),
                    bottom: Some(Twips(0)),
                    right: Some(Twips(108)),
                }),
                ..CT_TblPr::default()
            }),
    ]);
    styles
        .into_iter()
        .map(|builder| builder.build().0)
        .collect()
}

pub(crate) fn validate_style_graph(styles: &CT_Styles) -> Result<()> {
    match style_graph_defects(styles).into_iter().next() {
        Some(defect) => Err(style_graph_error(defect)),
        None => Ok(()),
    }
}

/// Validate a staged change to a style graph a producer may already have
/// left invalid.
///
/// Each defect `staged` shares with `source` is returned once, in check order,
/// for the caller to report. Defects are counted, so a defect `staged` has more
/// often than `source` was introduced by the change and rejects it, even when
/// the source already had the same one, such as a shadowed definition of a
/// repeated ID or another style inheriting an existing cycle.
pub(crate) fn validate_style_graph_change(
    source: &CT_Styles,
    staged: &CT_Styles,
) -> Result<Vec<String>> {
    let mut source_defects = style_graph_defects(source);
    let mut retained = Vec::new();
    for defect in style_graph_defects(staged) {
        let Some(index) = source_defects.iter().position(|known| *known == defect) else {
            return Err(style_graph_error(defect));
        };
        source_defects.swap_remove(index);
        if !retained.contains(&defect) {
            retained.push(defect);
        }
    }
    Ok(retained)
}

/// Every defect in check order. The first is the one `validate_style_graph`
/// reports.
fn style_graph_defects(styles: &CT_Styles) -> Vec<String> {
    let mut defects = Vec::new();
    let mut by_id = HashMap::new();
    for style in &styles.styles {
        if style.style_id.is_empty() {
            defects.push("style IDs cannot be empty".to_owned());
        } else if by_id.contains_key(style.style_id.as_str()) {
            defects.push(format!("duplicate style ID '{}'", style.style_id));
        } else {
            by_id.insert(style.style_id.as_str(), style);
        }
    }

    for style_type in [
        StyleType::Paragraph,
        StyleType::Character,
        StyleType::Table,
        StyleType::Numbering,
    ] {
        let defaults = styles
            .styles
            .iter()
            .filter(|style| style.style_type == style_type && style.is_default)
            .count();
        if defaults > 1 {
            defects.push(format!(
                "style type '{}' has more than one default",
                style_type.to_str()
            ));
        }
    }

    for style in &styles.styles {
        if style.style_type == StyleType::Character && style.ppr.is_some() {
            defects.push(format!(
                "character style '{}' cannot contain paragraph properties",
                style.style_id
            ));
        }
        if style.style_type != StyleType::Table
            && (style.table_properties.is_some()
                || style.table_row_properties.is_some()
                || style.table_cell_properties.is_some()
                || !style.conditional_table_styles.is_empty())
        {
            defects.push(format!(
                "{} style '{}' cannot contain table properties",
                style.style_type.to_str(),
                style.style_id
            ));
        }
        // Region validity is unrepresentable rather than checked. An
        // unrecognised `w:type` parses as `None`, round-trips from its
        // preserved bytes and is never a reason to refuse a file Word wrote,
        // so only recognised regions take part in the duplicate check.
        let mut conditional_regions = HashSet::new();
        for region in style
            .conditional_table_styles
            .iter()
            .filter_map(|conditional| conditional.region)
        {
            if !conditional_regions.insert(region) {
                defects.push(format!(
                    "table style '{}' repeats conditional region '{}'",
                    style.style_id,
                    region.to_str()
                ));
            }
        }

        if let Some(parent_id) = style.based_on.as_deref() {
            match by_id.get(parent_id) {
                None => defects.push(format!(
                    "style '{}' is based on missing style '{parent_id}'",
                    style.style_id
                )),
                Some(parent) if parent.style_type != style.style_type => {
                    defects.push(format!(
                        "style '{}' cannot be based on {} style '{parent_id}'",
                        style.style_id,
                        parent.style_type.to_str()
                    ));
                }
                Some(_) => {}
            }
        }

        if let Some(next_id) = style.next_style.as_deref() {
            if style.style_type != StyleType::Paragraph {
                defects.push(format!(
                    "{} style '{}' cannot declare a next style",
                    style.style_type.to_str(),
                    style.style_id
                ));
            } else {
                match by_id.get(next_id) {
                    None => defects.push(format!(
                        "style '{}' names missing next style '{next_id}'",
                        style.style_id
                    )),
                    Some(next) if next.style_type != StyleType::Paragraph => {
                        defects.push(format!(
                            "paragraph style '{}' has non-paragraph next style '{next_id}'",
                            style.style_id
                        ));
                    }
                    Some(_) => {}
                }
            }
        }

        if let Some(linked_id) = style.linked_style.as_deref() {
            match by_id.get(linked_id) {
                None => defects.push(format!(
                    "style '{}' links to missing style '{linked_id}'",
                    style.style_id
                )),
                Some(linked) => {
                    let legal_types = matches!(
                        (style.style_type, linked.style_type),
                        (StyleType::Paragraph, StyleType::Character)
                            | (StyleType::Character, StyleType::Paragraph)
                    );
                    if !legal_types {
                        defects.push(format!(
                            "{} style '{}' cannot link to {} style '{linked_id}'",
                            style.style_type.to_str(),
                            style.style_id,
                            linked.style_type.to_str()
                        ));
                    } else if linked.linked_style.as_deref() != Some(style.style_id.as_str()) {
                        defects.push(format!(
                            "linked styles '{}' and '{linked_id}' are not reciprocal",
                            style.style_id
                        ));
                    }
                }
            }
        }
    }

    for style in &styles.styles {
        let mut seen = HashSet::new();
        let mut current = Some(style.style_id.as_str());
        while let Some(style_id) = current {
            if !seen.insert(style_id) {
                defects.push(format!("based-on cycle contains style '{style_id}'"));
                break;
            }
            current = by_id
                .get(style_id)
                .and_then(|current_style| current_style.based_on.as_deref());
        }
    }

    defects
}

fn style_graph_error(message: impl Into<String>) -> Error {
    Error::Other(format!("invalid style graph: {}", message.into()))
}

/// Resolve the effective paragraph properties by walking the style inheritance chain.
pub fn resolve_paragraph_properties(style_id: Option<&str>, styles: &CT_Styles) -> CT_PPr {
    let mut effective = CT_PPr::default();

    // Start from docDefaults
    if let Some(ref defaults) = styles.doc_defaults
        && let Some(ref ppr) = defaults.ppr
    {
        effective.merge_from(ppr);
    }

    // Walk the selected style's basedOn chain.
    let selected_style_id = style_id.or_else(|| {
        styles
            .get_default(StyleType::Paragraph)
            .map(|style| style.style_id.as_str())
    });
    if let Some(sid) = selected_style_id {
        let chain = collect_style_chain(sid, styles);
        // Apply from most-base to most-derived
        for style in chain.iter().rev() {
            if let Some(ref ppr) = style.ppr {
                effective.merge_from(ppr);
            }
        }
    }

    effective
}

/// Resolve the effective run properties by walking the style inheritance chain.
pub fn resolve_run_properties(
    para_style_id: Option<&str>,
    run_style_id: Option<&str>,
    styles: &CT_Styles,
) -> CT_RPr {
    let mut effective = CT_RPr::default();

    // Start from docDefaults
    if let Some(ref defaults) = styles.doc_defaults
        && let Some(ref rpr) = defaults.rpr
    {
        effective.merge_from(rpr);
    }

    // Apply paragraph style's rpr
    let para_sid = para_style_id.or_else(|| {
        styles
            .get_default(StyleType::Paragraph)
            .map(|s| s.style_id.as_str())
    });
    if let Some(sid) = para_sid {
        let chain = collect_style_chain(sid, styles);
        for style in chain.iter().rev() {
            if let Some(ref rpr) = style.rpr {
                effective.merge_from(rpr);
            }
        }
    }

    // Apply character style's rpr
    if let Some(sid) = run_style_id.and_then(|style_id| character_style_id(style_id, styles)) {
        let chain = collect_style_chain(sid, styles);
        for style in chain.iter().rev() {
            if let Some(ref rpr) = style.rpr {
                effective.merge_from(rpr);
            }
        }
    }

    effective
}

fn character_style_id<'a>(style_id: &'a str, styles: &'a CT_Styles) -> Option<&'a str> {
    let style = styles.get_by_id(style_id)?;
    match style.style_type {
        StyleType::Character => Some(style.style_id.as_str()),
        StyleType::Paragraph => style.linked_style.as_deref().filter(|linked_id| {
            styles
                .get_by_id(linked_id)
                .is_some_and(|linked| linked.style_type == StyleType::Character)
        }),
        StyleType::Table | StyleType::Numbering => None,
    }
}

/// Collect the chain of styles from the given style up through basedOn ancestors.
fn collect_style_chain<'a>(style_id: &str, styles: &'a CT_Styles) -> Vec<&'a CT_Style> {
    let mut chain = Vec::new();
    let mut current_id = Some(style_id.to_string());
    let mut seen = std::collections::HashSet::new();

    while let Some(ref sid) = current_id {
        if !seen.insert(sid.clone()) {
            break; // Prevent cycles
        }
        if let Some(style) = styles.get_by_id(sid) {
            chain.push(style);
            current_id = style.based_on.clone();
        } else {
            break;
        }
    }

    chain
}

#[cfg(test)]
mod tests {
    use super::*;
    use rdocx_oxml::units::{HalfPoint, Twips};

    fn test_styles() -> CT_Styles {
        let mut styles = CT_Styles::new_default();

        // Add a Heading2 based on Heading1
        styles.styles.push(CT_Style {
            style_id: "Heading2".to_string(),
            style_type: StyleType::Paragraph,
            name: Some("heading 2".to_string()),
            based_on: Some("Heading1".to_string()),
            next_style: Some("Normal".to_string()),
            linked_style: None,
            auto_redefine: None,
            hidden: None,
            ui_priority: None,
            semi_hidden: None,
            unhide_when_used: None,
            quick_format: None,
            locked: None,
            is_default: false,
            ppr: Some(CT_PPr {
                space_before: Some(Twips(40)), // Override Heading1's 240
                ..Default::default()
            }),
            rpr: Some(CT_RPr {
                sz: Some(HalfPoint(26)), // Override Heading1's 32
                color: Some("2E74B5".to_string()),
                ..Default::default()
            }),
            table_properties: None,
            table_properties_original: None,
            table_properties_xml: None,
            table_row_properties: None,
            table_cell_properties: None,
            conditional_table_styles: Vec::new(),
            extra_attributes: Vec::new(),
            modeled_xml: Vec::new(),
            extra_xml: Vec::new(),
        });

        styles
    }

    #[test]
    fn resolve_normal_paragraph() {
        let styles = test_styles();
        let ppr = resolve_paragraph_properties(Some("Normal"), &styles);
        // Should have docDefaults' spacing
        assert_eq!(ppr.space_after, Some(Twips(160)));
    }

    #[test]
    fn resolve_heading1() {
        let styles = test_styles();
        let ppr = resolve_paragraph_properties(Some("Heading1"), &styles);
        // keepNext from Heading1
        assert_eq!(ppr.keep_next, Some(true));
        // spaceBefore from Heading1 (overrides docDefaults which has none)
        assert_eq!(ppr.space_before, Some(Twips(240)));
        // spaceAfter from Heading1 overrides docDefaults
        assert_eq!(ppr.space_after, Some(Twips(0)));
    }

    #[test]
    fn resolve_heading2_inherits_heading1() {
        let styles = test_styles();
        let ppr = resolve_paragraph_properties(Some("Heading2"), &styles);
        // keepNext inherited from Heading1
        assert_eq!(ppr.keep_next, Some(true));
        // spaceBefore overridden by Heading2
        assert_eq!(ppr.space_before, Some(Twips(40)));
    }

    #[test]
    fn resolve_heading2_rpr() {
        let styles = test_styles();
        let rpr = resolve_run_properties(Some("Heading2"), None, &styles);
        // Font from docDefaults
        assert_eq!(rpr.font_ascii, Some("Calibri".to_string()));
        // Size overridden by Heading2 (not Heading1's 32)
        assert_eq!(rpr.sz, Some(HalfPoint(26)));
        // Bold inherited from Heading1
        assert_eq!(rpr.bold, Some(true));
        // Color from Heading2
        assert_eq!(rpr.color, Some("2E74B5".to_string()));
    }

    #[test]
    fn new_paragraph_properties_inherit_through_the_style_chain() {
        use rdocx_oxml::properties::CT_FramePr;

        let mut styles = test_styles();
        let defaults = styles
            .doc_defaults
            .as_mut()
            .expect("docDefaults")
            .ppr
            .get_or_insert_with(CT_PPr::default);
        defaults.suppress_line_numbers = Some(true);
        defaults.text_alignment = Some("baseline".to_owned());
        for style in &mut styles.styles {
            let ppr = style.ppr.get_or_insert_with(CT_PPr::default);
            if style.style_id == "Heading1" {
                ppr.contextual_spacing = Some(true);
                ppr.text_direction = Some("tbRlV".to_owned());
                ppr.text_alignment = Some("center".to_owned());
                ppr.frame = Some(Box::new(CT_FramePr {
                    w: Some(Twips(2880)),
                    ..Default::default()
                }));
                ppr.div_id = Some(4);
            }
            if style.style_id == "Heading2" {
                ppr.mirror_indents = Some(true);
                ppr.text_direction = Some("lrTb".to_owned());
            }
        }

        let ppr = resolve_paragraph_properties(Some("Heading2"), &styles);
        assert_eq!(ppr.suppress_line_numbers, Some(true));
        assert_eq!(ppr.contextual_spacing, Some(true));
        assert_eq!(ppr.mirror_indents, Some(true));
        assert_eq!(ppr.text_alignment.as_deref(), Some("center"));
        assert_eq!(ppr.text_direction.as_deref(), Some("lrTb"));
        assert_eq!(ppr.frame.and_then(|frame| frame.w), Some(Twips(2880)));
        assert_eq!(ppr.div_id, Some(4));
    }

    #[test]
    fn resolve_default_when_no_style() {
        let mut styles = test_styles();
        for style in &mut styles.styles {
            style.is_default = style.style_id == "Heading2";
        }
        let ppr = resolve_paragraph_properties(None, &styles);
        assert_eq!(ppr.keep_next, Some(true));
        assert_eq!(ppr.space_before, Some(Twips(40)));
        assert_eq!(ppr.space_after, Some(Twips(0)));
    }

    #[test]
    fn style_graph_change_retains_producer_defects_and_rejects_introduced_ones() {
        let mut source = test_styles();
        for (builder, is_default) in [
            (
                StyleBuilder::paragraph("Orphan", "Orphan").based_on("Missing"),
                false,
            ),
            (StyleBuilder::paragraph("SecondDefault", "Second"), true),
            (
                StyleBuilder::character("OneWay", "One Way").linked_style("Normal"),
                false,
            ),
        ] {
            let (mut style, _, _) = builder.build();
            style.is_default = is_default;
            source.styles.push(style);
        }
        // Strict validation still fails on the first defect in check order.
        assert_eq!(
            validate_style_graph(&source).unwrap_err().to_string(),
            "invalid style graph: style type 'paragraph' has more than one default"
        );
        assert_eq!(
            validate_style_graph_change(&source, &source).unwrap(),
            [
                "style type 'paragraph' has more than one default",
                "style 'Orphan' is based on missing style 'Missing'",
                "linked styles 'OneWay' and 'Normal' are not reciprocal",
            ]
        );

        // Resolving the dangling parent closes a cycle the source did not have.
        let mut staged = source.clone();
        let (parent, _, _) = StyleBuilder::paragraph("Missing", "Missing")
            .based_on("Orphan")
            .build();
        staged.styles.push(parent);
        assert_eq!(
            validate_style_graph_change(&source, &staged)
                .unwrap_err()
                .to_string(),
            "invalid style graph: based-on cycle contains style 'Orphan'"
        );
    }
}