rootcause 0.12.1

A flexible, ergonomic, and inspectable error reporting library for 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
//! Default report formatter implementation for the rootcause error handling
//! library.
//!
//! This module provides [`DefaultReportFormatter`], a comprehensive and
//! configurable report formatter that handles the visual presentation of error
//! reports with hierarchical structures, attachments, and appendices.
//!
//! The formatter supports multiple output styles:
//! - **Unicode only** ([`DefaultReportFormatter::UNICODE`]) - Unicode
//!   box-drawing characters without ANSI colors (the default)
//! - **Unicode with ANSI colors** ([`DefaultReportFormatter::UNICODE_COLORS`])
//!   - Rich visual experience for modern terminals
//! - **ASCII-only** ([`DefaultReportFormatter::ASCII`]) - Compatible with basic
//!   terminals and text-only outputs
//!
//! # Usage
//!
//! This formatter is the one used by default when no other formatter is
//! installed. It is also possible to explicitly install it:
//!
//! ```
//! use rootcause::hooks::{Hooks, builtin_hooks::report_formatter::DefaultReportFormatter};
//!
//! // Use the default Unicode configuration (no colors)
//! Hooks::new()
//!     .report_formatter(DefaultReportFormatter::default())
//!     .install()
//!     .ok();
//!
//! // Or use Unicode with ANSI colors for enhanced visuals
//! Hooks::new()
//!     .report_formatter(DefaultReportFormatter::UNICODE_COLORS)
//!     .install()
//!     .ok();
//!
//! // Or use ASCII-only for compatibility
//! Hooks::new()
//!     .report_formatter(DefaultReportFormatter::ASCII)
//!     .install()
//!     .ok();
//! ```
//!
//! # Configuration Structures
//!
//! The formatter uses a hierarchy of configuration structures:
//! - [`LineFormatting`] - Basic line prefix/suffix formatting
//! - [`ItemFormatting`] - Multi-line item formatting with different rules for
//!   first/middle/last lines
//! - [`NodeConfig`] - Hierarchical node formatting with header and child
//!   indentation
//! - [`DefaultReportFormatter`] - Main configuration struct combining all
//!   formatting options

use alloc::{
    string::{String, ToString},
    vec::Vec,
};
use core::fmt::{self, Formatter, Write};

use indexmap::IndexMap;
use rootcause_internals::handlers::{
    AttachmentFormattingPlacement, AttachmentFormattingStyle, FormattingFunction,
};

use crate::{
    ReportRef,
    hooks::report_formatter::ReportFormatter,
    markers::{Dynamic, Local, Uncloneable},
    report_attachment::ReportAttachmentRef,
};

/// The default report formatter implementation that provides comprehensive
/// formatting for error reports with configurable styling and layout options.
///
/// This formatter supports both ASCII-only output (suitable for environments
/// without Unicode or ANSI support) and Unicode output with ANSI color codes
/// for enhanced visual presentation. It handles hierarchical report structures
/// with contexts, attachments, and appendices.
///
/// # Examples
///
/// Basic usage with default formatting:
/// ```
/// use rootcause::hooks::{Hooks, builtin_hooks::report_formatter::DefaultReportFormatter};
///
/// Hooks::new()
///     .report_formatter(DefaultReportFormatter::default())
///     .install()
///     .ok();
/// // Use with report formatting system (Unicode without colors)
/// ```
///
/// Using Unicode with ANSI colors for enhanced visuals:
/// ```
/// use rootcause::hooks::{Hooks, builtin_hooks::report_formatter::DefaultReportFormatter};
///
/// Hooks::new()
///     .report_formatter(DefaultReportFormatter::UNICODE_COLORS)
///     .install()
///     .ok();
/// // Use in modern terminals that support ANSI colors
/// ```
///
/// Using ASCII-only formatting for compatibility:
/// ```
/// use rootcause::hooks::{Hooks, builtin_hooks::report_formatter::DefaultReportFormatter};
///
/// Hooks::new()
///     .report_formatter(DefaultReportFormatter::ASCII)
///     .install()
///     .ok();
/// // Use in environments without Unicode/ANSI support
/// ```
#[derive(Debug)]
pub struct DefaultReportFormatter {
    /// Header text displayed at the beginning of report output
    pub report_header: &'static str,

    /// Prefix applied to every line of report content
    pub report_line_prefix_always: &'static str,

    /// Prefix applied to every line of appendix content
    pub appendix_line_prefix_always: &'static str,

    /// Formatting configuration for standalone report nodes, i.e. those without
    /// siblings
    pub report_node_standalone_formatting: NodeConfig,

    /// Formatting configuration for report nodes that have siblings below them
    pub report_node_middle_formatting: NodeConfig,

    /// Formatting configuration for the last report node in a sequence of more
    /// than one sibling
    pub report_node_last_formatting: NodeConfig,

    /// Formatting configuration for attachment items that output in [`Inline`]
    /// mode and have more data below them from the same report node
    ///
    /// [`Inline`]: AttachmentFormattingPlacement::Inline
    pub attachment_inline_formatting_middle: ItemFormatting,

    /// Formatting configuration for attachment items that output in [`Inline`]
    /// mode and are the last piece of data for the report node
    ///
    /// [`Inline`]: AttachmentFormattingPlacement::Inline
    pub attachment_inline_formatting_last: ItemFormatting,

    /// Formatting configuration for attachment items that output in
    /// [`InlineWithHeader`] mode and have more data below them from the
    /// same report node
    ///
    /// [`InlineWithHeader`]: AttachmentFormattingPlacement::InlineWithHeader
    pub attachment_headered_formatting_middle: NodeConfig,

