mdv 2.2.0

Terminal Markdown Viewer
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
use super::core::{CalloutFold, CalloutInfo, CalloutKind, CalloutState};
use super::{CalloutStyle, CowStr, EventRenderer, LinkStyle, Result, ThemeElement, create_style};

#[derive(Debug, Clone)]
struct HighlightSegment {
    text: String,
    highlighted: bool,
}

const CALLOUT_BUFFER_LIMIT: usize = 64;

enum CalloutBufferEval {
    Pending,
    Callout(CalloutMarker),
    NotCallout,
}

struct CalloutMarker {
    kind: CalloutKind,
    label: String,
    label_override: Option<String>,
    fold: Option<CalloutFold>,
    trailing: Option<String>,
    allow_label_override: bool,
    suppress_paragraph_break: bool,
}

enum CalloutDecision {
    RenderHeader {
        kind: CalloutKind,
        label: String,
        label_override: Option<String>,
        fold: Option<CalloutFold>,
        trailing: Option<String>,
        suppress_paragraph_break: bool,
    },
    AwaitLabelOverride,
    FlushBuffer(String),
    Pending,
}

impl<'a> EventRenderer<'a> {
    pub(super) fn handle_text(&mut self, text: CowStr) -> Result<()> {
        if !self.in_code_block && !self.in_link {
            self.scan_footnotes_in_text_stream(&text);
        }

        if self.in_code_block {
            self.pending_task_marker = false;
            self.pending_task_marker_buffer.clear();
            self.code_block_content.push_str(&text);
            return Ok(());
        } else if self.in_link {
            match self.config.link_style {
                LinkStyle::Clickable => {
                    // For Clickable mode, collect link text but don't add to output yet
                    // We'll add the complete clickable link in handle_link_end
                    self.current_link_text.push_str(&text);
                    return Ok(());
                }
                LinkStyle::ClickableForced => {
                    // For ClickableForced mode, collect link text but don't add to output yet
                    // We'll add the complete clickable link in handle_link_end
                    self.current_link_text.push_str(&text);
                    return Ok(());
                }
                LinkStyle::Inline => {
                    // For Inline mode, collect link text but don't add to output yet
                    // We'll add the underlined text and URL in handle_link_end with flexible breaking
                    self.current_link_text.push_str(&text);
                    return Ok(());
                }
                LinkStyle::InlineTable => {
                    // Collect link text but don't add to output yet, similar to other modes
                    // We'll add the underlined text and reference number in handle_link_end
                    self.current_link_text.push_str(&text);
                    return Ok(());
                }
                LinkStyle::EndTable => {
                    // Collect link text for document-scoped reference handling
                    self.current_link_text.push_str(&text);
                    return Ok(());
                }
                LinkStyle::Hide => {
                    // This shouldn't happen since we don't set in_link for Hide mode anymore
                }
            }
            self.pending_task_marker = false;
            self.pending_task_marker_buffer.clear();
            return Ok(());
        }

        let raw_text = text.as_ref();
        if self.pending_callout_label_override {
            if self.pending_callout_label_buffer.is_empty() {
                let mut remaining = raw_text;

                if let Some(first) = remaining.chars().next() {
                    if matches!(first, '+' | '-') {
                        if let Some(CalloutState::Active(info)) = self.callout_stack.last_mut() {
                            if info.fold.is_none() {
                                info.fold = Some(match first {
                                    '+' => CalloutFold::Expanded,
                                    '-' => CalloutFold::Collapsed,
                                    _ => unreachable!(),
                                });
                            }
                        }
                        remaining = &remaining[first.len_utf8()..];
                        if remaining.is_empty() {
                            return Ok(());
                        }
                    }
                }

                let starts_with_ws = remaining
                    .chars()
                    .next()
                    .map(|ch| ch.is_whitespace())
                    .unwrap_or(false);

                if !starts_with_ws {
                    if self.finalize_pending_callout_label_override() {
                        self.suppress_next_soft_break = true;
                    }
                    return Ok(());
                }

                self.pending_callout_label_buffer.push_str(remaining);
                return Ok(());
            }

            self.pending_callout_label_buffer.push_str(raw_text);
            return Ok(());
        }
        let mut callout_decision = None;
        if self.blockquote_level > 0 && self.list_stack.is_empty() {
            if let Some(state) = self.callout_stack.last_mut() {
                if matches!(state, CalloutState::Pending) {
                    if self.pending_callout_marker {
                        self.pending_callout_marker_buffer.push_str(raw_text);
                        let evaluation =
                            Self::evaluate_callout_buffer(&self.pending_callout_marker_buffer);
                        callout_decision = Some(Self::apply_callout_buffer_evaluation(
                            state,
                            evaluation,
                            &self.pending_callout_marker_buffer,
                        ));
                    } else if raw_text.trim().is_empty() {
                        // Keep pending until we see meaningful content.
                        return Ok(());
                    } else if raw_text.trim_start().starts_with('[') {
                        self.pending_callout_marker = true;
                        self.pending_callout_marker_buffer.clear();
                        self.pending_callout_marker_buffer.push_str(raw_text);
                        let evaluation =
                            Self::evaluate_callout_buffer(&self.pending_callout_marker_buffer);
                        callout_decision = Some(Self::apply_callout_buffer_evaluation(
                            state,
                            evaluation,
                            &self.pending_callout_marker_buffer,
                        ));
                    } else {
                        *state = CalloutState::None;
                    }
                }
            }
        }

        if let Some(decision) = callout_decision {
            match decision {
                CalloutDecision::RenderHeader {
                    kind,
                    label,
                    label_override,
                    fold,
                    trailing,
                    suppress_paragraph_break,
                } => {
                    self.pending_callout_marker = false;
                    self.pending_callout_marker_buffer.clear();
                    if matches!(self.config.callout_style.style, CalloutStyle::Pretty) {
                        self.content_indent = 0;
                        self.heading_indent = 0;
                    }
                    self.note_paragraph_content();
                    self.render_callout_header(kind, &label, label_override.as_deref(), fold);
                    if suppress_paragraph_break {
                        self.suppress_next_paragraph_break = true;
                    }
                    if let Some(trailing) = trailing {
                        if !trailing.trim().is_empty() {
                            self.note_paragraph_content();
                        }
                        self.process_text_with_wrapping_and_formatting(&trailing)?;
                        self.commit_pending_heading_placeholder_if_content();
                        self.suppress_next_soft_break = false;
                    } else {
                        self.suppress_next_soft_break = true;
                    }
                    return Ok(());
                }
                CalloutDecision::AwaitLabelOverride => {
                    self.pending_callout_marker = false;
                    self.pending_callout_marker_buffer.clear();
                    if matches!(self.config.callout_style.style, CalloutStyle::Pretty) {
                        self.content_indent = 0;
                        self.heading_indent = 0;
                    }
                    self.pending_callout_label_override = true;
                    self.pending_callout_label_buffer.clear();
                    return Ok(());
                }
                CalloutDecision::FlushBuffer(buffer) => {
                    self.pending_callout_marker = false;
                    self.pending_callout_marker_buffer.clear();
                    if !buffer.trim().is_empty() {
                        self.note_paragraph_content();
                    }
                    self.process_text_with_wrapping_and_formatting(&buffer)?;
                    self.commit_pending_heading_placeholder_if_content();
                    return Ok(());
                }
                CalloutDecision::Pending => {
                    return Ok(());
                }
            }
        }

        self.maybe_render_callout_header();
        if self.pending_task_marker && !self.list_stack.is_empty() {
            if self.pending_task_marker_buffer.is_empty() && !raw_text.starts_with('[') {
                self.pending_task_marker = false;
                self.pending_task_marker_buffer.clear();
                // Fall through to normal text handling when this isn't a task marker.
            } else {
                self.pending_task_marker_buffer.push_str(raw_text);
                if self.pending_task_marker_buffer.chars().count() < 3 {
                    return Ok(());
                }

                self.pending_task_marker = false;
                let buffer = std::mem::take(&mut self.pending_task_marker_buffer);
                if let Some((marker, remainder)) = self.split_custom_task_marker_prefix(&buffer) {
                    self.note_paragraph_content();
                    let style = create_style(self.theme, ThemeElement::ListMarker);
                    let styled_marker = style.apply(marker, self.config.no_colors);
                    self.output.push_str(&styled_marker);
                    if !remainder.is_empty() {
                        self.process_text_with_wrapping_and_formatting(remainder)?;
                    }
                } else {
                    // Process text with wrapping and formatting
                    if !buffer.trim().is_empty() {
                        self.note_paragraph_content();
                    }
                    self.process_text_with_wrapping_and_formatting(&buffer)?;
                }
                self.commit_pending_heading_placeholder_if_content();
                return Ok(());
            }
        }

        // Process text with wrapping and formatting
        if !raw_text.trim().is_empty() {
            self.note_paragraph_content();
        }
        self.process_text_with_wrapping_and_formatting(raw_text)?;
        self.commit_pending_heading_placeholder_if_content();
        Ok(())
    }

