office2pdf 0.6.5

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

#[test]
fn test_generate_plain_paragraph() {
    let doc = make_doc(vec![make_flow_page(vec![make_paragraph("Hello World")])]);
    let result = generate_typst(&doc).unwrap().source;
    assert!(result.contains("Hello World"));
}

#[test]
fn test_generate_empty_paragraph_reserves_line_height() {
    let doc = make_doc(vec![make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle::default(),
        runs: Vec::new(),
    })])]);
    let result = generate_typst(&doc).unwrap().source;

    assert!(
        result.contains("#v(12pt)"),
        "empty DOCX paragraph marks should reserve vertical flow space: {result}"
    );
}

#[test]
fn test_generate_page_setup() {
    let doc = make_doc(vec![Page::Flow(FlowPage {
        size: PageSize {
            width: 612.0,
            height: 792.0,
        },
        margins: Margins {
            top: 36.0,
            bottom: 36.0,
            left: 54.0,
            right: 54.0,
        },
        content: vec![make_paragraph("test")],
        header: None,
        footer: None,
        columns: None,
        line_grid_pitch: None,
        line_grid_snaps_lines: false,
    })]);
    let result = generate_typst(&doc).unwrap().source;
    assert!(result.contains("612pt"));
    assert!(result.contains("792pt"));
    assert!(result.contains("36pt"));
    assert!(result.contains("54pt"));
}

#[test]
fn test_generate_bold_text() {
    let doc = make_doc(vec![make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle::default(),
        runs: vec![Run {
            text: "Bold text".to_string(),
            style: TextStyle {
                bold: Some(true),
                ..TextStyle::default()
            },
            href: None,
            footnote: None,
        }],
    })])]);
    let result = generate_typst(&doc).unwrap().source;
    assert!(
        result.contains("weight: \"bold\""),
        "Expected bold weight in: {result}"
    );
    assert!(result.contains("Bold text"));
}

#[test]
fn test_generate_italic_text() {
    let doc = make_doc(vec![make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle::default(),
        runs: vec![Run {
            text: "Italic text".to_string(),
            style: TextStyle {
                italic: Some(true),
                ..TextStyle::default()
            },
            href: None,
            footnote: None,
        }],
    })])]);
    let result = generate_typst(&doc).unwrap().source;
    assert!(
        result.contains("style: \"italic\""),
        "Expected italic style in: {result}"
    );
    assert!(result.contains("Italic text"));
}

#[test]
fn test_generate_underline_text() {
    let doc = make_doc(vec![make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle::default(),
        runs: vec![Run {
            text: "Underlined".to_string(),
            style: TextStyle {
                underline: Some(true),
                ..TextStyle::default()
            },
            href: None,
            footnote: None,
        }],
    })])]);
    let result = generate_typst(&doc).unwrap().source;
    assert!(
        result.contains("#underline["),
        "Expected underline wrapper in: {result}"
    );
    assert!(result.contains("Underlined"));
}

#[test]
fn test_generate_font_size() {
    let doc = make_doc(vec![make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle::default(),
        runs: vec![Run {
            text: "Large text".to_string(),
            style: TextStyle {
                font_size: Some(24.0),
                ..TextStyle::default()
            },
            href: None,
            footnote: None,
        }],
    })])]);
    let result = generate_typst(&doc).unwrap().source;
    assert!(
        result.contains("size: 24pt"),
        "Expected font size in: {result}"
    );
}

#[test]
fn test_generate_font_color() {
    let doc = make_doc(vec![make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle::default(),
        runs: vec![Run {
            text: "Red text".to_string(),
            style: TextStyle {
                color: Some(Color::new(255, 0, 0)),
                ..TextStyle::default()
            },
            href: None,
            footnote: None,
        }],
    })])]);
    let result = generate_typst(&doc).unwrap().source;
    assert!(
        result.contains("fill: rgb(255, 0, 0)"),
        "Expected RGB color in: {result}"
    );
}

#[test]
fn test_generate_combined_text_styles() {
    let doc = make_doc(vec![make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle::default(),
        runs: vec![Run {
            text: "Styled".to_string(),
            style: TextStyle {
                bold: Some(true),
                italic: Some(true),
                font_size: Some(16.0),
                color: Some(Color::new(0, 128, 255)),
                ..TextStyle::default()
            },
            href: None,
            footnote: None,
        }],
    })])]);
    let result = generate_typst(&doc).unwrap().source;
    assert!(result.contains("weight: \"bold\""));
    assert!(result.contains("style: \"italic\""));
    assert!(result.contains("size: 16pt"));
    assert!(result.contains("fill: rgb(0, 128, 255)"));
    assert!(result.contains("Styled"));
}

#[test]
fn test_generate_alignment_center() {
    let doc = make_doc(vec![make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle {
            alignment: Some(Alignment::Center),
            ..ParagraphStyle::default()
        },
        runs: vec![Run {
            text: "Centered".to_string(),
            style: TextStyle::default(),
            href: None,
            footnote: None,
        }],
    })])]);
    let result = generate_typst(&doc).unwrap().source;
    assert!(
        result.contains("align(center"),
        "Expected center alignment in: {result}"
    );
}

#[test]
fn test_generate_alignment_right() {
    let doc = make_doc(vec![make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle {
            alignment: Some(Alignment::Right),
            ..ParagraphStyle::default()
        },
        runs: vec![Run {
            text: "Right".to_string(),
            style: TextStyle::default(),
            href: None,
            footnote: None,
        }],
    })])]);
    let result = generate_typst(&doc).unwrap().source;
    assert!(
        result.contains("align(right"),
        "Expected right alignment in: {result}"
    );
}