    /// Formatting configuration for attachment items that output in
    /// [`InlineWithHeader`] mode and are the last piece of data for the
    /// report node
    ///
    /// [`InlineWithHeader`]: AttachmentFormattingPlacement::InlineWithHeader
    pub attachment_headered_formatting_last: NodeConfig,

    /// Formatting configuration for the data of the attachments that output in
    /// [`InlineWithHeader`] mode.
    ///
    /// [`InlineWithHeader`]: AttachmentFormattingPlacement::InlineWithHeader
    pub attachment_headered_formatting_data: ItemFormatting,

    /// Optional prefix text for the data of the attachments that output in
    /// [`InlineWithHeader`] mode.
    ///
    /// [`InlineWithHeader`]: AttachmentFormattingPlacement::InlineWithHeader
    pub attachment_headered_data_prefix: Option<&'static str>,

    /// Optional suffix text for the data of the attachments that output in
    /// [`InlineWithHeader`] mode.
    ///
    /// [`InlineWithHeader`]: AttachmentFormattingPlacement::InlineWithHeader
    pub attachment_headered_data_suffix: Option<&'static str>,

    /// The formatting for the "see also" notice when this notice *is not* the
    /// last piece of data to render for the report node.
    ///
    /// The "see also" notice occur when an attachment item outputs in
    /// [`Appendix`] mode.
    ///
    /// [`Appendix`]: AttachmentFormattingPlacement::Appendix
    pub notice_see_also_middle_formatting: LineFormatting,

    /// The formatting for the "see also" notice when this notice *is* the last
    /// piece of data to render for the report node.
    ///
    /// The "see also" notice occur when an attachment item outputs in
    /// [`Appendix`] mode.
    ///
    /// [`Appendix`]: AttachmentFormattingPlacement::Appendix
    pub notice_see_also_last_formatting: LineFormatting,

    /// The formatting for the `N additional opaque attachments` notice when
    /// this notice *is not* the last piece of data to render for the report
    /// node.
    ///
    /// This notice occurs when one or more attachment items output in
    /// [`Opaque`] mode.
    ///
    /// [`Opaque`]: AttachmentFormattingPlacement::Opaque
    pub notice_opaque_middle_formatting: LineFormatting,

    /// The formatting for the `N additional opaque attachments` notice when
    /// this notice *is* the last piece of data to render for the report
    /// node.
    ///
    /// This notice occurs when one or more attachment items output in
    /// [`Opaque`] mode.
    ///
    /// [`Opaque`]: AttachmentFormattingPlacement::Opaque
    pub notice_opaque_last_formatting: LineFormatting,

    /// Optional separator inserted before child contexts
    pub pre_child_separator: Option<&'static str>,

    /// Optional separator inserted between sibling child contexts
    pub child_child_separator: Option<&'static str>,

    /// Formatting for the "Following the error chain" header when it's not the
    /// last piece of data for the report node
    pub source_chain_header_middle_formatting: NodeConfig,

    /// Formatting for the "Following the error chain" header when it's the
    /// last piece of data for the report node
    pub source_chain_header_last_formatting: NodeConfig,

    /// Formatting for individual source chain items that are not the last item
    pub source_chain_item_middle_formatting: ItemFormatting,

    /// Formatting for the last source chain item
    pub source_chain_item_last_formatting: ItemFormatting,

    /// Formatting for the notice when source chain errors are omitted due to
    /// depth limit
    pub source_chain_omitted_formatting: LineFormatting,

    /// Optional separator between the source chain and attachments/children
    pub source_chain_separator: Option<&'static str>,

    /// Separator text inserted between multiple reports
    pub report_report_separator: &'static str,

    /// Separator text inserted between report content and appendices
    pub report_appendix_separator: &'static str,

    /// Separator text inserted between multiple appendices
    pub appendix_appendix_separator: &'static str,

    /// Formatting configuration for appendix headers
    pub appendix_header: LineFormatting,

    /// Formatting configuration for appendix body content
    pub appendix_body: ItemFormatting,

    /// Footer text displayed after all appendices
    pub appendices_footer: &'static str,

    /// Footer text displayed when there are no appendices
    pub no_appendices_footer: &'static str,
}

