smart-markdown 0.3.0

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

/// State for tracking a table while rows are still being streamed.
#[derive(Debug, Clone)]
struct TableState {
    headers: Vec<String>,
    alignments: Vec<Alignment>,
    rows: Vec<Vec<String>>,
    rendered_lines: usize,
}

impl TableState {
    fn new(header: &str, separator: &str) -> Option<Self> {
        let headers = split_table_row(header);
        let separator_cells = split_table_row(separator);
        if headers.len() < 2
            || separator_cells.len() != headers.len()
            || !is_separator_cells(&separator_cells)
        {
            return None;
        }

        let alignments = separator_cells
            .iter()
            .map(|cell| parse_table_alignment(cell))
            .collect();

        Some(TableState {
            headers: headers
                .into_iter()
                .map(|header| header.trim().to_string())
                .collect(),
            alignments,
            rows: Vec::new(),
            rendered_lines: 0,
        })
    }

    fn column_count(&self) -> usize {
        self.headers.len()
    }

    fn has_rows(&self) -> bool {
        !self.rows.is_empty()
    }

    fn add_row(&mut self, row: Vec<String>) {
        self.rows.push(pad_table_row(row, self.column_count()));
    }

    fn render(
        &self,
        pending_row: Option<Vec<String>>,
        width: usize,
        theme_mode: ThemeMode,
        code_theme: Option<&str>,
        ascii_table_borders: bool,
    ) -> Vec<String> {
        let mut rows = self.rows.clone();
        if let Some(row) = pending_row {
            rows.push(pad_table_row(row, self.column_count()));
        }

        let table = MarkdownElement::Table(TableDef {
            headers: self.headers.clone(),
            alignments: self.alignments.clone(),
            rows,
        });

        render_element_with_options(&table, width, theme_mode, code_theme, ascii_table_borders)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TableBufferAction {
    KeepTable,
    CloseTable,
}

#[derive(Debug, Clone)]
struct TableBufferResult {
    action: TableBufferAction,
    pending_row: Option<Vec<String>>,
    consumed_bytes: usize,
}

fn split_table_row(line: &str) -> Vec<String> {
    let mut inner = line.trim();
    if let Some(stripped) = inner.strip_prefix('|') {
        inner = stripped;
    }
    if let Some(stripped) = inner.strip_suffix('|') {
        inner = stripped;
    }

    let mut cells = Vec::new();
    let mut current = String::new();
    let mut escaping = false;

    for ch in inner.chars() {
        if escaping {
            current.push(ch);
            escaping = false;
        } else if ch == '\\' {
            escaping = true;
        } else if ch == '|' {
            cells.push(std::mem::take(&mut current));
        } else {
            current.push(ch);
        }
    }
    cells.push(current);
    cells
}

fn is_separator_cells(cells: &[String]) -> bool {
    cells.iter().all(|cell| {
        let trimmed = cell.trim();
        !trimmed.is_empty()
            && trimmed
                .chars()
                .all(|ch| ch == '-' || ch == ':' || ch == ' ')
    })
}

fn parse_table_alignment(cell: &str) -> Alignment {
    let trimmed = cell.trim();
    match (trimmed.starts_with(':'), trimmed.ends_with(':')) {
        (true, true) => Alignment::Center,
        (false, true) => Alignment::Right,
        _ => Alignment::Left,
    }
}

fn pad_table_row(mut row: Vec<String>, column_count: usize) -> Vec<String> {
    row.truncate(column_count);
    while row.len() < column_count {
        row.push(String::new());
    }
    row.into_iter()
        .map(|cell| cell.trim().to_string())
        .collect()
}

fn looks_like_table_row(line: &str) -> bool {
    let trimmed = line.trim();
    trimmed.starts_with('|') || trimmed.contains('|')
}

fn consumed_prefix_for_lines(text: &str, count: usize) -> Option<usize> {
    let mut seen = 0;
    for (idx, ch) in text.char_indices() {
        if ch == '\n' {
            seen += 1;
            if seen == count {
                return Some(idx + ch.len_utf8());
            }
        }
    }

    if text.lines().count() >= count {
        Some(text.len())
    } else {
        None
    }
}

fn consume_streamed_table_buffer(buffer: &str, table_state: &mut TableState) -> TableBufferResult {
    let mut consumed_bytes = 0;
    let mut rest = buffer;

    while let Some(newline_idx) = rest.find('\n') {
        let line = &rest[..newline_idx];
        let trimmed = line.trim();
        let line_bytes = newline_idx + 1;

        if trimmed.is_empty() {
            if table_state.has_rows() {
                return TableBufferResult {
                    action: TableBufferAction::CloseTable,
                    pending_row: None,
                    consumed_bytes: consumed_bytes + line_bytes,
                };
            }
            consumed_bytes += line_bytes;
            rest = &rest[line_bytes..];
            continue;
        }

        if !looks_like_table_row(trimmed) {
            return TableBufferResult {
                action: TableBufferAction::CloseTable,
                pending_row: None,
                consumed_bytes,
            };
        }

        let cells = split_table_row(trimmed);
        if cells.len() > table_state.column_count() {
            return TableBufferResult {
                action: TableBufferAction::CloseTable,
                pending_row: None,
                consumed_bytes,
            };
        }

        table_state.add_row(cells);
        consumed_bytes += line_bytes;
        rest = &rest[line_bytes..];
    }

    let pending = rest.trim();
    if pending.is_empty() {
        return TableBufferResult {
            action: TableBufferAction::KeepTable,
            pending_row: None,
            consumed_bytes,
        };
    }

    if looks_like_table_row(pending) {
        return TableBufferResult {
            action: TableBufferAction::KeepTable,
            pending_row: Some(split_table_row(pending)),
            consumed_bytes,
        };
    }

    TableBufferResult {
        action: TableBufferAction::CloseTable,
        pending_row: None,
        consumed_bytes,
    }
}

fn prepend_clear_lines(rendered_lines: usize, lines: Vec<String>) -> Vec<String> {
    if rendered_lines == 0 {
        return lines;
    }

    let mut output = Vec::with_capacity(lines.len());
    for (index, line) in lines.into_iter().enumerate() {
        if index == 0 {
            output.push(format!("\x1B[{rendered_lines}A\x1B[2K{line}"));
        } else {
            output.push(format!("\x1B[2K{line}"));
        }
    }
    output
}

fn render_streamed_table(
    table_state: &mut TableState,
    pending_row: Option<Vec<String>>,
    width: usize,
    theme_mode: ThemeMode,
    code_theme: Option<&str>,
    ascii_table_borders: bool,
) -> Vec<String> {
    let old_rendered_lines = table_state.rendered_lines;
    let lines = table_state.render(
        pending_row,
        width,
        theme_mode,
        code_theme,
        ascii_table_borders,
    );
    table_state.rendered_lines = lines.len();
    prepend_clear_lines(old_rendered_lines, lines)
}

fn try_start_streamed_table(buffer: &mut String) -> Option<TableState> {
    let mut lines = buffer.lines();
    let header = lines.next()?.trim();
    let separator = lines.next()?.trim();
    let table_state = TableState::new(header, separator)?;
    let consumed = consumed_prefix_for_lines(buffer, 2)?;
    *buffer = buffer[consumed..].to_string();
    Some(table_state)
}

/// Incrementally renders markdown text chunks as they arrive.
///
/// `StreamRenderer` is designed for streaming LLM responses: as the model
/// generates markdown text chunk by chunk, this renderer produces complete,
/// renderable lines as soon as enough input has been buffered to form a
/// complete markdown element (e.g. a paragraph ended by a blank line, a
/// complete table, a closed fenced code block).
///
/// # Examples
///
/// ```rust
/// use smart_markdown::{StreamRenderer, ThemeMode, is_light_terminal};
///
/// let width = terminal_size::terminal_size()
///     .map(|(w, _)| w.0 as usize)
///     .unwrap_or(80);
/// let theme = if is_light_terminal() { ThemeMode::Light } else { ThemeMode::Dark };
/// let mut sr = StreamRenderer::new(width, theme)
///     .with_ascii_table_borders(true)
///     .with_code_theme("base16-ocean.dark");
///
/// // Feed chunks as they arrive from the LLM
/// for line in sr.push("# Hello\n\n") {
///     println!("{line}");
/// }
/// for line in sr.push("this is **bold** text") {
///     println!("{line}");
/// }
///
/// // Flush anything still buffered at the end
/// for line in sr.flush_remaining() {
///     println!("{line}");
/// }
/// ```
pub struct StreamRenderer {
    buffer: String,
    width: usize,
    theme_mode: ThemeMode,
    code_theme: Option<String>,
    ascii_table_borders: bool,
    rendered_count: usize,
    /// Tracks the current incomplete table being streamed
    current_table: Option<TableState>,
}

impl StreamRenderer {
    /// Create a new stream renderer.
    ///
    /// - `width`: terminal width in columns (e.g. from the `terminal_size` crate).
    /// - `theme_mode`: controls syntax highlighting theme for code blocks.
    pub fn new(width: usize, theme_mode: ThemeMode) -> Self {
        StreamRenderer {
            buffer: String::new(),
            width,
            theme_mode,
            code_theme: None,
            ascii_table_borders: false,
            rendered_count: 0,
            current_table: None,
        }
    }

    /// Set a custom syntax highlighting theme by name.
    ///
    /// See [`crate::highlight::list_themes`] for available theme names.
    pub fn with_code_theme(mut self, theme: &str) -> Self {
        self.code_theme = Some(theme.to_string());
        self
    }

    /// Use ASCII-only table borders (`+`, `-`, `|`) instead of Unicode
    /// box-drawing characters (`┌`, `─`, `│`, etc.).
    ///
    /// Useful for terminals where Unicode box-drawing renders poorly
    /// (e.g. light-background themes without proper color inversion).
    pub fn with_ascii_table_borders(mut self, ascii: bool) -> Self {
        self.ascii_table_borders = ascii;
        self
    }

    /// Push additional text chunks.
    ///
    /// Returns rendered complete lines as they become available.
    /// Incomplete markdown (partial fenced blocks, tables, paragraphs)
    /// is buffered internally.
    pub fn push(&mut self, text: &str) -> Vec<String> {
        self.buffer.push_str(text);

        if self.current_table.is_none()
            && let Some(table_state) = try_start_streamed_table(&mut self.buffer)
        {
            self.current_table = Some(table_state);
        }

        self.emit_complete()
    }

    /// Flush any remaining buffered content and return the final lines.
    ///
    /// Call this once at the end of the stream to emit any markdown that
    /// hasn't been completed by a blank line or structural close.
    pub fn flush_remaining(&mut self) -> Vec<String> {
        if let Some(mut table_state) = self.current_table.take() {
            let table_result = consume_streamed_table_buffer(&self.buffer, &mut table_state);
            let output = render_streamed_table(
                &mut table_state,
                table_result.pending_row,
                self.width,
                self.theme_mode,
                self.code_theme.as_deref(),
                self.ascii_table_borders,
            );
            self.buffer.clear();
            self.rendered_count = 0;
            return output;
        }

        if self.buffer.trim().is_empty() {
            return Vec::new();
        }
        if !self.buffer.ends_with('\n') {
            self.buffer.push('\n');
        }
        let elements = parse_document(&self.buffer);
        let total = elements.len();
        let new_elements: Vec<_> = elements.into_iter().skip(self.rendered_count).collect();
        self.rendered_count = total;

        let mut output: Vec<String> = Vec::new();
        for elem in &new_elements {
            output.extend(render_element_with_options(
                elem,
                self.width,
                self.theme_mode,
                self.code_theme.as_deref(),
                self.ascii_table_borders,
            ));
        }
        self.buffer.clear();
        self.rendered_count = 0;
        output
    }

    fn emit_complete(&mut self) -> Vec<String> {
        let mut output: Vec<String> = Vec::new();

        if let Some(mut table_state) = self.current_table.take() {
            let table_result = consume_streamed_table_buffer(&self.buffer, &mut table_state);
            if table_result.consumed_bytes > 0 {
                self.buffer = self.buffer[table_result.consumed_bytes..].to_string();
            }

            let should_render = table_result.pending_row.is_some()
                || table_state.has_rows()
                || table_state.rendered_lines > 0
                || table_result.action == TableBufferAction::CloseTable;

            if should_render {
                output.extend(render_streamed_table(
                    &mut table_state,
                    table_result.pending_row.clone(),
                    self.width,
                    self.theme_mode,
                    self.code_theme.as_deref(),
                    self.ascii_table_borders,
                ));
            }

            if table_result.action == TableBufferAction::KeepTable {
                self.current_table = Some(table_state);
                return output;
            }
        }

        let (complete, remaining) = split_at_complete_boundary(&self.buffer);
        if complete.is_empty() {
            self.buffer = remaining;
            self.rendered_count = 0;
            return output;
        }

        let elements = parse_document(&complete);
        let total = elements.len();
        let new_elements: Vec<_> = elements.into_iter().skip(self.rendered_count).collect();
        self.rendered_count = total;

        for elem in &new_elements {
            output.extend(render_element_with_options(
                elem,
                self.width,
                self.theme_mode,
                self.code_theme.as_deref(),
                self.ascii_table_borders,
            ));
        }

        self.buffer = remaining;
        self.rendered_count = 0;
        output
    }
}

/// Split buffer at the last complete markdown element boundary.
/// Returns (complete_prefix, remainder) where complete_prefix ends at a
/// safe boundary (blank line, end of a fenced block, etc.).
fn split_at_complete_boundary(text: &str) -> (String, String) {
    if text.is_empty() {
        return (String::new(), String::new());
    }

    // Find the last double-newline (blank line) boundary — safe for most elements,
    // but must not split a table (header|sep without data rows would emit a
    // zero-row border box, then orphan subsequent content).
    if let Some(pos) = text.rfind("\n\n") {
        let prefix = &text[..pos];
        if let Some(last_line) = prefix.lines().last()
            && is_table_separator(last_line.trim())
        {
            return (String::new(), text.to_string());
        }
        return (prefix.to_string(), trim_leading_newlines(&text[pos + 2..]));
    }

    // Check for completed fenced code block (``` or ~~~).
    let lines: Vec<&str> = text.lines().collect();
    if lines.len() >= 2 {
        let first = lines[0];
        if (first.starts_with("```") || first.starts_with("~~~")) && first.len() >= 3 {
            let fence = &first[..3];
            for (i, line) in lines.iter().enumerate().skip(1) {
                if line.trim().starts_with(fence)
                    && line.trim().len() >= 3
                    && line
                        .trim()
                        .chars()
                        .take(3)
                        .all(|c| c == fence.chars().next().unwrap())
                {
                    let end_pos = text
                        .char_indices()
                        .nth(
                            text.lines()
                                .take(i + 1)
                                .map(|l| l.len() + 1)
                                .sum::<usize>()
                                .saturating_sub(1),
                        )
                        .map(|(idx, _)| idx)
                        .unwrap_or(text.len());
                    return (
                        text[..end_pos].to_string(),
                        trim_leading_newlines(&text[end_pos..]),
                    );
                }
            }
            // Fenced block started but not closed — buffer it entirely
            return (String::new(), text.to_string());
        }
    }

    // Check for table. A table has: header line, separator line, then rows.
    // Complete when a terminator follows data rows, or when data rows are
    // present and the buffer ends (LLM streams don't add trailing blank lines).
    if let Some(table_end) = find_complete_table_end(&lines) {
        let end_pos = if table_end == lines.len() {
            text.len()
        } else {
            text.char_indices()
                .nth(
                    text.lines()
                        .take(table_end)
                        .map(|l| l.len() + 1)
                        .sum::<usize>()
                        .saturating_sub(1),
                )
                .map(|(idx, _)| idx)
                .unwrap_or(text.len())
        };
        return (
            text[..end_pos].to_string(),
            trim_leading_newlines(&text[end_pos..]),
        );
    }

    // Guard: incomplete table — header + separator detected but find_complete_table_end
    // found no terminator (blank line or non-table line). Buffer everything unconditionally.
    if lines.len() >= 2 {
        let h = lines[0].trim();
        let s = lines[1].trim();
        let hc: Vec<&str> = h.split('|').filter(|c| !c.is_empty()).collect();
        let sc: Vec<&str> = s.split('|').filter(|c| !c.is_empty()).collect();
        if hc.len() >= 2
            && sc.len() >= 2
            && sc.len() == hc.len()
            && sc
                .iter()
                .all(|c| c.chars().all(|ch| ch == '-' || ch == ':' || ch == ' '))
        {
            return (String::new(), text.to_string());
        }
    }

    // Check for definition list — needs the term line + at least one ": " definition line
    if let Some(def_end) = find_complete_definition_list_end(&lines) {
        let end_pos = text
            .char_indices()
            .nth(
                text.lines()
                    .take(def_end)
                    .map(|l| l.len() + 1)
                    .sum::<usize>()
                    .saturating_sub(1),
            )
            .map(|(idx, _)| idx)
            .unwrap_or(text.len());
        return (
            text[..end_pos].to_string(),
            trim_leading_newlines(&text[end_pos..]),
        );
    }

    // Guard: incomplete definition list — term present but no ": " definition line yet
    if lines.len() >= 2
        && is_definition_list_term(lines[0].trim())
        && !lines[1].trim().starts_with(": ")
    {
        return (String::new(), text.to_string());
    }

    // Check for HTML block — starts with a tag like <div>, needs closing </div> or blank line
    if let Some(html_end) = find_complete_html_block_end(&lines) {
        let end_pos = text
            .char_indices()
            .nth(
                text.lines()
                    .take(html_end)
                    .map(|l| l.len() + 1)
                    .sum::<usize>()
                    .saturating_sub(1),
            )
            .map(|(idx, _)| idx)
            .unwrap_or(text.len());
        return (
            text[..end_pos].to_string(),
            trim_leading_newlines(&text[end_pos..]),
        );
    }

    // Guard: incomplete HTML block — opening tag present but no closing tag or blank line
    if is_html_block_tag(lines[0].trim()) {
        return (String::new(), text.to_string());
    }

    // Check for indented code block — followed by non-indented, non-empty line or blank line
    if let Some(code_end) = find_complete_indented_code_end(&lines) {
        let end_pos = text
            .char_indices()
            .nth(
                text.lines()
                    .take(code_end)
                    .map(|l| l.len() + 1)
                    .sum::<usize>()
                    .saturating_sub(1),
            )
            .map(|(idx, _)| idx)
            .unwrap_or(text.len());
        return (
            text[..end_pos].to_string(),
            trim_leading_newlines(&text[end_pos..]),
        );
    }

    // Guard: incomplete indented code block — first line is indented but no end marker yet
    if (lines[0].starts_with("    ") || (lines[0].starts_with('\t') && lines[0].len() > 1))
        && lines.len() == 1
    {
        return (String::new(), text.to_string());
    }

    // Check for complete lists (ordered, unordered, task) — a list ends when a non-list line appears
    if let Some(list_end) = find_complete_list_end(&lines) {
        let end_pos = text
            .char_indices()
            .nth(
                text.lines()
                    .take(list_end)
                    .map(|l| l.len() + 1)
                    .sum::<usize>()
                    .saturating_sub(1),
            )
            .map(|(idx, _)| idx)
            .unwrap_or(text.len());
        return (
            text[..end_pos].to_string(),
            trim_leading_newlines(&text[end_pos..]),
        );
    }

    // Guard: incomplete list — first line is a list item but no terminator yet
    if is_any_list_item(lines[0].trim()) {
        return (String::new(), text.to_string());
    }

    // Check for footnote definitions — they can be multiline (continuation lines indented)
    if let Some(fn_end) = find_complete_footnote_end(&lines) {
        let end_pos = text
            .char_indices()
            .nth(
                text.lines()
                    .take(fn_end)
                    .map(|l| l.len() + 1)
                    .sum::<usize>()
                    .saturating_sub(1),
            )
            .map(|(idx, _)| idx)
            .unwrap_or(text.len());
        return (
            text[..end_pos].to_string(),
            trim_leading_newlines(&text[end_pos..]),
        );
    }

    // Guard: incomplete footnote — [^label]: line present but continuation/content still arriving
    if is_footnote_line(lines[0].trim()) {
        return (String::new(), text.to_string());
    }

    // Single-line elements: headings, horizontal rules, blockquotes (single line), paragraphs
    // If the last line is a heading or HR, emit everything
    if let Some(last) = lines.last() {
        let trimmed = last.trim();
        if trimmed.starts_with('#') && trimmed.len() > 1 && trimmed.as_bytes().get(1) == Some(&b' ')
        {
            // ATX heading — complete as a single line. Split off heading + preceding lines.
            if lines.len() > 1 {
                let end_pos = text
                    .char_indices()
                    .nth(
                        text.lines()
                            .take(lines.len() - 1)
                            .map(|l| l.len() + 1)
                            .sum::<usize>()
                            .saturating_sub(1),
                    )
                    .map(|(idx, _)| idx)
                    .unwrap_or(text.len());
                return (text[..end_pos].to_string(), text[end_pos..].to_string());
            }
            return (text.to_string(), String::new());
        }
        if trimmed == "---" || trimmed == "***" || trimmed == "___" {
            return (text.to_string(), String::new());
        }
        if trimmed.starts_with('>') {
            // Blockquote: emit everything before the blockquote line
            if lines.len() > 1 {
                let end_pos = text
                    .char_indices()
                    .nth(
                        text.lines()
                            .take(lines.len() - 1)
                            .map(|l| l.len() + 1)
                            .sum::<usize>()
                            .saturating_sub(1),
                    )
                    .map(|(idx, _)| idx)
                    .unwrap_or(text.len());
                return (text[..end_pos].to_string(), text[end_pos..].to_string());
            }
            return (text.to_string(), String::new());
        }
    }

    // Guard: single-line table header — looks like table row start, buffer for future chunks
    if lines.len() == 1 {
        let trimmed = lines[0].trim();
        if trimmed.starts_with('|') && trimmed.ends_with('|') {
            return (String::new(), text.to_string());
        }
    }

    // If the text ends with a newline, it's a complete paragraph or set of paragraphs
    if text.ends_with('\n') {
        return (text.to_string(), String::new());
    }

    // Scan backwards from the last \n to find a complete element boundary.
    // If the preceding line looks standalone (heading, HR, blockquote), split there.
    if let Some(last_nl) = text.rfind('\n') {
        let prefix = &text[..last_nl];
        let pre_lines: Vec<&str> = prefix.lines().collect();
        if let Some(pre_last) = pre_lines.last()
            && is_standalone_line(pre_last)
        {
            return (
                text[..last_nl + 1].to_string(),
                text[last_nl + 1..].to_string(),
            );
        }
    }

    // Buffer the text — more may arrive that belongs to the same paragraph
    (String::new(), text.to_string())
}

fn is_standalone_line(line: &str) -> bool {
    let line = line.trim();
    if line.starts_with('#') {
        let level = line.chars().take_while(|&c| c == '#').count();
        return level <= 6 && line.len() > level && line.as_bytes().get(level) == Some(&b' ');
    }
    line == "---" || line == "***" || line == "___" || line.starts_with('>')
}

fn trim_leading_newlines(s: &str) -> String {
    s.trim_start_matches('\n').to_string()
}

fn is_table_separator(line: &str) -> bool {
    let l = line.trim();
    let cells: Vec<&str> = l.split('|').filter(|s| !s.is_empty()).collect();
    if cells.is_empty() {
        return false;
    }
    cells
        .iter()
        .all(|c| c.chars().all(|ch| ch == '-' || ch == ':' || ch == ' '))
}

fn find_complete_table_end(lines: &[&str]) -> Option<usize> {
    if lines.len() < 2 {
        return None;
    }
    let header = lines[0].trim();
    let sep = lines[1].trim();
    let header_cells: Vec<&str> = header.split('|').filter(|s| !s.is_empty()).collect();
    let sep_cells: Vec<&str> = sep.split('|').filter(|s| !s.is_empty()).collect();
    if header_cells.len() < 2 || sep_cells.len() != header_cells.len() {
        return None;
    }
    let is_valid_sep = sep_cells
        .iter()
        .all(|c| c.chars().all(|ch| ch == '-' || ch == ':' || ch == ' '));
    if !is_valid_sep {
        return None;
    }
    let header_cols = header_cells.len();
    let mut seen_data = false;
    for (i, tmp) in lines.iter().enumerate().skip(2) {
        let tmp = tmp.trim();
        if tmp.is_empty() {
            if seen_data {
                return Some(i + 1);
            }
            continue;
        }
        seen_data = true;
        let row_cells: Vec<&str> = tmp.split('|').filter(|s| !s.is_empty()).collect();
        if row_cells.is_empty() {
            return Some(i);
        }
        if row_cells.len() != header_cols {
            return Some(i);
        }
    }
    if seen_data { Some(lines.len()) } else { None }
}

fn find_complete_definition_list_end(lines: &[&str]) -> Option<usize> {
    if lines.len() < 2 {
        return None;
    }
    let first = lines[0].trim();
    if first.starts_with('#')
        || first.starts_with('>')
        || first.starts_with('|')
        || first.starts_with('-')
        || first.starts_with('*')
        || first.starts_with('`')
        || first.is_empty()
    {
        return None;
    }
    if !lines[1].trim().starts_with(": ") {
        return None;
    }
    let mut i = 2;
    while i < lines.len() {
        let tmp = lines[i].trim();
        if tmp.starts_with(": ") {
            i += 1;
        } else if tmp.is_empty() {
            return Some(i + 1);
        } else {
            return Some(i);
        }
    }
    None
}

fn find_complete_html_block_end(lines: &[&str]) -> Option<usize> {
    let first = lines[0].trim();
    if !first.starts_with('<') {
        return None;
    }
    let rest = &first[1..];
    let tag_end = rest.find(|c: char| c == '>' || c.is_whitespace())?;
    let tag = &rest[..tag_end];
    let lower = tag.to_lowercase();
    let valid = matches!(
        lower.as_str(),
        "div"
            | "pre"
            | "table"
            | "script"
            | "style"
            | "section"
            | "article"
            | "nav"
            | "footer"
            | "header"
            | "aside"
            | "main"
            | "blockquote"
            | "form"
            | "fieldset"
            | "details"
            | "dialog"
            | "figure"
            | "figcaption"
            | "dl"
            | "ol"
            | "ul"
            | "h1"
            | "h2"
            | "h3"
            | "h4"
            | "h5"
            | "h6"
    );
    if !valid {
        return None;
    }
    let close = format!("</{}>", tag);
    for (i, line) in lines.iter().enumerate().skip(1) {
        if line.to_lowercase().contains(&close) {
            return Some(i + 1);
        }
        if line.trim().is_empty() {
            return Some(i + 1);
        }
    }
    None
}

fn find_complete_indented_code_end(lines: &[&str]) -> Option<usize> {
    let first = lines[0];
    if !(first.starts_with("    ") || first.starts_with('\t') && first.len() > 1) {
        return None;
    }
    for (i, l) in lines.iter().enumerate().skip(1) {
        if l.starts_with("    ") || (l.starts_with('\t') && l.len() > 1) {
            continue;
        }
        if l.is_empty() {
            continue;
        }
        return Some(i);
    }
    None
}

fn find_complete_list_end(lines: &[&str]) -> Option<usize> {
    let first = lines[0].trim();
    let is_unordered =
        first.starts_with("* ") || first.starts_with("- ") || first.starts_with("+ ");
    let is_task = first.starts_with("- [ ] ")
        || first.starts_with("- [x] ")
        || first.starts_with("- [X] ")
        || first.starts_with("* [ ] ")
        || first.starts_with("* [x] ")
        || first.starts_with("* [X] ");
    let is_ordered = first
        .find(". ")
        .is_some_and(|pos| first[..pos].parse::<u64>().is_ok());

    if !is_unordered && !is_task && !is_ordered {
        return None;
    }

    for (i, tmp) in lines.iter().enumerate().skip(1) {
        let tmp = tmp.trim();
        if tmp.is_empty() {
            return Some(i + 1);
        }

        if is_unordered || is_task {
            let still_list = tmp.starts_with("* ")
                || tmp.starts_with("- ")
                || tmp.starts_with("+ ")
                || (is_task
                    && (tmp.starts_with("- [ ] ")
                        || tmp.starts_with("- [x] ")
                        || tmp.starts_with("- [X] ")
                        || tmp.starts_with("* [ ] ")
                        || tmp.starts_with("* [x] ")
                        || tmp.starts_with("* [X] ")));
            if !still_list {
                return Some(i);
            }
        }
        if is_ordered
            && tmp
                .find(". ")
                .is_none_or(|pos| tmp[..pos].parse::<u64>().is_err())
        {
            return Some(i);
        }
    }
    None
}

fn find_complete_footnote_end(lines: &[&str]) -> Option<usize> {
    let first = lines[0].trim();
    if !first.starts_with("[^") {
        return None;
    }
    let close_br = first.find("]:")?;
    if close_br <= 2 {
        return None;
    }
    for (i, tmp) in lines.iter().enumerate().skip(1) {
        if tmp.trim().is_empty() {
            // blank line ends footnote
            return Some(i + 1);
        }
        if !tmp.starts_with("    ") {
            return Some(i);
        }
    }
    None
}

fn is_definition_list_term(line: &str) -> bool {
    let l = line.trim();
    !l.starts_with('#')
        && !l.starts_with('>')
        && !l.starts_with('|')
        && !l.starts_with('-')
        && !l.starts_with('*')
        && !l.starts_with('`')
        && !l.is_empty()
}

fn is_html_block_tag(line: &str) -> bool {
    let l = line.trim();
    if !l.starts_with('<') {
        return false;
    }
    let rest = &l[1..];
    let tag_end = rest.find(|c: char| c == '>' || c.is_whitespace());
    let Some(tag_end) = tag_end else { return false };
    let tag = &rest[..tag_end];
    let lower = tag.to_lowercase();
    matches!(
        lower.as_str(),
        "div"
            | "pre"
            | "table"
            | "script"
            | "style"
            | "section"
            | "article"
            | "nav"
            | "footer"
            | "header"
            | "aside"
            | "main"
            | "blockquote"
            | "form"
            | "fieldset"
            | "details"
            | "dialog"
            | "figure"
            | "figcaption"
            | "dl"
            | "ol"
            | "ul"
            | "h1"
            | "h2"
            | "h3"
            | "h4"
            | "h5"
            | "h6"
    )
}

fn is_any_list_item(line: &str) -> bool {
    let l = line.trim();
    // Unordered
    if l.starts_with("* ") || l.starts_with("- ") || l.starts_with("+ ") {
        return true;
    }
    // Task
    if l.starts_with("- [ ] ")
        || l.starts_with("- [x] ")
        || l.starts_with("- [X] ")
        || l.starts_with("* [ ] ")
        || l.starts_with("* [x] ")
        || l.starts_with("* [X] ")
    {
        return true;
    }
    // Ordered
    l.find(". ")
        .is_some_and(|pos| l[..pos].parse::<u64>().is_ok())
}

fn is_footnote_line(line: &str) -> bool {
    let l = line.trim();
    if !l.starts_with("[^") {
        return false;
    }
    let close = l.find("]:");
    close.is_some_and(|c| c > 2)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_split_at_blank_line() {
        let (complete, remaining) = split_at_complete_boundary("hello\n\nworld");
        assert_eq!(complete, "hello");
        assert_eq!(remaining, "world");
    }

    #[test]
    fn test_split_no_boundary() {
        let (complete, remaining) = split_at_complete_boundary("hello world");
        assert_eq!(complete, "");
        assert_eq!(remaining, "hello world");
    }

    #[test]
    fn test_split_trailing_newline() {
        let (complete, remaining) = split_at_complete_boundary("hello\n");
        assert_eq!(complete, "hello\n");
        assert_eq!(remaining, "");
    }

    #[test]
    fn test_split_complete_fenced_block() {
        let input = "```rust\nlet x = 1;\n```\nsome text";
        let (complete, remaining) = split_at_complete_boundary(input);
        assert!(complete.contains("```"));
        assert!(complete.contains("```"));
        assert_eq!(remaining, "some text");
    }

    #[test]
    fn test_split_incomplete_fenced_block() {
        let input = "```rust\nlet x = 1;\nstill writing";
        let (complete, remaining) = split_at_complete_boundary(input);
        assert_eq!(complete, "");
        assert_eq!(remaining, input);
    }

    #[test]
    fn test_split_complete_table() {
        let input = "| a | b |\n|---|---|\n| 1 | 2 |\nnext";
        let (complete, remaining) = split_at_complete_boundary(input);
        assert!(complete.contains("| a"));
        assert!(!complete.ends_with('\n'));
        assert_eq!(remaining, "next");
    }

    #[test]
    fn test_split_complete_heading() {
        let (complete, remaining) = split_at_complete_boundary("### Hello\nmore");
        assert_eq!(complete, "### Hello\n");
        assert_eq!(remaining, "more");
    }

    #[test]
    fn test_stream_renderer_paragraph_then_flush() {
        let mut sr = StreamRenderer::new(80, ThemeMode::Dark);
        let lines = sr.push("Hello world.");
        assert!(lines.is_empty(), "unterminated paragraph should buffer");
        let remaining = sr.flush_remaining();
        assert!(!remaining.is_empty());
    }

    #[test]
    fn test_stream_renderer_incremental() {
        let mut sr = StreamRenderer::new(80, ThemeMode::Dark);
        let lines1 = sr.push("First paragraph.");
        assert!(lines1.is_empty() || lines1.iter().any(|l| l.contains("First")));
        let lines2 = sr.push("\n\nSecond paragraph.");
        assert!(!lines2.is_empty());
        let final_lines = sr.flush_remaining();
        assert!(!final_lines.is_empty() || lines2.iter().any(|l| l.contains("Second")));
    }

    #[test]
    fn test_stream_renderer_fenced_block() {
        let mut sr = StreamRenderer::new(80, ThemeMode::Dark);
        let lines1 = sr.push("```rust\nlet x = 1;\n```\n");
        assert!(!lines1.is_empty());
        let remaining = sr.flush_remaining();
        assert!(remaining.is_empty());
    }

    #[test]
    fn test_stream_renderer_table() {
        let mut sr = StreamRenderer::new(80, ThemeMode::Dark);
        assert!(
            sr.push("| a | b |\n").is_empty(),
            "header alone should buffer"
        );
        assert!(
            sr.push("|---|---|\n").is_empty(),
            "header+sep should buffer"
        );
        let lines = sr.push("| 1 | 2 |\n");
        assert!(!lines.is_empty(), "table with data rows should emit");
        assert!(lines.iter().any(|l| l.contains('') || l.contains('+')));
    }

    #[test]
    fn test_stream_renderer_table_partial_row_streams_cells() {
        let mut sr = StreamRenderer::new(80, ThemeMode::Dark);

        assert!(sr.push("| Lorem | Ipsum | Dolor |\n").is_empty());
        assert!(
            sr.push("|-------|-------|-------|").is_empty(),
            "header and separator should not render an empty table"
        );

        let partial_first_cell = sr.push("\n| Lor");
        assert!(
            partial_first_cell.iter().any(|line| line.contains("Lor")),
            "partial first cell should render as soon as row content arrives"
        );

        let partial_second_cell = sr.push("em ipsum | Sed");
        assert!(
            partial_second_cell
                .iter()
                .any(|line| line.contains("Lorem ipsum") && line.contains("Sed")),
            "partial second cell should render before the row is complete"
        );

        let complete_row = sr.push(" do | Ut enim |\n");
        assert!(
            complete_row
                .iter()
                .any(|line| line.contains("Lorem ipsum") && line.contains("Ut enim")),
            "complete row should remain rendered inside the table"
        );
    }

    #[test]
    fn test_stream_renderer_table_raw_llm_chunk_shape() {
        let mut sr = StreamRenderer::new(80, ThemeMode::Dark);
        let chunks = [
            "|", " Lorem", " |", " I", "psum", " |", " D", "olor", " |", "\n|", "-------", "|",
            "-------", "|", "-------", "|", "\n|", " Lorem", " ipsum", " dolor", " |", " Sed",
            " do", " |", " Ut", " enim", " |",
        ];

        let mut rendered = Vec::new();
        for chunk in chunks {
            rendered.extend(sr.push(chunk));
        }

        assert!(
            rendered
                .iter()
                .any(|line| line.contains("Lorem ipsum dolor")),
            "first streamed cell should appear before the final newline"
        );
        assert!(
            rendered.iter().any(|line| line.contains("Sed do")),
            "second streamed cell should appear before the final newline"
        );
        assert!(
            rendered.iter().any(|line| line.contains("Ut enim")),
            "third streamed cell should appear before the final newline"
        );
    }

    #[test]
    fn test_stream_renderer_ascii_borders() {
        let mut sr = StreamRenderer::new(80, ThemeMode::Dark).with_ascii_table_borders(true);
        sr.push("| a | b |\n");
        sr.push("|---|---|\n");
        let lines = sr.push("| 1 | 2 |\n");
        assert!(lines.iter().any(|l| l.contains('+')));
    }

    #[test]
    fn test_stream_renderer_code_theme() {
        let mut sr = StreamRenderer::new(80, ThemeMode::Dark).with_code_theme("base16-ocean.dark");
        let lines = sr.push("```rust\nlet x = 1;\n```\n");
        assert!(!lines.is_empty());
    }

    #[test]
    fn test_stream_renderer_table_updates() {
        let mut sr = StreamRenderer::new(80, ThemeMode::Dark);

        // Push table header and separator
        assert!(sr.push("| a | b |\n").is_empty());
        assert!(sr.push("|---|---|\n").is_empty());

        // Push first data row - should render table
        let lines1 = sr.push("| 1 | 2 |\n");
        assert!(!lines1.is_empty());
        assert!(lines1.iter().any(|l| l.contains('')));

        // Push second data row - should re-render table with both rows
        let lines2 = sr.push("| 3 | 4 |\n");
        assert!(!lines2.is_empty());
        assert!(
            lines2
                .first()
                .is_some_and(|line| line.starts_with("\x1B[5A\x1B[2K")),
            "refresh should move up and clear on the first rendered line"
        );
        assert!(lines2.iter().any(|l| l.contains('')));
    }

    #[test]
    fn test_stream_renderer_table_refresh_has_no_standalone_clear_lines() {
        let mut sr = StreamRenderer::new(80, ThemeMode::Dark);

        assert!(sr.push("| a | b |\n").is_empty());
        assert!(sr.push("|---|---|\n").is_empty());
        assert!(!sr.push("| 1 | 2 |\n").is_empty());

        let lines = sr.push("| 3 | 4 |\n");
        assert!(
            !lines.iter().any(|line| line == "\x1B[A\x1B[2K"),
            "standalone clear lines do not work with println-based callers"
        );
        assert!(
            lines.iter().all(|line| !line.trim().is_empty()),
            "refresh output should contain rendered table lines only"
        );
    }

    #[test]
    fn test_stream_renderer_table_trailing_content() {
        let mut sr = StreamRenderer::new(80, ThemeMode::Dark);

        // Push table header and separator
        assert!(sr.push("| a | b |\n").is_empty());
        assert!(sr.push("|---|---|\n").is_empty());

        // Push first data row - should render table
        sr.push("| 1 | 2 |\n");

        // Push second data row followed by a non-table line — this
        // terminates the table and renders it.
        let lines = sr.push("| 3 | 4 |\nsome trailing text");
        assert!(!lines.is_empty());
        assert!(lines.iter().any(|l| l.contains('')));

        // The trailing text is incomplete (no newline terminator)
        // and should not appear in this output.
        let plain_text: Vec<_> = lines
            .iter()
            .filter(|l| !l.starts_with('\x1B') && !l.trim().is_empty())
            .collect();
        for l in plain_text {
            assert!(
                !l.contains("trailing text"),
                "trailing text should not appear yet: {l}"
            );
        }

        // Complete the trailing text with a newline — now it should emit.
        let final_lines = sr.push("\n");
        assert!(
            final_lines.iter().any(|l| l.contains("trailing text")),
            "trailing text should render after a terminator"
        );
        assert!(sr.current_table.is_none(), "table should be closed");
    }

    #[test]
    fn test_stream_renderer_table_data_row_then_flush() {
        let mut sr = StreamRenderer::new(80, ThemeMode::Dark);

        // Push table header, separator, and a data row
        assert!(sr.push("| Header | Header2 |\n").is_empty());
        assert!(sr.push("|---|---|\n").is_empty());
        let lines = sr.push("| data1 | data2 |\n");
        assert!(!lines.is_empty(), "data row should trigger table emit");
        assert!(lines.iter().any(|l| l.contains('')));

        // Flush should finalize the table and NOT leak the data row
        let flushed = sr.flush_remaining();
        // Flushed should show the already-rendered table
        // and not contain raw data row text outside table borders
        let all_rendered: Vec<_> = lines.into_iter().chain(flushed).collect();
        let raw_data = all_rendered
            .iter()
            .any(|l| l.contains("data1") && !l.contains('') && !l.starts_with('\x1B'));
        assert!(
            !raw_data,
            "data row should only appear inside rendered table"
        );
    }
}