#[test]
fn test_generate_alignment_justify() {
    let doc = make_doc(vec![make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle {
            alignment: Some(Alignment::Justify),
            ..ParagraphStyle::default()
        },
        runs: vec![Run {
            text: "Justified text".to_string(),
            style: TextStyle::default(),
            href: None,
            footnote: None,
        }],
    })])]);
    let result = generate_typst(&doc).unwrap().source;
    assert!(
        result.contains("par(justify: true") || result.contains("set par(justify: true"),
        "Expected justify in: {result}"
    );
}

#[test]
fn test_generate_line_spacing_proportional() {
    let doc = make_doc(vec![make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle {
            line_spacing: Some(LineSpacing::Proportional(2.0)),
            ..ParagraphStyle::default()
        },
        runs: vec![Run {
            text: "Double spaced".to_string(),
            style: TextStyle::default(),
            href: None,
            footnote: None,
        }],
    })])]);
    let result = generate_typst(&doc).unwrap().source;
    assert!(
        result.contains("leading:"),
        "Expected leading setting in: {result}"
    );
}

#[test]
fn test_generate_line_spacing_exact() {
    let doc = make_doc(vec![make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle {
            line_spacing: Some(LineSpacing::Exact(18.0)),
            ..ParagraphStyle::default()
        },
        runs: vec![Run {
            text: "Exact spaced".to_string(),
            style: TextStyle::default(),
            href: None,
            footnote: None,
        }],
    })])]);
    let result = generate_typst(&doc).unwrap().source;
    assert!(
        result.contains("leading: 18pt"),
        "Expected exact leading in: {result}"
    );
}

#[test]
fn test_generate_word_default_line_box() {
    let doc = make_doc(vec![make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle {
            line_box: Some(LineBox {
                ascent_em: 1.3125,
                descent_em: 0.4375,
            }),
            space_after: Some(8.0),
            ..ParagraphStyle::default()
        },
        runs: vec![Run {
            text: "Word defaults".to_string(),
            style: TextStyle::default(),
            href: None,
            footnote: None,
        }],
    })])]);
    let source = generate_typst(&doc).unwrap().source;

    assert!(
        source.contains("#set text(top-edge: 1.3125em, bottom-edge: -0.4375em)"),
        "Expected Word-compatible line edges in: {source}"
    );
    assert!(
        source.contains("#set par(leading: 0pt)"),
        "Expected Word-compatible line stacking in: {source}"
    );
    assert!(
        source.contains("below: 8pt"),
        "Expected paragraph spacing in: {source}"
    );
}

#[test]
fn test_generate_letter_spacing() {
    let doc = make_doc(vec![make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle::default(),
        runs: vec![Run {
            text: "Spaced text".to_string(),
            style: TextStyle {
                letter_spacing: Some(2.0),
                ..TextStyle::default()
            },
            href: None,
            footnote: None,
        }],
    })])]);
    let result = generate_typst(&doc).unwrap().source;
    assert!(
        result.contains("tracking: 2pt"),
        "Expected tracking param in: {result}"
    );
}

#[test]
fn test_generate_letter_spacing_negative() {
    let doc = make_doc(vec![make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle::default(),
        runs: vec![Run {
            text: "Condensed".to_string(),
            style: TextStyle {
                letter_spacing: Some(-0.5),
                ..TextStyle::default()
            },
            href: None,
            footnote: None,
        }],
    })])]);
    let result = generate_typst(&doc).unwrap().source;
    assert!(
        result.contains("tracking: -0.5pt"),
        "Expected negative tracking in: {result}"
    );
}

#[test]
fn test_generate_tab_uses_measured_default_stops() {
    let doc = make_doc(vec![make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle::default(),
        runs: vec![Run {
            text: "Name:\tValue".to_string(),
            style: TextStyle::default(),
            href: None,
            footnote: None,
        }],
    })])]);
    let result = generate_typst(&doc).unwrap().source;
    assert!(
        result.contains("#context {"),
        "Expected contextual tab rendering in: {result}"
    );
    assert!(
        result.contains("measure(tab_prefix_0).width"),
        "Expected tab spacing to measure the rendered prefix in: {result}"
    );
    assert!(
        result.contains("calc.rem-euclid(tab_prefix_width_1.abs.pt(), 36)"),
        "Expected default tabs to advance to the next 36pt stop in: {result}"
    );
    assert!(
        !result.contains("#h(36pt)"),
        "Expected default tabs to avoid a hard-coded 36pt gap in: {result}"
    );
}

#[test]
fn test_generate_tab_uses_next_explicit_stop_and_alignment() {
    use crate::ir::{TabAlignment, TabLeader, TabStop};

    let doc = make_doc(vec![make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle {
            tab_stops: Some(vec![
                TabStop {
                    position: 72.0,
                    alignment: TabAlignment::Left,
                    leader: TabLeader::None,
                },
                TabStop {
                    position: 216.0,
                    alignment: TabAlignment::Right,
                    leader: TabLeader::Dot,
                },
            ]),
            ..ParagraphStyle::default()
        },
        runs: vec![Run {
            text: "Col1\tCol2\tCol3".to_string(),
            style: TextStyle::default(),
            href: None,
            footnote: None,
        }],
    })])]);
    let result = generate_typst(&doc).unwrap().source;
    assert!(
        result.contains("if tab_prefix_width_1 < 72pt"),
        "Expected the first explicit stop to be chosen by measured width in: {result}"
    );
    assert!(
        result.contains("else if tab_prefix_width_2 < 216pt"),
        "Expected the next explicit stop to be selected after the first one in: {result}"
    );
    assert!(
        result.contains("216pt - tab_prefix_width_2 - tab_segment_width_2"),
        "Expected right-aligned tabs to subtract the following segment width in: {result}"
    );
}