impl DefaultReportFormatter {
    /// A predefined configuration that uses only ASCII characters without ANSI
    /// color codes.
    ///
    /// This configuration is suitable for environments that don't support
    /// Unicode characters or ANSI color codes, such as basic terminals, log
    /// files, or text-only outputs. Uses simple ASCII box-drawing
    /// alternatives like `|-`, `o`, and `--`.
    ///
    /// # Examples
    ///
    /// ```
    /// use rootcause::hooks::{Hooks, builtin_hooks::report_formatter::DefaultReportFormatter};
    ///
    /// // Use ASCII-only formatting
    /// Hooks::new()
    ///     .report_formatter(DefaultReportFormatter::ASCII)
    ///     .install()
    ///     .ok();
    /// ```
    pub const ASCII: Self = Self {
        report_header: "\n",
        report_line_prefix_always: "",
        appendix_line_prefix_always: "",
        report_node_standalone_formatting: NodeConfig::new(
            ("o  ", "\n"),
            ("o  ", "\n"),
            ("|  ", "\n"),
            ("|  ", "\n"),
            "",
        ),
        report_node_middle_formatting: NodeConfig::new(
            ("|--> o  ", "\n"),
            ("|--> o  ", "\n"),
            ("|    |  ", "\n"),
            ("|    |  ", "\n"),
            "|    ",
        ),
        report_node_last_formatting: NodeConfig::new(
            (r"|--> o  ", "\n"),
            (r"|--> o  ", "\n"),
            ("     |  ", "\n"),
            ("     |  ", "\n"),
            "     ",
        ),
        attachment_inline_formatting_middle: ItemFormatting::new(
            ("|- ", "\n"),
            ("|- ", "\n"),
            ("|  ", "\n"),
            ("|  ", "\n"),
        ),
        attachment_inline_formatting_last: ItemFormatting::new(
            (r"|- ", "\n"),
            (r"|- ", "\n"),
            ("   ", "\n"),
            ("   ", "\n"),
        ),
        attachment_headered_formatting_middle: NodeConfig::new(
            (r"|- ", "\n"),
            ("|- ", "\n"),
            ("|  ", "\n"),
            ("|  ", "\n"),
            "| ",
        ),
        attachment_headered_formatting_last: NodeConfig::new(
            (r"|- ", "\n"),
            (r"|- ", "\n"),
            ("  ", "\n"),
            ("  ", "\n"),
            "  ",
        ),
        attachment_headered_formatting_data: ItemFormatting::new(
            (r"|- ", "\n"),
            ("|- ", "\n"),
            ("|- ", "\n"),
            (r"|- ", "\n"),
        ),
        attachment_headered_data_prefix: None,
        attachment_headered_data_suffix: None,
        notice_see_also_middle_formatting: LineFormatting::new("|- See ", " below\n"),
        notice_see_also_last_formatting: LineFormatting::new(r"|- See ", " below\n"),
        notice_opaque_middle_formatting: LineFormatting::new("|- ", "\n"),
        notice_opaque_last_formatting: LineFormatting::new(r"|- ", "\n"),
        pre_child_separator: None,
        child_child_separator: None,
        source_chain_header_middle_formatting: NodeConfig::new(
            ("| > ", "\n"),
            ("| > ", "\n"),
            ("|   ", "\n"),
            ("|   ", "\n"),
            "|   ",
        ),
        source_chain_header_last_formatting: NodeConfig::new(
            ("  > ", "\n"),
            ("  > ", "\n"),
            ("    ", "\n"),
            ("    ", "\n"),
            "    ",
        ),
        source_chain_item_middle_formatting: ItemFormatting::new(
            ("|- ", "\n"),
            ("|- ", "\n"),
            ("|  ", "\n"),
            ("|  ", "\n"),
        ),
        source_chain_item_last_formatting: ItemFormatting::new(
            (r"|- ", "\n"),
            (r"|- ", "\n"),
            ("   ", "\n"),
            ("   ", "\n"),
        ),
        source_chain_omitted_formatting: LineFormatting::new("|- note: ", "\n"),
        source_chain_separator: None,
        report_report_separator: "--\n",
        report_appendix_separator: "----------------------------------------\n",
        appendix_appendix_separator: "----------------------------------------\n",
        appendix_header: LineFormatting::new(" ", "\n\n"),
        appendix_body: ItemFormatting::new((" ", "\n"), (" ", "\n"), (" ", "\n"), (" ", "\n")),
        appendices_footer: "----------------------------------------\n",
        no_appendices_footer: "",
    };
    /// The default formatter configuration, which is an alias for
    /// [`UNICODE`](Self::UNICODE).
    ///
    /// This provides Unicode box-drawing characters without ANSI colors,
    /// offering a good balance between visual clarity and compatibility.
    pub const DEFAULT: Self = Self::UNICODE;
    /// A predefined configuration that uses Unicode box-drawing characters
    /// without ANSI color codes.
    ///
    /// This is the default configuration. It provides clear visual hierarchy
    /// using Unicode box-drawing characters (like `├`, `╰`, `│`) without ANSI
    /// colors, making it suitable for environments that support Unicode but
    /// where colored output may not be desired (such as log files or CI
    /// environments).
    pub const UNICODE: Self = Self {
        report_header: "\n",
        report_line_prefix_always: " ",
        appendix_line_prefix_always: "",
        report_node_standalone_formatting: NodeConfig::new(
            ("", "\n"),
            ("", "\n"),
            ("", "\n"),
            ("", "\n"),
            "",
        ),
        report_node_middle_formatting: NodeConfig::new(
            ("├─ ● ", "\n"),
            ("├─ ● ", "\n"),
            ("│  │ ", "\n"),
            ("│  │ ", "\n"),
            "",
        ),
        report_node_last_formatting: NodeConfig::new(
            ("╰─ ● ", "\n"),
            ("╰─ ● ", "\n"),
            ("", "\n"),
            ("", "\n"),
            "   ",
        ),
        attachment_inline_formatting_middle: ItemFormatting::new(
            ("", "\n"),
            ("", "\n"),
            ("", "\n"),
            ("", "\n"),
        ),
        attachment_inline_formatting_last: ItemFormatting::new(
            ("", "\n"),
            ("", "\n"),
            ("  ", "\n"),
            ("  ", "\n"),
        ),
        attachment_headered_formatting_middle: NodeConfig::new(
            ("", "\n"),
            ("", "\n"),
            ("", "\n"),
            ("", "\n"),
            "",
        ),
        attachment_headered_formatting_last: NodeConfig::new(
            ("", "\n"),
            ("", "\n"),
            (" ", "\n"),
            (" ", "\n"),
            "  ",
        ),
        attachment_headered_formatting_data: ItemFormatting::new(
            ("", "\n"),
            ("", "\n"),
            ("", "\n"),
            ("", "\n"),
        ),
        attachment_headered_data_prefix: None,
        attachment_headered_data_suffix: Some("╰─\n"),
        notice_see_also_middle_formatting: LineFormatting::new("├ See ", " below\n"),
        notice_see_also_last_formatting: LineFormatting::new("╰ See ", " below\n"),
        notice_opaque_middle_formatting: LineFormatting::new("", "\n"),
        notice_opaque_last_formatting: LineFormatting::new("", "\n"),
        pre_child_separator: Some("\n"),
        child_child_separator: Some("\n"),
        source_chain_header_middle_formatting: NodeConfig::new(
            ("│ ╰ ", "\n"),
            ("│ ╰ ", "\n"),
            ("", "\n"),
            ("", "\n"),
            "",
        ),
        source_chain_header_last_formatting: NodeConfig::new(
            ("", "\n"),
            ("", "\n"),
            ("    ", "\n"),
            ("    ", "\n"),
            "    ",
        ),
        source_chain_item_middle_formatting: ItemFormatting::new(
            ("", "\n"),
            ("", "\n"),
            ("", "\n"),
            ("", "\n"),
        ),
        source_chain_item_last_formatting: ItemFormatting::new(
            ("", "\n"),
            ("", "\n"),
            ("  ", "\n"),
            ("  ", "\n"),
        ),
        source_chain_omitted_formatting: LineFormatting::new("│ note: ", "\n"),
        source_chain_separator: None,
        report_report_separator: "━━\n",
        report_appendix_separator: "\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n",
        appendix_appendix_separator: "\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n",
        appendix_header: LineFormatting::new(" ", "\n\n"),
        appendix_body: ItemFormatting::new((" ", "\n"), (" ", "\n"), (" ", "\n"), (" ", "\n")),
        appendices_footer: "\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n",
        no_appendices_footer: "",
    };
    /// A predefined configuration that uses Unicode box-drawing characters with
    /// ANSI color codes.
    ///
    /// This configuration provides the richest visual experience with Unicode
    /// box-drawing characters (like `├`, `╰`, `│`) and ANSI color codes for
    /// enhanced readability. Suitable for modern terminals and development
    /// environments.
    pub const UNICODE_COLORS: Self = Self {
        report_header: "\n",
        report_line_prefix_always: " ",
        appendix_line_prefix_always: "",
        report_node_standalone_formatting: NodeConfig::new(
            ("\x1b[97m● \x1b[1m", "\x1b[0m\n"),
            ("\x1b[97m● \x1b[1m", "\x1b[0m\n"),
            ("\x1b[1;97m", "\x1b[0m\n"),
            ("\x1b[1;97m", "\x1b[0m\n"),
            "",
        ),
        report_node_middle_formatting: NodeConfig::new(
            ("├─ \x1b[97m● \x1b[1m", "\x1b[0m\n"),
            ("├─ \x1b[97m● \x1b[1m", "\x1b[0m\n"),
            ("│  │ \x1b[1;97m", "\x1b[0m\n"),
            ("│  │ \x1b[1;97m", "\x1b[0m\n"),
            "",
        ),
        report_node_last_formatting: NodeConfig::new(
            ("╰─ \x1b[97m● \x1b[1m", "\x1b[0m\n"),
            ("╰─ \x1b[97m● \x1b[1m", "\x1b[0m\n"),
            ("\x1b[1;97m", "\x1b[0m\n"),
            ("\x1b[1;97m", "\x1b[0m\n"),
            "   ",
        ),
        attachment_inline_formatting_middle: ItemFormatting::new(
            ("", "\n"),
            ("", "\n"),
            ("", "\n"),
            ("", "\n"),
        ),
        attachment_inline_formatting_last: ItemFormatting::new(
            ("", "\n"),
            ("", "\n"),
            ("  ", "\n"),
            ("  ", "\n"),
        ),
        attachment_headered_formatting_middle: NodeConfig::new(
            ("\x1b[4m", "\x1b[0m\n"),
            ("\x1b[4m", "\x1b[0m\n"),
            ("\x1b[4m", "\x1b[0m\n"),
            ("\x1b[4m", "\x1b[0m\n"),
            "",
        ),
        attachment_headered_formatting_last: NodeConfig::new(
            ("\x1b[4m", "\x1b[0m\n"),
            ("\x1b[4m", "\x1b[0m\n"),
            (" \x1b[4m", "\x1b[0m\n"),
            (" \x1b[4m", "\x1b[0m\n"),
            "  ",
        ),
        attachment_headered_formatting_data: ItemFormatting::new(
            ("", "\n"),
            ("", "\n"),
            ("", "\n"),
            ("", "\n"),
        ),
        attachment_headered_data_prefix: None,
        attachment_headered_data_suffix: Some("╰─\n"),
        notice_see_also_middle_formatting: LineFormatting::new("├ See \x1b[4m", "\x1b[0m below\n"),
        notice_see_also_last_formatting: LineFormatting::new("╰ See \x1b[4m", "\x1b[0m below\n"),
        notice_opaque_middle_formatting: LineFormatting::new("", "\n"),
        notice_opaque_last_formatting: LineFormatting::new("", "\n"),
        pre_child_separator: Some("\n"),
        child_child_separator: Some("\n"),
        source_chain_header_middle_formatting: NodeConfig::new(
            ("│ ╰ ", "\n"),
            ("│ ╰ ", "\n"),
            ("", "\n"),
            ("", "\n"),
            "",
        ),
        source_chain_header_last_formatting: NodeConfig::new(
            ("", "\n"),
            ("", "\n"),
            ("    ", "\n"),
            ("    ", "\n"),
            "    ",
        ),
        source_chain_item_middle_formatting: ItemFormatting::new(
            ("", "\n"),
            ("", "\n"),
            ("", "\n"),
            ("", "\n"),
        ),
        source_chain_item_last_formatting: ItemFormatting::new(
            ("", "\n"),
            ("", "\n"),
            ("  ", "\n"),
            ("  ", "\n"),
        ),
        source_chain_omitted_formatting: LineFormatting::new("│ note: ", "\n"),
        source_chain_separator: None,
        report_report_separator: "━━\n",
        report_appendix_separator: "\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n",
        appendix_appendix_separator: "\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n",
        appendix_header: LineFormatting::new(" \x1b[4m", "\x1b[0m\n\n"),
        appendix_body: ItemFormatting::new((" ", "\n"), (" ", "\n"), (" ", "\n"), (" ", "\n")),
        appendices_footer: "\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n",
        no_appendices_footer: "",
    };
}

