smart-markdown 0.2.3

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
use crate::parser::parse_document;
use crate::renderer::render_element_with_options;
use crate::ThemeMode;

/// 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,
}

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,
        }
    }

    /// 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);
        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 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 (complete, remaining) = split_at_complete_boundary(&self.buffer);
        if complete.is_empty() {
            return Vec::new();
        }

        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;

        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 = 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.
    // It's complete when a terminator follows data rows.
    if let Some(table_end) = find_complete_table_end(&lines) {
        let end_pos = 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
        && lines[0].trim().starts_with('|')
        && lines[0].trim().ends_with('|')
        && lines[1].trim().starts_with('|')
        && lines[1].trim().ends_with('|')
    {
        let sep = lines[1].trim();
        let is_separator = sep
            .chars()
            .filter(|&c| c != ' ' && c != '|' && c != '-' && c != ':')
            .count()
            == 0;
        if is_separator {
            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();
    if !l.starts_with('|') || !l.ends_with('|') {
        return false;
    }
    l.chars()
        .filter(|&c| c != ' ' && c != '|' && c != '-' && c != ':')
        .count()
        == 0
}

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();
    if !header.starts_with('|') || !header.ends_with('|')
        || !sep.starts_with('|') || !sep.ends_with('|')
    {
        return None;
    }
    let is_sep = sep
        .chars()
        .filter(|&c| c != ' ' && c != '|' && c != '-' && c != ':')
        .count()
        == 0;
    if !is_sep {
        return None;
    }
    let header_cols = header.split('|').filter(|s| !s.is_empty()).count();
    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;
        if !tmp.starts_with('|') || !tmp.ends_with('|') {
            return Some(i);
        }
        let cols = tmp.split('|').filter(|s| !s.is_empty()).count();
        if cols != header_cols {
            return Some(i);
        }
    }
    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);
        sr.push("| a | b |\n|---|---|\n| 1 | 2 |\n");
        let lines = sr.flush_remaining();
        assert!(!lines.is_empty());
        assert!(lines.iter().any(|l| l.contains('') || l.contains('+')));
    }

    #[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|---|---|\n| 1 | 2 |\n");
        let lines = sr.flush_remaining();
        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());
    }
}