#[test]
fn test_generate_tab_falls_back_to_next_default_stop_after_explicit_tabs() {
    use crate::ir::{TabAlignment, TabLeader, TabStop};

    let doc = make_doc(vec![make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle {
            tab_stops: Some(vec![TabStop {
                position: 100.0,
                alignment: TabAlignment::Left,
                leader: TabLeader::None,
            }]),
            ..ParagraphStyle::default()
        },
        runs: vec![Run {
            text: "A\tB\tC".to_string(),
            style: TextStyle::default(),
            href: None,
            footnote: None,
        }],
    })])]);
    let result = generate_typst(&doc).unwrap().source;
    assert!(
        result.contains("if tab_prefix_width_1 < 100pt"),
        "Expected the explicit stop to be used when it is still ahead of the prefix in: {result}"
    );
    assert!(
        result.contains("calc.rem-euclid(tab_prefix_width_2.abs.pt(), 36)"),
        "Expected tabs beyond explicit stops to use the next default stop in: {result}"
    );
}

#[test]
fn test_generate_tab_leader_uses_repeat_fill() {
    use crate::ir::{TabAlignment, TabLeader, TabStop};

    let doc = make_doc(vec![make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle {
            tab_stops: Some(vec![TabStop {
                position: 144.0,
                alignment: TabAlignment::Left,
                leader: TabLeader::Dot,
            }]),
            ..ParagraphStyle::default()
        },
        runs: vec![Run {
            text: "Heading\t12".to_string(),
            style: TextStyle::default(),
            href: None,
            footnote: None,
        }],
    })])]);
    let result = generate_typst(&doc).unwrap().source;
    assert!(
        result.contains("box(width: tab_advance_1, repeat[.])"),
        "Expected dot tab leaders to render with Typst repeat fill in: {result}"
    );
}

#[test]
fn test_generate_decimal_tab_uses_decimal_separator_not_thousands_separator() {
    use crate::ir::{TabAlignment, TabLeader, TabStop};

    let doc = make_doc(vec![make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle {
            tab_stops: Some(vec![TabStop {
                position: 180.0,
                alignment: TabAlignment::Decimal,
                leader: TabLeader::None,
            }]),
            ..ParagraphStyle::default()
        },
        runs: vec![Run {
            text: "Total\t1,234.56".to_string(),
            style: TextStyle::default(),
            href: None,
            footnote: None,
        }],
    })])]);
    let result = generate_typst(&doc).unwrap().source;
    assert!(
        result.contains("let tab_decimal_anchor_1 = [1,234]"),
        "Expected decimal alignment to anchor after the thousands group in: {result}"
    );
}

#[test]
fn test_generate_decimal_tab_handles_comma_decimal_locale() {
    use crate::ir::{TabAlignment, TabLeader, TabStop};

    let doc = make_doc(vec![make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle {
            tab_stops: Some(vec![TabStop {
                position: 180.0,
                alignment: TabAlignment::Decimal,
                leader: TabLeader::None,
            }]),
            ..ParagraphStyle::default()
        },
        runs: vec![Run {
            text: "Total\t1.234,56".to_string(),
            style: TextStyle::default(),
            href: None,
            footnote: None,
        }],
    })])]);
    let result = generate_typst(&doc).unwrap().source;
    assert!(
        result.contains("let tab_decimal_anchor_1 = [1.234]"),
        "Expected decimal alignment to anchor on the locale decimal separator in: {result}"
    );
}

#[test]
fn test_generate_multiple_paragraphs() {
    let doc = make_doc(vec![make_flow_page(vec![
        make_paragraph("First paragraph"),
        make_paragraph("Second paragraph"),
    ])]);
    let result = generate_typst(&doc).unwrap().source;
    assert!(result.contains("First paragraph"));
    assert!(result.contains("Second paragraph"));
    assert!(
        result.contains("First paragraph\n\nSecond paragraph"),
        "Expected paragraph break between flow paragraphs in: {result}"
    );
}

#[test]
fn test_generate_paragraph_with_multiple_runs() {
    let doc = make_doc(vec![make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle::default(),
        runs: vec![
            Run {
                text: "Normal ".to_string(),
                style: TextStyle::default(),
                href: None,
                footnote: None,
            },
            Run {
                text: "bold".to_string(),
                style: TextStyle {
                    bold: Some(true),
                    ..TextStyle::default()
                },
                href: None,
                footnote: None,
            },
            Run {
                text: " normal again".to_string(),
                style: TextStyle::default(),
                href: None,
                footnote: None,
            },
        ],
    })])]);
    let result = generate_typst(&doc).unwrap().source;
    assert!(result.contains("Normal "));
    assert!(result.contains("bold"));
    assert!(result.contains(" normal again"));
}

#[test]
fn test_generate_empty_document() {
    let doc = make_doc(vec![]);
    let result = generate_typst(&doc).unwrap().source;
    assert!(result.is_empty() || !result.is_empty());
}