impl Default for DefaultReportFormatter {
    fn default() -> Self {
        Self::DEFAULT
    }
}

/// Configuration for formatting individual lines with prefix and suffix text.
///
/// This is the fundamental building block for all report formatting, allowing
/// each line to be decorated with consistent prefix and suffix strings that
/// can include tree characters, ANSI color codes, or other visual elements.
///
/// # Examples
///
/// Creating line formatting with tree characters:
/// ```
/// use rootcause::hooks::builtin_hooks::report_formatter::LineFormatting;
///
/// let formatting = LineFormatting::new("├─ ", "\n");
/// // This will format lines as: "├─ content\n"
/// ```
///
/// Creating line formatting with ANSI colors:
/// ```
/// use rootcause::hooks::builtin_hooks::report_formatter::LineFormatting;
///
/// let formatting = LineFormatting::new("\x1b[31m● ", "\x1b[0m\n");
/// // This will format lines as: "\x1b[31m● content\x1b[0m\n" (red bullet)
/// ```
#[derive(Copy, Clone, Debug)]
pub struct LineFormatting {
    /// Text prefix prepended to the beginning of each line
    pub prefix: &'static str,
    /// Text suffix appended to the end of each line
    pub suffix: &'static str,
}

impl LineFormatting {
    /// Creates a new line formatting configuration with the specified prefix
    /// and suffix.
    ///
    /// # Arguments
    ///
    /// * `prefix` - Text to prepend to each formatted line
    /// * `suffix` - Text to append to each formatted line
    ///
    /// # Examples
    ///
    /// ```
    /// use rootcause::hooks::builtin_hooks::report_formatter::LineFormatting;
    ///
    /// let formatting = LineFormatting::new("→ ", "\n");
    /// ```
    pub const fn new(prefix: &'static str, suffix: &'static str) -> Self {
        Self { prefix, suffix }
    }
}
/// Configuration for formatting items that may span multiple lines, with
/// different formatting rules based on the line's position within the item.
///
/// This allows for sophisticated formatting where the first, middle, and last
/// lines of multi-line content can have different prefixes and suffixes,
/// enabling tree-like structures and visual connection between related lines.
///
/// # Examples
///
/// Creating formatting for a tree structure:
/// ```
/// use rootcause::hooks::builtin_hooks::report_formatter::ItemFormatting;
///
/// let formatting = ItemFormatting::new(
///     ("● ", "\n"), // single line: "● content\n"
///     ("┌ ", "\n"), // first line:  "┌ first line\n"
///     ("│ ", "\n"), // middle line: "│ middle line\n"
///     ("└ ", "\n"), // last line:   "└ last line\n"
/// );
/// ```
#[derive(Copy, Clone, Debug)]
pub struct ItemFormatting {
    /// Formatting applied when the item consists of only one line
    pub standalone_line: LineFormatting,
    /// Formatting applied to the first line of a multi-line item
    pub first_line: LineFormatting,
    /// Formatting applied to middle lines of a multi-line item
    pub middle_line: LineFormatting,
    /// Formatting applied to the last line of a multi-line item
    pub last_line: LineFormatting,
}