    fn split_custom_task_marker_prefix<'b>(&self, text: &'b str) -> Option<(&'b str, &'b str)> {
        let bytes = text.as_bytes();
        if bytes.len() < 3 || bytes[0] != b'[' || bytes[2] != b']' {
            return None;
        }

        if !Self::is_supported_task_marker(bytes[1]) {
            return None;
        }

        let mut marker_end = 3;
        if bytes.len() == marker_end {
            return Some((&text[..marker_end], &text[marker_end..]));
        }

        while marker_end < bytes.len() {
            match bytes[marker_end] {
                b' ' | b'\t' => marker_end += 1,
                _ => break,
            }
        }

        if marker_end == 3 {
            return None;
        }

        Some((&text[..marker_end], &text[marker_end..]))
    }

    fn parse_callout_marker(text: &str) -> Option<CalloutMarker> {
        let trimmed = text.trim_start();
        if !trimmed.starts_with("[!") {
            return None;
        }

        let closing = trimmed.find(']')?;
        if closing < 2 {
            return None;
        }

        let kind_raw = trimmed[2..closing].trim();
        if kind_raw.is_empty() || !Self::is_valid_callout_kind(kind_raw) {
            return None;
        }

        let (kind, label) = Self::resolve_callout_kind(kind_raw);
        let mut rest = &trimmed[closing + 1..];
        let mut fold = None;

        if let Some(first) = rest.chars().next() {
            if matches!(first, '+' | '-') {
                fold = Some(match first {
                    '+' => CalloutFold::Expanded,
                    '-' => CalloutFold::Collapsed,
                    _ => unreachable!(),
                });
                rest = &rest[first.len_utf8()..];
            }
        }

        if rest.is_empty() {
            return Some(CalloutMarker {
                kind,
                label,
                label_override: None,
                fold,
                trailing: None,
                allow_label_override: true,
                suppress_paragraph_break: false,
            });
        }

        let starts_with_ws = rest
            .chars()
            .next()
            .map(|ch| ch.is_whitespace())
            .unwrap_or(false);
        if starts_with_ws {
            let label_override_raw = rest.trim();
            if label_override_raw.is_empty() {
                return Some(CalloutMarker {
                    kind,
                    label,
                    label_override: None,
                    fold,
                    trailing: None,
                    allow_label_override: false,
                    suppress_paragraph_break: false,
                });
            }
            return Some(CalloutMarker {
                kind,
                label,
                label_override: Some(label_override_raw.to_string()),
                fold,
                trailing: None,
                allow_label_override: false,
                suppress_paragraph_break: false,
            });
        }

        Some(CalloutMarker {
            kind,
            label,
            label_override: None,
            fold,
            trailing: None,
            allow_label_override: false,
            suppress_paragraph_break: true,
        })
    }

    fn evaluate_callout_buffer(buffer: &str) -> CalloutBufferEval {
        let trimmed = buffer.trim_start();
        if !trimmed.starts_with('[') {
            return CalloutBufferEval::NotCallout;
        }

        if trimmed.len() >= 2 && !trimmed.starts_with("[!") {
            return CalloutBufferEval::NotCallout;
        }

        if trimmed.contains(']') {
            return match Self::parse_callout_marker(buffer) {
                Some(marker) => CalloutBufferEval::Callout(marker),
                None => CalloutBufferEval::NotCallout,
            };
        }

        if trimmed.len() > CALLOUT_BUFFER_LIMIT {
            return CalloutBufferEval::NotCallout;
        }

        CalloutBufferEval::Pending
    }

    fn apply_callout_buffer_evaluation(
        state: &mut CalloutState,
        evaluation: CalloutBufferEval,
        buffer: &str,
    ) -> CalloutDecision {
        match evaluation {
            CalloutBufferEval::Callout(marker) => {
                let has_label_override = marker
                    .label_override
                    .as_ref()
                    .map(|text| !text.trim().is_empty())
                    .unwrap_or(false);
                let defer_label_override = marker.allow_label_override && !has_label_override;
                let info = CalloutInfo {
                    kind: marker.kind,
                    label: marker.label.clone(),
                    label_override: marker.label_override.clone(),
                    fold: marker.fold,
                    header_rendered: !defer_label_override,
                    min_heading_indent: None,
                    inline_link_counter: 0,
                    inline_links: Vec::new(),
                };
                *state = CalloutState::Active(info);
                if defer_label_override {
                    CalloutDecision::AwaitLabelOverride
                } else {
                    CalloutDecision::RenderHeader {
                        kind: marker.kind,
                        label: marker.label,
                        label_override: marker.label_override,
                        fold: marker.fold,
                        trailing: marker.trailing,
                        suppress_paragraph_break: marker.suppress_paragraph_break,
                    }
                }
            }
            CalloutBufferEval::NotCallout => {
                *state = CalloutState::None;
                CalloutDecision::FlushBuffer(buffer.to_string())
            }
            CalloutBufferEval::Pending => CalloutDecision::Pending,
        }
    }

    fn is_valid_callout_kind(kind: &str) -> bool {
        kind.chars()
            .all(|ch| ch.is_ascii_alphanumeric() || ch == '-' || ch == '_')
    }

    fn resolve_callout_kind(raw: &str) -> (CalloutKind, String) {
        let lower = raw.trim().to_ascii_lowercase();
        let kind = match lower.as_str() {
            "note" | "seealso" => CalloutKind::Note,
            "abstract" | "summary" | "tldr" => CalloutKind::Abstract,
            "info" => CalloutKind::Info,
            "todo" => CalloutKind::Todo,
            "tip" | "hint" | "important" => CalloutKind::Tip,
            "success" | "check" | "done" => CalloutKind::Success,
            "question" | "help" | "faq" => CalloutKind::Question,
            "warning" | "caution" | "attention" => CalloutKind::Warning,
            "failure" | "fail" | "missing" => CalloutKind::Failure,
            "danger" | "error" => CalloutKind::Danger,
            "bug" => CalloutKind::Bug,
            "example" => CalloutKind::Example,
            "quote" | "cite" => CalloutKind::Quote,
            _ => CalloutKind::Tip,
        };

        (kind, lower)
    }

    fn is_supported_task_marker(marker: u8) -> bool {
        matches!(
            marker,
            b' ' | b'x' | b'X' | b'/' | b'-' | b'?' | b'\\' | b'|'
        )
    }

    /// Process text with wrapping and formatting, handling styled text properly
    fn process_text_with_wrapping_and_formatting(&mut self, text: &str) -> Result<()> {
        if !text.contains("==") {
            return self.process_segment_with_wrapping_and_formatting(
                text,
                false,
                self.table_state.is_some(),
            );
        }

        for segment in self.split_highlight_segments(text) {
            if !segment.text.is_empty() {
                self.process_segment_with_wrapping_and_formatting(
                    &segment.text,
                    segment.highlighted,
                    self.table_state.is_some(),
                )?;
            }
        }

        Ok(())
    }

    fn process_segment_with_wrapping_and_formatting(
        &mut self,
        text: &str,
        highlighted: bool,
        is_table_cell: bool,
    ) -> Result<()> {
        // Check if this is for a table cell
        if is_table_cell {
            // For table cells, apply formatting directly without complex wrapping
            let formatted_text = self.apply_formatting_with_highlight(text, highlighted);
            if let Some(ref mut table) = self.table_state {
                table.current_cell.push_str(&formatted_text);
            }
            return Ok(());
        }

        // Add blockquote prefix if we're starting new content in a blockquote
        // Check if we're at the start of a line (after newline or any whitespace-only content)
        if self.blockquote_level > 0 {
            let after_newline = self.output.ends_with('\n');
            let at_start = self.output.is_empty();
            let at_line_start = if let Some(last_newline_pos) = self.output.rfind('\n') {
                // Check if everything after the last newline is just whitespace
                self.output[last_newline_pos + 1..].trim().is_empty()
            } else {
                // No newlines, check if entire output is just whitespace
                self.output.trim().is_empty()
            };

            if after_newline || at_start || at_line_start {
                let prefix = self.current_line_prefix();
                if !prefix.is_empty() {
                    self.output.push_str(&prefix);
                }
            }
        }

        // Check if we need to wrap text. When no explicit cols are provided,
        // wrap to the detected terminal width (unless --no-wrap is set).
        let should_wrap = self.config.is_text_wrapping_enabled();

        if should_wrap && !self.formatting_stack.is_empty() {
            // For styled text, prefer continuous decoration for strike-through
            if self.formatting_stack.contains(&ThemeElement::Strikethrough) {
                self.process_strikethrough_text_with_wrapping(text, highlighted)?;
            } else {
                // Default styled processing (per-unit formatting)
                self.process_styled_text_with_wrapping(text, highlighted)?;
            }
        } else {
            // Regular text processing
            self.process_regular_text(text, should_wrap, highlighted)?;
        }

        Ok(())
    }

    fn split_highlight_segments(&self, text: &str) -> Vec<HighlightSegment> {
        let mut segments = Vec::with_capacity(4);
        let mut buffer = String::new();
        let mut highlighted = false;
        let mut chars = text.chars().peekable();

        while let Some(ch) = chars.next() {
            if ch == '=' && matches!(chars.peek(), Some('=')) {
                chars.next(); // consume second '='
                if !buffer.is_empty() {
                    segments.push(HighlightSegment {
                        text: std::mem::take(&mut buffer),
                        highlighted,
                    });
                }
                highlighted = !highlighted;
                continue;
            }
            buffer.push(ch);
        }

        segments.push(HighlightSegment {
            text: if highlighted {
                format!("=={}", buffer)
            } else {
                buffer
            },
            highlighted,
        });

        segments
    }

    /// Process styled text with proper character/word-level wrapping like the original logic
    fn process_styled_text_with_wrapping(&mut self, text: &str, highlighted: bool) -> Result<()> {
        let terminal_width = self.effective_text_width();

        // The effective width is the full terminal width since current_line_width
        // already includes any indentation that's been added to the current line
        let effective_width = terminal_width;

        // Determine wrap mode based on config
        let wrap_mode = self.config.text_wrap_mode();

        // Split text into wrappable units (words or characters) while preserving formatting
        let units = match wrap_mode {
            crate::utils::WrapMode::Word => self.split_text_into_words_styled(text),
            crate::utils::WrapMode::Character => self.split_text_into_characters_styled(text),
            crate::utils::WrapMode::None => vec![text.to_string()],
        };

        // Process each unit individually with formatting
        for (i, unit) in units.iter().enumerate() {
            if unit.trim().is_empty() && i > 0 {
                // Handle whitespace between units
                let formatted_unit = if highlighted {
                    self.apply_formatting_with_highlight(unit, true)
                } else {
                    unit.to_string()
                };
                self.output.push_str(&formatted_unit);
                continue;
            }

            // Check if adding this unit would exceed line width
            let current_line_clean = if let Some(last_newline) = self.output.rfind('\n') {
                crate::utils::strip_ansi(&self.output[last_newline + 1..])
            } else {
                crate::utils::strip_ansi(&self.output)
            };

            let current_line_width = crate::utils::display_width(&current_line_clean);
            let unit_width = crate::utils::display_width(unit);

            // For InlineTable links, account for the reference number that will be added
            let additional_width = if self.in_link
                && matches!(
                    self.config.link_style,
                    LinkStyle::InlineTable | LinkStyle::EndTable
                ) {
                // Calculate the width of the reference number like [1], [2], etc.
                let reference_index = if matches!(self.config.link_style, LinkStyle::InlineTable) {
                    match self.callout_stack.last() {
                        Some(CalloutState::Active(info)) => info.inline_link_counter,
                        _ => self.paragraph_link_counter,
                    }
                } else {
                    self.paragraph_link_counter
                };
                let ref_num_str = format!("[{}]", reference_index);
                crate::utils::display_width(&ref_num_str)
            } else {
                0
            };

            let would_exceed = current_line_width + unit_width + additional_width > effective_width;

            // Force line break if needed (but not for the first unit on a line)
            if would_exceed && current_line_width > 0 && !current_line_clean.trim().is_empty() {
                // Check if we should break before this unit
                let should_break = match wrap_mode {
                    crate::utils::WrapMode::Word => {
                        // For word wrapping, break before words (but not before punctuation)
                        !unit.trim_start().starts_with(',')
                            && !unit.trim_start().starts_with('.')
                            && !unit.trim_start().starts_with(';')
                            && !unit.trim_start().starts_with(':')
                            && !unit.trim_start().starts_with('!')
                            && !unit.trim_start().starts_with('?')
                            && !unit.trim_start().starts_with(')')
                            && !unit.trim_start().starts_with(']')
                            && !unit.trim_start().starts_with('}')
                    }
                    crate::utils::WrapMode::Character => true, // Always break for character mode
                    crate::utils::WrapMode::None => false,
                };

                if should_break {
                    // Centralized handler adds correct indent for lists, blockquotes, headings
                    self.push_newline_with_context();
                }
            }

            // Apply formatting and add to output
            let formatted_unit = self.apply_formatting_with_highlight(unit, highlighted);

            // Add content indentation for new lines if needed
            // But don't add it if we're continuing text on the same line (like after inline links)
            let should_add_indent = (self.output.ends_with('\n') || self.output.is_empty())
                && !formatted_unit.trim().is_empty();

            // Check if we're immediately after content that shouldn't get extra indentation
            let after_inline_content = if let Some(last_newline) = self.output.rfind('\n') {
                let line_content = &self.output[last_newline + 1..];
                // If the line has content (not just whitespace), we're continuing on the same line
                !line_content.trim().is_empty()
            } else {
                // No newlines, check if we have any content
                !self.output.trim().is_empty()
            };

            // Don't add indentation if we're continuing on the same line OR
            // if we just processed a link (which may have wrapped URLs)
            if should_add_indent && !after_inline_content {
                self.push_indent_for_line_start();
            }

            self.output.push_str(&formatted_unit);
        }

        Ok(())
    }

    /// Split text into words for word-based wrapping (for styled text)
    fn split_text_into_words_styled(&self, text: &str) -> Vec<String> {
        let mut words = Vec::new();
        let mut current_word = String::new();
        let mut in_whitespace = false;

        for ch in text.chars() {
            if ch.is_whitespace() {
                if !in_whitespace && !current_word.is_empty() {
                    words.push(current_word.clone());
                    current_word.clear();
                }
                current_word.push(ch);
                in_whitespace = true;
            } else {
                if in_whitespace && !current_word.is_empty() {
                    words.push(current_word.clone());
                    current_word.clear();
                }
                current_word.push(ch);
                in_whitespace = false;
            }
        }

        if !current_word.is_empty() {
            words.push(current_word);
        }

        words
    }

    /// Split text into characters for character-based wrapping (for styled text)
    fn split_text_into_characters_styled(&self, text: &str) -> Vec<String> {
        text.chars().map(|c| c.to_string()).collect()
    }

    /// Calculate proper indentation for list content continuation lines
    pub(super) fn calculate_list_content_indent(&self) -> usize {
        let mut total_indent = 0;

        // Add heading content indentation
        total_indent += self.content_indent;

        // Add list nesting indentation (2 spaces per level)
        let indent_level = self.list_stack.len().saturating_sub(1);
        total_indent += indent_level * 2;

        // Add space for the list marker
        if let Some(list_state) = self.list_stack.last() {
            let marker_width = if list_state.is_ordered {
                // For ordered lists: "1. ", "2. ", etc. - typically 3 characters
                3
            } else {
                // For unordered lists: "- " - 2 characters
                2
            };
            total_indent += marker_width;
        }

        total_indent
    }

    /// Process text with underline formatting applied to continuous fragments between line breaks
    pub(super) fn process_underlined_text_with_wrapping(&mut self, text: &str) -> Result<()> {
        let should_wrap = self.config.is_text_wrapping_enabled();

        if !should_wrap {
            // No wrapping - just apply underline to entire text
            let formatted_text = if !self.config.no_colors {
                format!("\x1b[4m{}\x1b[0m", text)
            } else {
                text.to_string()
            };
            self.output.push_str(&formatted_text);
            return Ok(());
        }

        let terminal_width = self.effective_text_width();
        let effective_width = terminal_width;

        // Determine wrap mode based on config
        let wrap_mode = self.config.text_wrap_mode();

        // Split text into wrappable units (words or characters)
        let units = match wrap_mode {
            crate::utils::WrapMode::Word => self.split_text_into_words_styled(text),
            crate::utils::WrapMode::Character => self.split_text_into_characters_styled(text),
            crate::utils::WrapMode::None => vec![text.to_string()],
        };

        // Process units in groups - each group becomes one continuous underlined fragment
        let mut current_fragment = String::new();

        // Get initial line width
        let initial_line_clean = if let Some(last_newline) = self.output.rfind('\n') {
            crate::utils::strip_ansi(&self.output[last_newline + 1..])
        } else {
            crate::utils::strip_ansi(&self.output)
        };
        let mut fragment_start_line_width = crate::utils::display_width(&initial_line_clean);

        // If there's no space left on the current line, move to a new one before adding any underlined text
        // If only 0 or 1 cells remain, start on a fresh line to avoid placing
        // a single dangling character at the line edge (which looks like overflow).
        if effective_width.saturating_sub(fragment_start_line_width) <= 1 && !text.trim().is_empty()
        {
            self.push_newline_with_context();

            // Account for full visual prefix on the new line (heading indent, list content
            // indent, blockquote pipes, etc.)
            fragment_start_line_width = self.compute_line_start_context_width();
        }

        for (i, unit) in units.iter().enumerate() {
            let is_ws = unit.trim().is_empty();
            let unit_width = crate::utils::display_width(unit);
            let current_fragment_width = crate::utils::display_width(&current_fragment);
            let would_exceed =
                fragment_start_line_width + current_fragment_width + unit_width > effective_width;

            // Special handling for whitespace: never allow trailing spaces to cause overflow
            if is_ws && i > 0 {
                if would_exceed && !current_fragment.trim().is_empty() {
                    // Flush current fragment and break line; drop the whitespace (no leading spaces)
                    let fragment_to_format = current_fragment.trim_end();
                    let trailing_spaces = &current_fragment[fragment_to_format.len()..];

                    let formatted_fragment = if !self.config.no_colors {
                        format!("\x1b[4m{}\x1b[0m{}", fragment_to_format, trailing_spaces)
                    } else {
                        current_fragment.clone()
                    };
                    self.output.push_str(&formatted_fragment);

                    // Start new visual line with proper indent/prefix
                    self.push_newline_with_context();

                    fragment_start_line_width = self.compute_line_start_context_width();

                    current_fragment.clear();
                    continue; // Skip adding whitespace at the start of the new line
                } else {
                    // Safe to keep whitespace in the fragment
                    current_fragment.push_str(unit);
                    continue;
                }
            }

            if would_exceed && !current_fragment.trim().is_empty() {
                // We need to break - output current fragment first
                // Remove trailing spaces before applying underline to avoid underlined spaces at line end
                let fragment_to_format = current_fragment.trim_end();
                let trailing_spaces = &current_fragment[fragment_to_format.len()..];

                let formatted_fragment = if !self.config.no_colors {
                    format!("\x1b[4m{}\x1b[0m{}", fragment_to_format, trailing_spaces)
                } else {
                    current_fragment.clone()
                };
                self.output.push_str(&formatted_fragment);

                // Check if we should break before this unit
                let should_break = match wrap_mode {
                    crate::utils::WrapMode::Word => {
                        // For word wrapping, break before words (but not before punctuation)
                        !unit.trim_start().starts_with(',')
                            && !unit.trim_start().starts_with('.')
                            && !unit.trim_start().starts_with(';')
                            && !unit.trim_start().starts_with(':')
                            && !unit.trim_start().starts_with('!')
                            && !unit.trim_start().starts_with('?')
                            && !unit.trim_start().starts_with(')')
                            && !unit.trim_start().starts_with(']')
                            && !unit.trim_start().starts_with('}')
                    }
                    crate::utils::WrapMode::Character => true, // Always break for character mode
                    crate::utils::WrapMode::None => false,
                };

                if should_break {
                    self.push_newline_with_context();

                    // Reset fragment tracking for new visual line
                    fragment_start_line_width = self.compute_line_start_context_width();
                }

                // Start new fragment with current unit
                current_fragment = unit.clone();
            } else {
                if would_exceed {
                    // Nothing in fragment yet but even this unit would exceed the line.
                    // Break the line first, then start with this unit.
                    self.push_newline_with_context();

                    fragment_start_line_width = self.compute_line_start_context_width();
                }

                // Add unit to current fragment
                current_fragment.push_str(unit);
            }
        }

        // Output remaining fragment if any
        if !current_fragment.is_empty() {
            // Remove trailing spaces before applying underline to avoid underlined spaces at line end
            let fragment_to_format = current_fragment.trim_end();
            let trailing_spaces = &current_fragment[fragment_to_format.len()..];

            let formatted_fragment = if !self.config.no_colors {
                format!("\x1b[4m{}\x1b[0m{}", fragment_to_format, trailing_spaces)
            } else {
                current_fragment
            };
            self.output.push_str(&formatted_fragment);
        }

        Ok(())
    }

    /// Process text with strikethrough formatting applied as a continuous run (includes spaces)
    fn process_strikethrough_text_with_wrapping(
        &mut self,
        text: &str,
        highlighted: bool,
    ) -> Result<()> {
        let should_wrap = self.config.is_text_wrapping_enabled();

        if !should_wrap {
            // No wrapping - apply full formatting (including strikethrough) to entire text
            let formatted_text = self.apply_formatting_with_highlight(text, highlighted);
            self.output.push_str(&formatted_text);
            return Ok(());
        }

        let terminal_width = self.effective_text_width();
        let effective_width = terminal_width;

        // Determine wrap mode based on config
        let wrap_mode = self.config.text_wrap_mode();

        // Split text into wrappable units (words or characters)
        let units = match wrap_mode {
            crate::utils::WrapMode::Word => self.split_text_into_words_styled(text),
            crate::utils::WrapMode::Character => self.split_text_into_characters_styled(text),
            crate::utils::WrapMode::None => vec![text.to_string()],
        };

        // Process units in groups - each group becomes one continuous struck fragment
        let mut current_fragment = String::new();

        // Initial line width (without ANSI)
        let initial_line_clean = if let Some(last_newline) = self.output.rfind('\n') {
            crate::utils::strip_ansi(&self.output[last_newline + 1..])
        } else {
            crate::utils::strip_ansi(&self.output)
        };
        let mut fragment_start_line_width = crate::utils::display_width(&initial_line_clean);

        // If little space left on the current line, move to a new one before adding any struck text
        if effective_width.saturating_sub(fragment_start_line_width) <= 1 && !text.trim().is_empty()
        {
            self.push_newline_with_context();
            fragment_start_line_width = self.compute_line_start_context_width();
        }

        for (i, unit) in units.iter().enumerate() {
            let is_ws = unit.trim().is_empty();
            let unit_width = crate::utils::display_width(unit);
            let current_fragment_width = crate::utils::display_width(&current_fragment);
            let would_exceed =
                fragment_start_line_width + current_fragment_width + unit_width > effective_width;

            // Whitespace handling: keep inside fragment unless it would overflow the line
            if is_ws && i > 0 {
                if would_exceed && !current_fragment.trim().is_empty() {
                    // Flush current fragment and break line; drop whitespace at new line start
                    let fragment_to_format = current_fragment.trim_end();
                    let trailing_spaces = &current_fragment[fragment_to_format.len()..];

                    // Apply full formatting (includes strike) to the fragment; keep spaces highlighted when needed
                    let formatted_fragment = if highlighted {
                        self.apply_formatting_with_highlight(&current_fragment, true)
                    } else {
                        format!(
                            "{}{}",
                            self.apply_formatting(fragment_to_format),
                            trailing_spaces
                        )
                    };
                    self.output.push_str(&formatted_fragment);

                    // Start new visual line with correct context indentation
                    self.push_newline_with_context();
                    fragment_start_line_width = self.compute_line_start_context_width();

                    current_fragment.clear();
                    continue;
                } else {
                    current_fragment.push_str(unit);
                    continue;
                }
            }

            if would_exceed && !current_fragment.trim().is_empty() {
                // Break: output current fragment first
                let fragment_to_format = current_fragment.trim_end();
                let trailing_spaces = &current_fragment[fragment_to_format.len()..];
                let formatted_fragment = if highlighted {
                    self.apply_formatting_with_highlight(&current_fragment, true)
                } else {
                    format!(
                        "{}{}",
                        self.apply_formatting(fragment_to_format),
                        trailing_spaces
                    )
                };
                self.output.push_str(&formatted_fragment);

                // Decide if we break before this unit (word wrap rules)
                let should_break = match wrap_mode {
                    crate::utils::WrapMode::Word => {
                        !unit.trim_start().starts_with(',')
                            && !unit.trim_start().starts_with('.')
                            && !unit.trim_start().starts_with(';')
                            && !unit.trim_start().starts_with(':')
                            && !unit.trim_start().starts_with('!')
                            && !unit.trim_start().starts_with('?')
                            && !unit.trim_start().starts_with(')')
                            && !unit.trim_start().starts_with(']')
                            && !unit.trim_start().starts_with('}')
                    }
                    crate::utils::WrapMode::Character => true,
                    crate::utils::WrapMode::None => false,
                };

                if should_break {
                    self.push_newline_with_context();
                    fragment_start_line_width = self.compute_line_start_context_width();
                }

                current_fragment = unit.clone();
            } else {
                if would_exceed {
                    // Nothing in fragment yet, but unit would exceed -> break line first
                    self.push_newline_with_context();
                    fragment_start_line_width = self.compute_line_start_context_width();
                }

                current_fragment.push_str(unit);
            }
        }

        // Output remaining fragment if any
        if !current_fragment.is_empty() {
            let fragment_to_format = current_fragment.trim_end();
            let trailing_spaces = &current_fragment[fragment_to_format.len()..];
            let formatted_fragment = if highlighted {
                self.apply_formatting_with_highlight(&current_fragment, true)
            } else {
                format!(
                    "{}{}",
                    self.apply_formatting(fragment_to_format),
                    trailing_spaces
                )
            };
            self.output.push_str(&formatted_fragment);
        }

        Ok(())
    }
    fn process_regular_text(
        &mut self,
        text: &str,
        should_wrap: bool,
        highlighted: bool,
    ) -> Result<()> {
        // Use the same word-by-word logic as styled text for consistent behavior
        if should_wrap {
            let terminal_width = self.effective_text_width();

            // Use full terminal width as effective width since current_line_width already includes indents
            let effective_width = terminal_width;

            // Determine wrap mode based on config
            let wrap_mode = self.config.text_wrap_mode();

            // Split text into wrappable units (words or characters)
            let units = match wrap_mode {
                crate::utils::WrapMode::Word => self.split_text_into_words_styled(text),
                crate::utils::WrapMode::Character => self.split_text_into_characters_styled(text),
                crate::utils::WrapMode::None => vec![text.to_string()],
            };

            // Process each unit individually
            for (_i, unit) in units.iter().enumerate() {
                if unit.trim().is_empty() {
                    // Handle whitespace cautiously: don't let a trailing space overflow the line
                    let current_line_clean = if let Some(last_newline) = self.output.rfind('\n') {
                        crate::utils::strip_ansi(&self.output[last_newline + 1..])
                    } else {
                        crate::utils::strip_ansi(&self.output)
                    };
                    let current_line_width = crate::utils::display_width(&current_line_clean);
                    let space_width = crate::utils::display_width(unit);
                    if current_line_width + space_width > effective_width {
                        // Break visual line and skip adding whitespace at start of next line
                        self.push_newline_with_context();
                    } else {
                        let formatted_unit = if highlighted {
                            self.apply_formatting_with_highlight(unit, true)
                        } else {
                            unit.to_string()
                        };
                        self.output.push_str(&formatted_unit);
                    }
                    continue;
                }

                // Check if adding this unit would exceed line width
                let current_line_clean = if let Some(last_newline) = self.output.rfind('\n') {
                    crate::utils::strip_ansi(&self.output[last_newline + 1..])
                } else {
                    crate::utils::strip_ansi(&self.output)
                };

                let current_line_width = crate::utils::display_width(&current_line_clean);
                let unit_width = crate::utils::display_width(unit);

                // For InlineTable links, account for the reference number that will be added
                let additional_width = if self.in_link
                    && matches!(
                        self.config.link_style,
                        LinkStyle::InlineTable | LinkStyle::EndTable
                    ) {
                    // Calculate the width of the reference number like [1], [2], etc.
                    let reference_index =
                        if matches!(self.config.link_style, LinkStyle::InlineTable) {
                            match self.callout_stack.last() {
                                Some(CalloutState::Active(info)) => info.inline_link_counter,
                                _ => self.paragraph_link_counter,
                            }
                        } else {
                            self.paragraph_link_counter
                        };
                    let ref_num_str = format!("[{}]", reference_index);
                    crate::utils::display_width(&ref_num_str)
                } else {
                    0
                };

                let would_exceed =
                    current_line_width + unit_width + additional_width > effective_width;

                // Force line break if needed (but not for the first unit on a line)
                if would_exceed && current_line_width > 0 && !current_line_clean.trim().is_empty() {
                    // Check if we should break before this unit
                    let should_break = match wrap_mode {
                        crate::utils::WrapMode::Word => {
                            // For word wrapping, break before words (but not before punctuation)
                            !unit.trim_start().starts_with(',')
                                && !unit.trim_start().starts_with('.')
                                && !unit.trim_start().starts_with(';')
                                && !unit.trim_start().starts_with(':')
                                && !unit.trim_start().starts_with('!')
                                && !unit.trim_start().starts_with('?')
                                && !unit.trim_start().starts_with(')')
                                && !unit.trim_start().starts_with(']')
                                && !unit.trim_start().starts_with('}')
                        }
                        crate::utils::WrapMode::Character => true, // Always break for character mode
                        crate::utils::WrapMode::None => false,
                    };

                    if should_break {
                        self.push_newline_with_context();
                    }
                }

                // Apply formatting (no-op for regular text) and add to output
                let formatted_unit = self.apply_formatting_with_highlight(unit, highlighted);

                // Add content indentation for new lines if needed
                // But don't add it if we're continuing text on the same line (like after inline links)
                let should_add_indent = (self.output.ends_with('\n') || self.output.is_empty())
                    && !formatted_unit.trim().is_empty();

                // Check if we're immediately after content that shouldn't get extra indentation
                let after_inline_content = if let Some(last_newline) = self.output.rfind('\n') {
                    let line_content = &self.output[last_newline + 1..];
                    // If the line has content (not just whitespace), we're continuing on the same line
                    !line_content.trim().is_empty()
                } else {
                    // No newlines, check if we have any content
                    !self.output.trim().is_empty()
                };

                if should_add_indent && !after_inline_content {
                    self.push_indent_for_line_start();
                }

                self.output.push_str(&formatted_unit);
            }
        } else {
            // No wrapping - still ensure correct indentation at visual line starts
            let final_text = self.apply_formatting_with_highlight(text, highlighted);

            // Add content indentation for new visual lines when appropriate
            if (self.output.ends_with('\n') || self.output.is_empty())
                && !final_text.trim().is_empty()
            {
                // If the current line (after the last newline) already contains
                // non-whitespace content, we are continuing on the same line and
                // must not add extra indentation.
                let after_inline_content = if let Some(last_newline) = self.output.rfind('\n') {
                    let line_content = &self.output[last_newline + 1..];
                    !line_content.trim().is_empty()
                } else {
                    !self.output.trim().is_empty()
                };

                if !after_inline_content {
                    self.push_indent_for_line_start();
                }
            }

            self.output.push_str(&final_text);
        }

        Ok(())
    }
}