#[test]
fn test_generate_special_characters_escaped() {
    let doc = make_doc(vec![make_flow_page(vec![make_paragraph(
        "Price: $100 #items @store",
    )])]);
    let result = generate_typst(&doc).unwrap().source;
    assert!(
        result.contains("\\#") || result.contains("Price"),
        "Expected escaped or present text in: {result}"
    );
}

#[test]
fn test_centered_paragraph_with_spacing_keeps_full_width_block() {
    // A paragraph with spacing gets a #block wrapper; without width: 100%
    // the block shrinks to its content and the inner #align(center) has no
    // visible effect (Word: <w:spacing w:after> + <w:jc w:val="center">).
    let doc = make_doc(vec![make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle {
            alignment: Some(Alignment::Center),
            space_after: Some(6.0),
            ..ParagraphStyle::default()
        },
        runs: vec![Run {
            text: "Centered title".to_string(),
            style: TextStyle::default(),
            href: None,
            footnote: None,
        }],
    })])]);
    let result = generate_typst(&doc).unwrap().source;
    assert!(
        result.contains("align(center"),
        "Expected center alignment in: {result}"
    );
    let block_start = result.find("#block(").expect("expected block wrapper");
    let block_params = &result[block_start..block_start + 60];
    assert!(
        block_params.contains("width: 100%"),
        "Block wrapper must span the full width for alignment to apply: {block_params}"
    );
}

#[test]
fn test_document_grid_pitch_snaps_line_height() {
    // A Korean Word section whose <w:docGrid> snaps lines puts body lines on
    // an 18pt grid. The line box is clamped to a fixed em height equal to the
    // grid pitch (leading 0) so a taller fallback glyph on a line cannot
    // inflate its advance past the grid (issue #398). The baseline keeps its
    // constant ascent inside that box: the slot's slack accrues below it, not
    // around it (issue #518). Uses a font from Typst's embedded set so the
    // test is environment-free.
    let Some((_, _, word_pitch_em)) = crate::render::pdf::font_line_metrics_em("Libertinus Serif")
    else {
        return; // no font book available (e.g. exotic CI sandbox)
    };
    let mut page = match make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle::default(),
        runs: vec![Run {
            text: "그리드 정렬 grid snapped".to_string(),
            style: TextStyle {
                font_family: Some("Libertinus Serif".to_string()),
                font_size: Some(10.0),
                ..TextStyle::default()
            },
            href: None,
            footnote: None,
        }],
    })]) {
        Page::Flow(flow) => flow,
        _ => unreachable!(),
    };
    page.line_grid_pitch = Some(18.0);
    page.line_grid_snaps_lines = true;
    let doc = make_doc(vec![Page::Flow(page)]);
    let result = generate_typst(&doc).unwrap().source;

    assert_line_advance(
        &result,
        "Libertinus Serif",
        10.0,
        18.0,
        0.15 * word_pitch_em,
    );
    assert!(
        result.contains("leading: 0pt"),
        "the grid advance is carried by the box, not by leading: {result}"
    );
}

#[test]
fn test_latin_paragraph_ignores_document_grid() {
    // Word leaves Latin-only paragraphs at their metric line height even
    // when the section carries a document grid; only East Asian text snaps
    // (issue #354).
    let mut page = match make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle::default(),
        runs: vec![Run {
            text: "latin only body text".to_string(),
            style: TextStyle {
                font_family: Some("Libertinus Serif".to_string()),
                font_size: Some(10.0),
                ..TextStyle::default()
            },
            href: None,
            footnote: None,
        }],
    })]) {
        Page::Flow(flow) => flow,
        _ => unreachable!(),
    };
    page.line_grid_pitch = Some(18.0);
    page.line_grid_snaps_lines = true;
    let doc = make_doc(vec![Page::Flow(page)]);
    let result = generate_typst(&doc).unwrap().source;

    // The paragraph keeps Word's hhea single-spacing advance; the 18pt grid
    // pitch must not appear in its line box.
    let Some((ascender, descender, word_pitch)) =
        crate::render::pdf::font_line_metrics_em("Libertinus Serif")
    else {
        return;
    };
    let single_pt: f64 = (word_pitch * 10.0).max((ascender + descender) * 10.0);
    assert_line_advance(&result, "Libertinus Serif", 10.0, single_pt, 0.0);
    assert!(
        (single_pt - 18.0).abs() > 0.01,
        "the fixture only proves anything if the grid pitch differs from single spacing"
    );
}

#[test]
fn test_no_document_grid_uses_word_single_spacing() {
    // Without a document grid, paragraphs still use Word's hhea single-line
    // pitch instead of Typst's glyph-tight default (issue #354).
    let doc = make_doc(vec![make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle::default(),
        runs: vec![Run {
            text: "plain".to_string(),
            style: TextStyle {
                font_family: Some("Libertinus Serif".to_string()),
                font_size: Some(10.0),
                ..TextStyle::default()
            },
            href: None,
            footnote: None,
        }],
    })])]);
    let result = generate_typst(&doc).unwrap().source;
    let Some((ascender, descender, word_pitch)) =
        crate::render::pdf::font_line_metrics_em("Libertinus Serif")
    else {
        return;
    };
    let single_pt: f64 = (word_pitch * 10.0).max((ascender + descender) * 10.0);
    assert_line_advance(&result, "Libertinus Serif", 10.0, single_pt, 0.0);
    assert!(
        result.contains("leading: 0pt"),
        "the advance is carried by the box, not by leading: {result}"
    );
}