impl ItemFormatting {
    /// Creates a new item formatting configuration with line-specific
    /// formatting rules.
    ///
    /// # Arguments
    ///
    /// * `standalone_line` - Prefix and suffix for single-line items: `(prefix,
    ///   suffix)`
    /// * `first_line` - Prefix and suffix for the first line of multi-line
    ///   items: `(prefix, suffix)`
    /// * `middle_line` - Prefix and suffix for middle lines of multi-line
    ///   items: `(prefix, suffix)`
    /// * `last_line` - Prefix and suffix for the last line of multi-line items:
    ///   `(prefix, suffix)`
    ///
    /// # Examples
    ///
    /// ```
    /// use rootcause::hooks::builtin_hooks::report_formatter::ItemFormatting;
    ///
    /// let formatting = ItemFormatting::new(
    ///     ("■ ", "\n"), // standalone: "■ content\n"
    ///     ("┌ ", "\n"), // first:      "┌ first line\n"
    ///     ("│ ", "\n"), // middle:     "│ middle line\n"
    ///     ("└ ", "\n"), // last:       "└ last line\n"
    /// );
    /// ```
    pub const fn new(
        standalone_line: (&'static str, &'static str),
        first_line: (&'static str, &'static str),
        middle_line: (&'static str, &'static str),
        last_line: (&'static str, &'static str),
    ) -> Self {
        Self {
            standalone_line: LineFormatting::new(standalone_line.0, standalone_line.1),
            first_line: LineFormatting::new(first_line.0, first_line.1),
            middle_line: LineFormatting::new(middle_line.0, middle_line.1),
            last_line: LineFormatting::new(last_line.0, last_line.1),
        }
    }
}