#[test]
fn test_generate_paragraph_with_background_shading() {
    // w:pPr/w:shd paints the whole paragraph; the block wrapper must carry
    // the fill so the shading spans the full line width (issue #351).
    let doc = make_doc(vec![make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle {
            background: Some(Color::new(0xF4, 0xF4, 0xF4)),
            ..ParagraphStyle::default()
        },
        runs: vec![Run {
            text: "$ cargo install office2pdf-cli".to_string(),
            style: TextStyle::default(),
            href: None,
            footnote: None,
        }],
    })])]);
    let result = generate_typst(&doc).unwrap().source;
    assert!(
        result.contains("fill: rgb(244, 244, 244)"),
        "paragraph shading must fill the block wrapper: {result}"
    );
    assert!(
        result.contains("#block(width: 100%"),
        "shaded paragraphs need the full-width block wrapper: {result}"
    );
}

#[test]
fn test_generate_paragraph_with_bottom_border_rule() {
    // w:pBdr bottom rules (resume header underline) must stroke the block
    // wrapper's bottom edge (issue #368).
    let doc = make_doc(vec![make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle {
            border: Some(Box::new(CellBorder {
                bottom: Some(BorderSide {
                    width: 0.75,
                    color: Color::new(0x1E, 0x27, 0x61),
                    style: BorderLineStyle::Solid,
                }),
                ..CellBorder::default()
            })),
            ..ParagraphStyle::default()
        },
        runs: vec![Run {
            text: "JAMIE PARKER".to_string(),
            style: TextStyle::default(),
            href: None,
            footnote: None,
        }],
    })])]);
    let result = generate_typst(&doc).unwrap().source;
    assert!(
        result.contains("stroke: (bottom: 0.75pt + rgb(30, 39, 97))"),
        "bottom border must stroke the wrapper: {result}"
    );
}

#[test]
fn test_generate_paragraph_with_double_bottom_border() {
    // Double letterhead rules render as two placed hairlines; Typst strokes
    // have no double style (issue #368).
    let doc = make_doc(vec![make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle {
            border: Some(Box::new(CellBorder {
                bottom: Some(BorderSide {
                    width: 1.0,
                    color: Color::black(),
                    style: BorderLineStyle::Double,
                }),
                ..CellBorder::default()
            })),
            ..ParagraphStyle::default()
        },
        runs: vec![Run {
            text: "주식회사 에이엑스솔루션".to_string(),
            style: TextStyle::default(),
            href: None,
            footnote: None,
        }],
    })])]);
    let result = generate_typst(&doc).unwrap().source;
    let rule_count = result.matches("line(length: 100%").count();
    assert_eq!(
        rule_count, 2,
        "double borders draw exactly two rules: {result}"
    );
    assert!(
        !result.contains("stroke: (bottom:"),
        "double sides must not also stroke the wrapper: {result}"
    );
}

fn make_tab_paragraph() -> Block {
    Block::Paragraph(Paragraph {
        style: ParagraphStyle::default(),
        runs: vec![Run {
            text: "제1조\t(목적) 본문".to_string(),
            style: TextStyle::default(),
            href: None,
            footnote: None,
        }],
    })
}

#[test]
fn test_tab_advance_uses_document_default_tab_stop() {
    // Word documents carry w:defaultTabStop; tabs advance to multiples of
    // it, not the ECMA fallback (issue #393).
    let mut doc = make_doc(vec![make_flow_page(vec![make_tab_paragraph()])]);
    doc.styles.default_tab_stop_pt = Some(40.0);
    let result = generate_typst(&doc).unwrap().source;
    assert!(
        result.contains("calc.rem-euclid(tab_prefix_width_1.abs.pt(), 40)"),
        "explicit default tab stop must drive the advance: {result}"
    );
}

#[test]
fn test_tab_advance_defaults_to_40pt_under_document_grid() {
    // When settings.xml omits w:defaultTabStop, East Asian Word (signalled
    // by the section's w:docGrid) falls back to 800 twips = 40pt, not the
    // ECMA 720 twips (issue #393).
    let mut page = match make_flow_page(vec![make_tab_paragraph()]) {
        Page::Flow(flow) => flow,
        _ => unreachable!(),
    };
    page.line_grid_pitch = Some(18.0);
    page.line_grid_snaps_lines = true;
    let doc = make_doc(vec![Page::Flow(page)]);
    let result = generate_typst(&doc).unwrap().source;
    assert!(
        result.contains("calc.rem-euclid(tab_prefix_width_1.abs.pt(), 40)"),
        "grid documents default to 40pt tab stops: {result}"
    );
}

#[test]
fn test_tab_advance_defaults_to_36pt_without_grid() {
    let doc = make_doc(vec![make_flow_page(vec![make_tab_paragraph()])]);
    let result = generate_typst(&doc).unwrap().source;
    assert!(
        result.contains("calc.rem-euclid(tab_prefix_width_1.abs.pt(), 36)"),
        "ECMA default stays 36pt: {result}"
    );
}

#[test]
fn test_latin_paragraph_space_after_stays_raw_gap() {
    // Word places `w:spacing w:after` directly below the full line box,
    // which the paragraph's own line box already spans, so the gap reaches
    // the block unchanged and needs no leading top-up (issues #394, #452).
    let make_para = |text: &str| {
        Block::Paragraph(Paragraph {
            style: ParagraphStyle {
                space_after: Some(4.0),
                ..ParagraphStyle::default()
            },
            runs: vec![Run {
                text: text.to_string(),
                style: TextStyle {
                    font_family: Some("Libertinus Serif".to_string()),
                    font_size: Some(10.0),
                    ..TextStyle::default()
                },
                href: None,
                footnote: None,
            }],
        })
    };
    let doc = make_doc(vec![make_flow_page(vec![
        make_para("first paragraph"),
        make_para("second paragraph"),
    ])]);
    let result = generate_typst(&doc).unwrap().source;

    assert!(
        result.contains("below: 4pt"),
        "Latin paragraph keeps the raw 4pt gap: {result}"
    );
}

#[test]
fn test_consecutive_paragraphs_each_advance_by_the_full_font_line() {
    // The shaded command lines of a technical manual are separate 9pt
    // Courier New paragraphs with `w:spacing w:after="0"`. Word advances
    // each by the font's full single-spacing line; Typst only inserts
    // `par(leading:)` *between* the lines of one paragraph, so recovering
    // the advance that way left every paragraph one leading short and
    // consecutive command lines packed 28% tighter than Word (issue #452).
    // The line box must therefore span the whole advance on its own.
    let Some(advance_pt) = single_spacing_advance_pt(LINE_GAP_FONT, 9.0) else {
        return;
    };
    let make_code_line = |text: &str| {
        Block::Paragraph(Paragraph {
            style: ParagraphStyle {
                space_after: Some(0.0),
                ..ParagraphStyle::default()
            },
            runs: vec![Run {
                text: text.to_string(),
                style: TextStyle {
                    font_family: Some(LINE_GAP_FONT.to_string()),
                    font_size: Some(9.0),
                    ..TextStyle::default()
                },
                href: None,
                footnote: None,
            }],
        })
    };
    let doc = make_doc(vec![make_flow_page(vec![
        make_code_line("$ cargo install office2pdf-cli"),
        make_code_line("$ office2pdf --version"),
    ])]);
    let result = generate_typst(&doc).unwrap().source;

    assert_line_advance(&result, LINE_GAP_FONT, 9.0, advance_pt, 0.0);
    assert!(
        result.contains("leading: 0pt"),
        "the advance belongs to the box, not to leading: {result}"
    );
    assert!(
        result.contains("below: 0pt"),
        "a zero w:spacing w:after stays zero: {result}"
    );
}

/// A Typst-embedded font whose hhea line is taller than its typographic
/// metric box, so the single-spacing advance is strictly larger than the
/// metric box. Libertinus Serif - the default test font here - has no line
/// gap at all, which would make the assertions above pass vacuously.
const LINE_GAP_FONT: &str = "DejaVu Sans Mono";

/// Word's single-spacing advance for `family` at `font_size`, or `None`
/// when the font is unavailable or its hhea line adds no gap over the
/// typographic metric box (which would make the assertion vacuous).
fn single_spacing_advance_pt(family: &str, font_size: f64) -> Option<f64> {
    let (ascender, descender, word_pitch) = crate::render::pdf::font_line_metrics_em(family)?;
    (word_pitch - (ascender + descender) > 0.001).then_some(word_pitch * font_size)
}

#[test]
fn test_grid_paragraph_space_after_stays_raw_gap() {
    // Grid variant: the snapped line box already spans the full grid pitch,
    // so Word's after-gap sits directly below it and reaches the block
    // unchanged (issues #394, #452).
    if crate::render::pdf::font_line_metrics_em("Libertinus Serif").is_none() {
        return;
    }
    let mut page = match make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle {
            space_after: Some(4.0),
            ..ParagraphStyle::default()
        },
        runs: vec![Run {
            text: "그리드 본문".to_string(),
            style: TextStyle {
                font_family: Some("Libertinus Serif".to_string()),
                font_size: Some(10.0),
                ..TextStyle::default()
            },
            href: None,
            footnote: None,
        }],
    })]) {
        Page::Flow(flow) => flow,
        _ => unreachable!(),
    };
    page.line_grid_pitch = Some(18.0);
    page.line_grid_snaps_lines = true;
    let doc = make_doc(vec![Page::Flow(page)]);
    let result = generate_typst(&doc).unwrap().source;

    assert!(
        result.contains("below: 4pt"),
        "grid paragraph keeps the raw 4pt gap: {result}"
    );
}

#[test]
fn test_paragraph_left_indent_offsets_the_text_column() {
    // Word's `w:ind w:left` moves the whole paragraph right; only the list
    // path ever read it, so indented body paragraphs started at the margin
    // (issue #464).
    let doc = make_doc(vec![make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle {
            indent_left: Some(12.0),
            ..ParagraphStyle::default()
        },
        runs: vec![Run {
            text: "$ cargo install office2pdf-cli".to_string(),
            style: TextStyle::default(),
            href: None,
            footnote: None,
        }],
    })])]);
    let result = generate_typst(&doc).unwrap().source;

    assert!(
        result.contains("inset: (left: 12pt, right: 0pt)"),
        "left indent should inset the paragraph block: {result}"
    );
}

#[test]
fn test_paragraph_right_indent_narrows_the_text_column() {
    let doc = make_doc(vec![make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle {
            indent_right: Some(18.0),
            ..ParagraphStyle::default()
        },
        runs: vec![Run {
            text: "narrowed".to_string(),
            style: TextStyle::default(),
            href: None,
            footnote: None,
        }],
    })])]);
    let result = generate_typst(&doc).unwrap().source;

    assert!(
        result.contains("inset: (left: 0pt, right: 18pt)"),
        "right indent should inset the paragraph block: {result}"
    );
}