/// Configuration for formatting hierarchical nodes that contain both header
/// content and child elements with specific indentation.
///
/// A node represents a hierarchical element in the report structure, such as a
/// context or a headered attachment, that has both a header line and potential
/// child content that needs to be indented relative to the header.
///
/// # Examples
///
/// Creating a node configuration with tree-like formatting:
/// ```
/// use rootcause::hooks::builtin_hooks::report_formatter::{ItemFormatting, NodeConfig};
///
/// let config = NodeConfig::new(
///     ("● ", "\n"),  // standalone header
///     ("├─ ", "\n"), // first line of multi-line header
///     ("│  ", "\n"), // middle lines of multi-line header
///     ("╰─ ", "\n"), // last line of multi-line header
///     "   ",         // prefix for child content
/// );
/// ```
#[derive(Copy, Clone, Debug)]
pub struct NodeConfig {
    /// Formatting configuration for the node's header content
    pub header: ItemFormatting,
    /// Text prefix applied to all child content lines for proper indentation
    pub prefix_children: &'static str,
}

impl NodeConfig {
    /// Creates a new node configuration with header formatting and child
    /// indentation.
    ///
    /// # Arguments
    ///
    /// * `standalone_line` - Prefix and suffix for single-line headers:
    ///   `(prefix, suffix)`
    /// * `first_line` - Prefix and suffix for the first line of multi-line
    ///   headers: `(prefix, suffix)`
    /// * `middle_line` - Prefix and suffix for middle lines of multi-line
    ///   headers: `(prefix, suffix)`
    /// * `last_line` - Prefix and suffix for the last line of multi-line
    ///   headers: `(prefix, suffix)`
    /// * `prefix_children` - Text prefix applied to all child content for
    ///   proper indentation
    ///
    /// # Examples
    ///
    /// ```
    /// use rootcause::hooks::builtin_hooks::report_formatter::NodeConfig;
    ///
    /// let config = NodeConfig::new(
    ///     ("◆ ", "\n"), // standalone header
    ///     ("◆ ", "\n"), // first line of a multi-line header
    ///     ("│ ", "\n"), // middle lines of multi-line header
    ///     ("╰ ", "\n"), // last line of multi-line header
    ///     "  ",         // indent for children
    /// );
    /// ```
    pub const fn new(
        standalone_line: (&'static str, &'static str),
        first_line: (&'static str, &'static str),
        middle_line: (&'static str, &'static str),
        last_line: (&'static str, &'static str),
        prefix_children: &'static str,
    ) -> Self {
        Self {
            header: ItemFormatting::new(standalone_line, first_line, middle_line, last_line),
            prefix_children,
        }
    }
}
type Appendices<'a> = IndexMap<
    &'static str,
    Vec<(ReportAttachmentRef<'a, Dynamic>, FormattingFunction)>,
    rustc_hash::FxBuildHasher,
>;

struct DefaultFormatterState<'a, 'b> {
    config: &'a DefaultReportFormatter,
    appendices: Appendices<'a>,
    line_prefix: String,
    formatter: &'a mut Formatter<'b>,
    report_formatting_function: FormattingFunction,
}

impl ReportFormatter for DefaultReportFormatter {
    fn format_reports(
        &self,
        reports: &[ReportRef<'_, Dynamic, Uncloneable, Local>],
        formatter: &mut fmt::Formatter<'_>,
        report_formatting_function: FormattingFunction,
    ) -> fmt::Result {
        formatter.write_str(self.report_header)?;
        DefaultFormatterState::new(self, formatter, report_formatting_function)
            .format_reports(reports)
    }
}

type TmpValueBuffer = String;
type TmpAttachmentsBuffer<'a> = Vec<(AttachmentFormattingStyle, ReportAttachmentRef<'a, Dynamic>)>;

impl<'a, 'b> DefaultFormatterState<'a, 'b> {
    fn new(
        config: &'a DefaultReportFormatter,
        formatter: &'a mut Formatter<'b>,
        report_formatting_function: FormattingFunction,
    ) -> Self {
        Self {
            config,
            appendices: IndexMap::default(),
            line_prefix: String::new(),
            formatter,
            report_formatting_function,
        }
    }

    fn format_with_line_prefix(&mut self, line: &str) -> fmt::Result {
        self.formatter.write_str(&self.line_prefix)?;
        self.formatter.write_str(line)?;
        Ok(())
    }

    fn format_node(
        &mut self,
        tmp_value_buffer: &mut TmpValueBuffer,
        formatting: &NodeConfig,
        value: impl fmt::Display + fmt::Debug,
        function: FormattingFunction,
        children: impl FnOnce(&mut Self, &mut String) -> fmt::Result,
    ) -> fmt::Result {
        self.format_item(tmp_value_buffer, &formatting.header, value, function)?;

        let len_before = self.line_prefix.len();
        self.line_prefix.push_str(formatting.prefix_children);
        let result = children(self, tmp_value_buffer);
        self.line_prefix.truncate(len_before);
        result
    }

    fn format_item(
        &mut self,
        tmp_value_buffer: &mut TmpValueBuffer,
        formatting: &ItemFormatting,
        value: impl fmt::Display + fmt::Debug,
        function: FormattingFunction,
    ) -> fmt::Result {
        let mut is_first = true;
        tmp_value_buffer.clear();
        match function {
            FormattingFunction::Display => write!(tmp_value_buffer, "{value}")?,
            FormattingFunction::Debug => write!(tmp_value_buffer, "{value:?}")?,
        }

        let mut value_lines = tmp_value_buffer.trim_end().lines().peekable();
        while let Some(value_line) = value_lines.next() {
            let is_last = value_lines.peek().is_none();
            let line_formatting = match (is_first, is_last) {
                (true, true) => &formatting.standalone_line,
                (true, false) => &formatting.first_line,
                (false, false) => &formatting.middle_line,
                (false, true) => &formatting.last_line,
            };
            self.format_line(line_formatting, value_line)?;
            is_first = false;
        }
        Ok(())
    }

    fn format_line(
        &mut self,
        line_info: &LineFormatting,
        line: impl core::fmt::Display,
    ) -> fmt::Result {
        self.formatter.write_str(&self.line_prefix)?;
        self.formatter.write_str(line_info.prefix)?;
        line.fmt(self.formatter)?;
        self.formatter.write_str(line_info.suffix)?;
        Ok(())
    }

    fn format_reports(
        &mut self,
        reports: &[ReportRef<'a, Dynamic, Uncloneable, Local>],
    ) -> fmt::Result {
        let mut tmp_value_buffer = TmpValueBuffer::default();
        let mut tmp_attachments_buffer = TmpAttachmentsBuffer::default();
        let mut is_first = true;
        self.line_prefix = self.config.report_line_prefix_always.to_string();
        for &report in reports.iter() {
            if is_first {
                is_first = false;
            } else {
                self.formatter
                    .write_str(self.config.report_report_separator)?;
            }
            self.format_report_node(
                &mut tmp_value_buffer,
                &mut tmp_attachments_buffer,
                report,
                true,
                true,
            )?;
        }
        self.line_prefix = self.config.appendix_line_prefix_always.to_string();
        self.format_appendices(&mut tmp_value_buffer)?;
        Ok(())
    }

    fn format_report_node(
        &mut self,
        tmp_value_buffer: &mut TmpValueBuffer,
        tmp_attachments_buffer: &mut TmpAttachmentsBuffer<'a>,
        report: ReportRef<'a, Dynamic, Uncloneable, Local>,
        is_first_child: bool,
        is_last_child: bool,
    ) -> fmt::Result {
        let formatting = if is_first_child && is_last_child {
            &self.config.report_node_standalone_formatting
        } else if is_last_child {
            &self.config.report_node_last_formatting
        } else {
            &self.config.report_node_middle_formatting
        };
        let context_style =
            report.preferred_context_formatting_style(self.report_formatting_function);
        self.format_node(
            tmp_value_buffer,
            formatting,
            report.format_current_context(),
            context_style.function,
            |this, tmp_value_buffer| {
                this.format_node_data(
                    tmp_value_buffer,
                    tmp_attachments_buffer,
                    report,
                    context_style,
                )
            },
        )?;
        Ok(())
    }

    fn format_node_data(
        &mut self,
        tmp_value_buffer: &mut TmpValueBuffer,
        tmp_attachments_buffer: &mut TmpAttachmentsBuffer<'a>,
        report: ReportRef<'a, Dynamic, Uncloneable, Local>,
        context_style: rootcause_internals::handlers::ContextFormattingStyle,
    ) -> fmt::Result {
        let has_children = !report.children().is_empty();
        let has_attachments = !report.attachments().is_empty();

        // Format source chain if enabled
        let has_source_chain = if context_style.follow_source {
            self.format_source_chain(
                tmp_value_buffer,
                report,
                context_style,
                has_attachments || has_children,
            )?
        } else {
            false
        };

        let mut opaque_attachment_count = 0;
        tmp_attachments_buffer.clear();
        tmp_attachments_buffer.extend(
            report
                .attachments()
                .iter()
                .map(|attachment| {
                    (
                        attachment.preferred_formatting_style(self.report_formatting_function),
                        attachment,
                    )
                })
                .filter(
                    |(formatting_style, _attachment)| match formatting_style.placement {
                        AttachmentFormattingPlacement::Opaque => {
                            opaque_attachment_count += 1;
                            false
                        }
                        AttachmentFormattingPlacement::Hidden => false,
                        _ => true,
                    },
                ),
        );
        tmp_attachments_buffer
            .sort_by_key(|(style1, _attachment)| core::cmp::Reverse(style1.priority));
        for (attachment_index, &(attachment_formatting_style, attachment)) in
            tmp_attachments_buffer.iter().enumerate()
        {
            let is_last_attachment = attachment_index + 1 == tmp_attachments_buffer.len();
            self.format_attachment(
                tmp_value_buffer,
                attachment_formatting_style,
                attachment,
                is_last_attachment && !has_children,
            )?;
        }

        if opaque_attachment_count != 0 {
            let item_info = if has_children {
                &self.config.notice_opaque_middle_formatting
            } else {
                &self.config.notice_opaque_last_formatting
            };
            self.format_line(
                item_info,
                format_args!(
                    "{opaque_attachment_count} additional opaque {word}",
                    word = if opaque_attachment_count == 1 {
                        "attachment"
                    } else {
                        "attachments"
                    },
                ),
            )?;
        }

        if has_source_chain
            && (has_attachments || has_children)
            && let Some(source_chain_separator) = self.config.source_chain_separator
        {
            self.format_with_line_prefix(source_chain_separator)?;
        }

        if has_children && let Some(pre_child_separator) = self.config.pre_child_separator {
            self.format_with_line_prefix(pre_child_separator)?;
        }

        for (report_index, child) in report.children().iter().enumerate() {
            if report_index != 0
                && let Some(child_child_separator) = self.config.child_child_separator
            {
                self.format_with_line_prefix(child_child_separator)?;
            }
            let is_first_child = report_index == 0;
            let is_last_child = report_index + 1 == report.children().len();
            self.format_report_node(
                tmp_value_buffer,
                tmp_attachments_buffer,
                child.into_uncloneable(),
                is_first_child,
                is_last_child,
            )?;
        }

        Ok(())
    }

    fn format_attachment(
        &mut self,
        tmp_value_buffer: &mut TmpValueBuffer,
        attachment_formatting_style: AttachmentFormattingStyle,
        attachment: ReportAttachmentRef<'a, Dynamic>,
        is_last: bool,
    ) -> fmt::Result {
        match attachment_formatting_style.placement {
            AttachmentFormattingPlacement::Inline => {
                let formatting = if is_last {
                    &self.config.attachment_inline_formatting_last
                } else {
                    &self.config.attachment_inline_formatting_middle
                };
                self.format_item(
                    tmp_value_buffer,
                    formatting,
                    attachment.format_inner(),
                    attachment_formatting_style.function,
                )?;
            }
            AttachmentFormattingPlacement::InlineWithHeader { header } => {
                let formatting = if is_last {
                    &self.config.attachment_headered_formatting_last
                } else {
                    &self.config.attachment_headered_formatting_middle
                };

                self.format_node(
                    tmp_value_buffer,
                    formatting,
                    header,
                    FormattingFunction::Display,
                    |this, tmp_value_buffer| {
                        if let Some(attachment_headered_data_prefix) =
                            this.config.attachment_headered_data_prefix
                        {
                            this.format_with_line_prefix(attachment_headered_data_prefix)?;
                        }

                        this.format_item(
                            tmp_value_buffer,
                            &self.config.attachment_headered_formatting_data,
                            attachment.format_inner(),
                            attachment_formatting_style.function,
                        )?;
                        if let Some(headered_attachment_data_suffix) =
                            this.config.attachment_headered_data_suffix
                        {
                            this.format_with_line_prefix(headered_attachment_data_suffix)?;
                        }

                        Ok(())
                    },
                )?;
            }
            AttachmentFormattingPlacement::Appendix { appendix_name } => {
                let appendices = self.appendices.entry(appendix_name).or_default();
                appendices.push((attachment, attachment_formatting_style.function));
                let formatting = if is_last {
                    &self.config.notice_see_also_last_formatting
                } else {
                    &self.config.notice_see_also_middle_formatting
                };
                let line = format_args!("{appendix_name} #{}", appendices.len());
                self.format_line(formatting, line)?;
            }
            AttachmentFormattingPlacement::Opaque | AttachmentFormattingPlacement::Hidden => {}
        }
        Ok(())
    }

    fn format_source_chain(
        &mut self,
        tmp_value_buffer: &mut TmpValueBuffer,
        report: ReportRef<'a, Dynamic, Uncloneable, Local>,
        context_style: rootcause_internals::handlers::ContextFormattingStyle,
        has_more_data: bool,
    ) -> Result<bool, fmt::Error> {
        // Collect sources up to depth limit
        let max_depth = context_style.follow_source_depth.unwrap_or(usize::MAX);
        let mut sources = Vec::new();
        let mut source = report.current_context_error_source();
        let mut depth = 0;

        while let Some(err) = source {
            if depth >= max_depth {
                break;
            }
            sources.push(err);
            source = err.source();
            depth += 1;
        }

        if sources.is_empty() {
            return Ok(false);
        }

        // Check if we have omitted errors
        let has_omitted = source.is_some();

        // Format using format_node to get proper tree structure
        let header_formatting = if has_more_data {
            &self.config.source_chain_header_middle_formatting
        } else {
            &self.config.source_chain_header_last_formatting
        };

        self.format_node(
            tmp_value_buffer,
            header_formatting,
            "Following the error chain for the context:",
            FormattingFunction::Display,
            |this, tmp_value_buffer| {
                // Format each source
                for (idx, err) in sources.iter().enumerate() {
                    let is_last_source = idx + 1 == sources.len();
                    // Last item in the source chain only if it's the last source AND there's no
                    // omitted notice
                    let is_last_in_chain = is_last_source && !has_omitted;
                    let item_formatting = if is_last_in_chain {
                        &this.config.source_chain_item_last_formatting
                    } else {
                        &this.config.source_chain_item_middle_formatting
                    };

                    this.format_item(
                        tmp_value_buffer,
                        item_formatting,
                        err,
                        context_style.function,
                    )?;
                }

                // Count and report omitted errors if we hit depth limit
                if has_omitted {
                    let mut omitted_count = 0;
                    let mut remaining = source;
                    while remaining.is_some() {
                        omitted_count += 1;
                        remaining = remaining.and_then(|e| e.source());
                    }

                    // The omitted notice is always the last item in the source chain subtree,
                    // so we use a modified version with ╰ instead of ├
                    this.format_line(
                        &this
                            .config
                            .source_chain_item_last_formatting
                            .standalone_line,
                        format_args!(
                            "note: {} error(s) omitted from source chain.",
                            omitted_count
                        ),
                    )?;
                }

                Ok(())
            },
        )?;

        Ok(true)
    }

    fn format_appendices(&mut self, tmp_value_buffer: &mut TmpValueBuffer) -> fmt::Result {
        let appendices = core::mem::take(&mut self.appendices);

        if appendices.is_empty() {
            self.formatter.write_str(self.config.no_appendices_footer)?;
            return Ok(());
        }

        self.formatter
            .write_str(self.config.report_appendix_separator)?;

        let mut is_first = true;
        for (appendix_name, appendices) in &appendices {
            for (appendix_index, &(attachment, formatting_function)) in
                appendices.iter().enumerate()
            {
                if is_first {
                    is_first = false;
                } else {
                    self.formatter
                        .write_str(self.config.appendix_appendix_separator)?;
                }

                let line = format_args!("{appendix_name} #{}", appendix_index + 1);
                self.format_line(&self.config.appendix_header, line)?;
                self.format_item(
                    tmp_value_buffer,
                    &self.config.appendix_body,
                    attachment.format_inner(),
                    formatting_function,
                )?;
            }
        }
        self.formatter.write_str(self.config.appendices_footer)?;
        Ok(())
    }
}