#[test]
fn test_indented_paragraph_shading_starts_at_the_indent() {
    // Word paints `w:pPr/w:shd` from the left indent to the right indent,
    // not across the whole text column: measured on a Word export, the
    // shaded band of a 12pt-indented code line starts at the indent, 12pt
    // right of the margin (issue #464). The fill therefore belongs to an
    // inner block that spans only the inset content area.
    let doc = make_doc(vec![make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle {
            indent_left: Some(12.0),
            background: Some(Color::new(0xF4, 0xF4, 0xF4)),
            ..ParagraphStyle::default()
        },
        runs: vec![Run {
            text: "$ office2pdf --version".to_string(),
            style: TextStyle::default(),
            href: None,
            footnote: None,
        }],
    })])]);
    let result = generate_typst(&doc).unwrap().source;

    let inset_at = result
        .find("inset: (left: 12pt, right: 0pt)")
        .expect("indent should inset the outer block");
    let fill_at = result
        .find("fill: rgb(244, 244, 244)")
        .expect("shading should still be emitted");
    assert!(
        fill_at > inset_at,
        "the fill belongs to a block nested inside the indent: {result}"
    );
}

#[test]
fn test_unindented_paragraph_keeps_a_single_block() {
    // A paragraph with no indent must not gain an inset or a nested block.
    let doc = make_doc(vec![make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle {
            background: Some(Color::new(0xF4, 0xF4, 0xF4)),
            ..ParagraphStyle::default()
        },
        runs: vec![Run {
            text: "flush left".to_string(),
            style: TextStyle::default(),
            href: None,
            footnote: None,
        }],
    })])]);
    let result = generate_typst(&doc).unwrap().source;

    assert!(
        !result.contains("inset: (left:"),
        "an unindented paragraph needs no inset: {result}"
    );
    assert!(
        result.contains("fill: rgb(244, 244, 244)"),
        "shading is still emitted: {result}"
    );
}

#[test]
fn test_empty_indented_paragraph_closes_its_block() {
    // An indented paragraph with no runs takes the early-return path. Leaving
    // its indent wrapper open produced "unclosed delimiter" and failed 73
    // third-party fixtures outright (regression caught on #464).
    let doc = make_doc(vec![make_flow_page(vec![
        Block::Paragraph(Paragraph {
            style: ParagraphStyle {
                indent_left: Some(24.0),
                ..ParagraphStyle::default()
            },
            runs: Vec::new(),
        }),
        make_paragraph("after the empty paragraph"),
    ])]);
    let result = generate_typst(&doc).unwrap().source;

    let opened: usize = result.matches('[').count();
    let closed: usize = result.matches(']').count();
    assert_eq!(
        opened, closed,
        "every content block opened must be closed: {result}"
    );
    assert!(
        result.contains("after the empty paragraph"),
        "the following paragraph must not be swallowed: {result}"
    );
}

/// One paragraph of `text` in `family` at `font_size`, with no grid.
fn line_box_for_text(text: &str, family: &str, font_size: f64) -> Option<(f64, f64)> {
    crate::render::pdf::font_line_metrics_em(family)?;
    let doc = make_doc(vec![make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle::default(),
        runs: vec![Run {
            text: text.to_string(),
            style: TextStyle {
                font_family: Some(family.to_string()),
                font_size: Some(font_size),
                ..TextStyle::default()
            },
            href: None,
            footnote: None,
        }],
    })])]);
    emitted_line_box_em(&generate_typst(&doc).unwrap().source)
}

#[test]
fn east_asian_line_advances_130_percent_of_the_font_line() {
    // Word gives a line carrying East Asian text 130% of the font's own hhea
    // line. Measured across the business corpus: 10.5pt Malgun Gothic paces its
    // wrapped lines at 18.00-18.24pt against 18.156 predicted, and
    // 06_official_letter_ko's 9.5pt paragraphs advance 16.43pt where the bare
    // hhea line is 12.64pt (issue #518).
    let Some((ascender, descender, word_pitch_em)) =
        crate::render::pdf::font_line_metrics_em("Libertinus Serif")
    else {
        return; // no font book available (e.g. exotic CI sandbox)
    };
    let _ = (ascender, descender);
    let Some((top, bottom)) = line_box_for_text("본문 한 줄", "Libertinus Serif", 10.0) else {
        return;
    };

    assert!(
        (top + bottom - 1.3 * word_pitch_em).abs() < 0.001,
        "East Asian advance {}em should be 1.3 x the {word_pitch_em}em hhea line",
        top + bottom
    );
}

#[test]
fn east_asian_bonus_is_centred_on_the_baseline() {
    // Half of the 30% lands above the baseline and half below: an Arial first
    // baseline sits at `hhea ascender + lineGap` while a Malgun Gothic one at
    // the same settings sits 0.15 x pitch lower, and the descent gap grows by
    // the same amount (issue #518).
    let Some((ascender, _descender, word_pitch_em)) =
        crate::render::pdf::font_line_metrics_em("Libertinus Serif")
    else {
        return;
    };
    let Some((top, bottom)) = line_box_for_text("본문 한 줄", "Libertinus Serif", 10.0) else {
        return;
    };

    assert!(
        (top - (ascender + 0.15 * word_pitch_em)).abs() < 0.001,
        "the baseline should sit 0.15 x pitch below the Latin seat, got {top}em"
    );
    assert!(
        (bottom - (word_pitch_em - ascender + 0.15 * word_pitch_em)).abs() < 0.001,
        "the other half of the bonus belongs below the baseline, got {bottom}em"
    );
}

#[test]
fn a_latin_line_keeps_the_plain_hhea_line_and_seat() {
    // Triangulation for both rules above: the bonus is a property of the
    // line's script, not of the renderer. Inflating Latin lines too made every
    // Western document 30-50% taller (issue #354).
    let Some((ascender, _descender, word_pitch_em)) =
        crate::render::pdf::font_line_metrics_em("Libertinus Serif")
    else {
        return;
    };
    let Some((top, bottom)) = line_box_for_text("plain body text", "Libertinus Serif", 10.0) else {
        return;
    };

    assert!(
        (top + bottom - word_pitch_em).abs() < 0.001,
        "a Latin line advances the bare hhea line, got {}em",
        top + bottom
    );
    assert!(
        (top - ascender).abs() < 0.001,
        "a Latin baseline keeps the `hhea ascender + lineGap` seat, got {top}em"
    );
}

#[test]
fn the_east_asian_bonus_scales_with_the_font_size_not_with_the_text() {
    // The rule is a factor on the font's line, so doubling the size doubles
    // both edges exactly - a fake that returned one measured pair would not.
    let Some((small_top, small_bottom)) = line_box_for_text("", "Libertinus Serif", 9.0) else {
        return;
    };
    let (large_top, large_bottom) =
        line_box_for_text("전혀 다른 한국어 문장", "Libertinus Serif", 21.0)
            .expect("the same font resolves at any size");

    // The box is emitted in em, so the em split must be identical at both
    // sizes and for unrelated text.
    assert!(
        (small_top - large_top).abs() < 0.001 && (small_bottom - large_bottom).abs() < 0.001,
        "the split is a property of the font, not of the size or the text: \
         {small_top}/{small_bottom} vs {large_top}/{large_bottom}"
    );
}

/// One paragraph with a bottom rule of `style` at `width`pt and `space`pt of
/// `w:pBdr` gap.
fn bordered_paragraph_source(width: f64, style: BorderLineStyle, space: f64) -> String {
    let doc = make_doc(vec![make_flow_page(vec![Block::Paragraph(Paragraph {
        style: ParagraphStyle {
            border: Some(Box::new(CellBorder {
                bottom: Some(BorderSide {
                    width,
                    color: Color::black(),
                    style,
                }),
                ..CellBorder::default()
            })),
            border_space: Some(Box::new(Insets {
                top: 0.0,
                right: 0.0,
                bottom: space,
                left: 0.0,
            })),
            ..ParagraphStyle::default()
        },
        runs: vec![Run {
            text: "서울특별시 강남구".to_string(),
            style: TextStyle::default(),
            href: None,
            footnote: None,
        }],
    })])]);
    generate_typst(&doc).unwrap().source
}

#[test]
fn a_paragraph_rule_reserves_its_own_declared_space() {
    // `w:pBdr` carries `w:space` per side, in points. A fixed 4pt stood in for
    // it until #520, which displaced every line below a bordered paragraph by
    // the difference — 06_official_letter_ko declares 8pt and lost 4pt of it,
    // as a step that survived to the bottom of the page.
    let source = bordered_paragraph_source(0.75, BorderLineStyle::Solid, 8.0);

    assert!(
        source.contains("inset: (bottom: 8.75pt)"),
        "the rule reserves its declared 8pt plus its own 0.75pt width: {source}"
    );
}

#[test]
fn a_rule_that_declares_no_space_sits_against_the_text() {
    // Triangulation, and the attribute's own default: `w:space` omitted means
    // zero, not a house value.
    let source = bordered_paragraph_source(0.75, BorderLineStyle::Solid, 0.0);

    assert!(
        source.contains("inset: (bottom: 0.75pt)"),
        "with no declared space only the rule's width is reserved: {source}"
    );
}

#[test]
fn a_double_rule_reserves_its_space_plus_all_three_widths() {
    // A Word double rule is two lines of the declared width separated by a gap
    // of the same width, and it is drawn as two placed hairlines because Typst
    // strokes have no double style. Both the reserved height and the placement
    // of each hairline hang off the declared space (issue #520).
    let source = bordered_paragraph_source(1.0, BorderLineStyle::Double, 8.0);

    assert!(
        source.contains("inset: (bottom: 11pt)"),
        "8pt of space plus three 1pt widths: {source}"
    );
    assert!(
        source.contains("#place(bottom, dy: 9pt,") && source.contains("#place(bottom, dy: 11pt,"),
        "both hairlines are placed from the declared space: {source}"
    );
    assert!(
        !source.contains("stroke: (bottom:"),
        "a double rule is drawn as overlays, not as a block stroke: {source}"
    );
}

#[test]
fn every_declared_space_reaches_the_output_unchanged() {
    // Triangulation across values, so no single measured constant can pass.
    for (space, expected) in [
        (0.0, "0.75pt"),
        (2.0, "2.75pt"),
        (8.0, "8.75pt"),
        (14.0, "14.75pt"),
    ] {
        let source = bordered_paragraph_source(0.75, BorderLineStyle::Solid, space);
        assert!(
            source.contains(&format!("inset: (bottom: {expected})")),
            "{space}pt of declared space should reserve {expected}: {source}"
        );
    }
}