revue 2.71.1

A Vue-style TUI framework for Rust with CSS styling
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
//! Markdown widget for rendering markdown content
//!
//! This module provides a comprehensive markdown renderer with syntax highlighting,
//! table of contents generation, and support for CommonMark syntax.
//!
//! ## Features
//!
//! - **Full CommonMark support** via pulldown-cmark
//! - **Syntax highlighting** for code blocks (via syntect)
//! - **Table of contents** generation
//! - **Admonitions** (note, tip, warning, danger)
//! - **Footnotes** support
//! - **Task lists** with checkboxes
//! - **Headings** with FIGLET big text option
//! - **Links** with styling
//! - **Block quotes** with styling
//! - **Code blocks** with line numbers
//! - **Horizontal rules**
//!
//! # Quick Start
//!
//! ```rust,ignore
//! use revue::prelude::*;
//!
//! let markdown = "# Welcome to Revue\n\nThis is **bold** and this is *italic*.\n\n## Features\n\n- CSS styling\n- Reactive state\n- 100+ widgets\n\n> Tip: Check out the docs!";
//!
//! markdown()
//!     .content(markdown)
//!     .width(60);
//! ```
//!
//! # Configuration
//!
//! ```rust,ignore
//! use revue::widget::markdown::MarkdownConfig;
//! use revue::style::Color;
//!
//! let config = MarkdownConfig {
//!     link_fg: Color::CYAN,
//!     code_fg: Color::YELLOW,
//!     heading_fg: Color::WHITE,
//!     quote_fg: PLACEHOLDER_FG,
//!     show_toc: true,
//!     syntax_highlight: true,
//!     code_line_numbers: true,
//!     ..Default::default()
//! };
//! ```

#![allow(missing_docs)]

mod helpers;
pub mod parser;
pub mod types;

use crate::render::{Cell, Modifier};
use crate::style::Color;
use crate::utils::figlet::FigletFont;
use crate::utils::syntax::{Language, SyntaxTheme};
use crate::widget::theme::{DARK_GRAY, DISABLED_FG, PLACEHOLDER_FG};
use crate::widget::traits::{RenderContext, View, WidgetProps};
use crate::{impl_props_builders, impl_styled_view};

pub use types::{AdmonitionType, FootnoteDefinition, Line, StyledText, TocEntry};

// Re-export helpers
pub use helpers::markdown;

// Import pulldown-cmark types for parser
#[cfg(feature = "markdown")]
use pulldown_cmark::{CodeBlockKind, Tag, TagEnd};

/// Markdown configuration options
#[derive(Clone, Debug)]
pub struct MarkdownConfig {
    pub link_fg: Color,
    pub code_fg: Color,
    pub heading_fg: Color,
    pub quote_fg: Color,
    pub toc_fg: Color,
    pub figlet_font: Option<FigletFont>,
    pub figlet_max_level: u8,
    pub show_toc: bool,
    pub toc_title: String,
    pub syntax_highlight: bool,
    pub syntax_theme: SyntaxTheme,
    pub code_line_numbers: bool,
    pub code_border: bool,
}

impl Default for MarkdownConfig {
    fn default() -> Self {
        Self {
            link_fg: Color::CYAN,
            code_fg: Color::YELLOW,
            heading_fg: Color::WHITE,
            quote_fg: PLACEHOLDER_FG,
            toc_fg: Color::CYAN,
            figlet_font: None,
            figlet_max_level: 1,
            show_toc: false,
            toc_title: "Table of Contents".to_string(),
            syntax_highlight: true,
            syntax_theme: SyntaxTheme::monokai(),
            code_line_numbers: false,
            code_border: true,
        }
    }
}

/// A markdown widget for rendering markdown content
pub struct Markdown {
    pub source: String,
    pub lines: Vec<Line>,
    pub toc: Vec<TocEntry>,
    pub config: MarkdownConfig,
    pub props: WidgetProps,
}

impl Markdown {
    /// Create a new markdown widget
    pub fn new(source: impl Into<String>) -> Self {
        let source = source.into();
        let toc = Self::extract_toc(&source);
        let config = MarkdownConfig::default();
        let mut md = Self {
            source,
            lines: Vec::new(),
            toc,
            config,
            props: WidgetProps::new(),
        };
        md.lines = md.parse_with_options();
        md
    }

    /// Extract table of contents from markdown source
    fn extract_toc(source: &str) -> Vec<TocEntry> {
        #[cfg(feature = "markdown")]
        use pulldown_cmark::{Event, HeadingLevel, Options, Parser, Tag, TagEnd};

        let mut options = Options::empty();
        options.insert(Options::ENABLE_TABLES);
        options.insert(Options::ENABLE_TASKLISTS);
        options.insert(Options::ENABLE_STRIKETHROUGH);
        options.insert(Options::ENABLE_FOOTNOTES);

        let parser = Parser::new_ext(source, options);
        let mut toc = Vec::new();
        let mut in_heading = false;
        let mut heading_level: u8 = 1;
        let mut heading_text = String::new();

        for event in parser {
            match event {
                Event::Start(Tag::Heading { level, .. }) => {
                    in_heading = true;
                    heading_level = match level {
                        HeadingLevel::H1 => 1,
                        HeadingLevel::H2 => 2,
                        HeadingLevel::H3 => 3,
                        HeadingLevel::H4 => 4,
                        HeadingLevel::H5 => 5,
                        HeadingLevel::H6 => 6,
                    };
                    heading_text.clear();
                }
                Event::End(TagEnd::Heading(_)) => {
                    if in_heading && !heading_text.is_empty() {
                        toc.push(TocEntry {
                            level: heading_level,
                            text: heading_text.clone(),
                        });
                    }
                    in_heading = false;
                }
                Event::Text(text) if in_heading => {
                    heading_text.push_str(text.as_ref());
                }
                _ => {}
            }
        }

        toc
    }

    /// Get the table of contents
    pub fn toc(&self) -> &[TocEntry] {
        &self.toc
    }

    /// Parse markdown into styled lines with current options
    fn parse_with_options(&self) -> Vec<Line> {
        #[allow(unused_imports)]
        #[cfg(feature = "markdown")]
        use pulldown_cmark::{Event, HeadingLevel, Parser, Tag, TagEnd};

        let parser = Parser::new_ext(&self.source, parser::ParserContext::parser_options());
        let mut ctx = parser::ParserContext::new(&self.source, &self.config);

        for event in parser {
            match event {
                Event::Start(tag) => self.handle_start_tag(&mut ctx, tag),
                Event::End(tag_end) => self.handle_end_tag(&mut ctx, tag_end),
                Event::Text(text) => self.handle_text(&mut ctx, &text),
                Event::Code(text) => self.handle_code(&mut ctx, &text),
                Event::Html(text) => self.handle_html(&mut ctx, &text),
                Event::FootnoteReference(text) => self.handle_footnote_reference(&mut ctx, &text),
                Event::Rule => {
                    ctx.flush_line();
                    let rule_line = Line::new();
                    ctx.lines.push(rule_line);
                }
                Event::SoftBreak => {
                    if ctx.in_blockquote || ctx.current_admonition.is_some() {
                        ctx.flush_line();
                        ctx.new_line();
                    } else {
                        ctx.add_text(" ");
                    }
                }
                Event::HardBreak => {
                    ctx.flush_line();
                    ctx.new_line();
                }
                Event::TaskListMarker(checked) => {
                    // Task list item - add checkbox
                    if checked {
                        ctx.add_text("[x] ");
                    } else {
                        ctx.add_text("[ ] ");
                    }
                    ctx.item_needs_bullet = false;
                }
                // Handle remaining events
                _ => {}
            }
        }

        // Render footnotes at the end if any
        if !ctx.footnote_definitions.is_empty() {
            ctx.new_line();
            ctx.flush_line();

            // Separator
            let mut sep_line = Line::new();
            sep_line.push(
                StyledText::new("────────────────────────────────────────").with_fg(DARK_GRAY),
            );
            ctx.lines.push(sep_line);
            ctx.new_line();

            // Sort footnotes by reference number
            let mut sorted_definitions: Vec<_> = ctx.footnote_definitions.iter().collect();
            sorted_definitions
                .sort_by_key(|d| ctx.footnote_label_map.get(&d.label).copied().unwrap_or(999));

            for (idx, def) in sorted_definitions.iter().enumerate() {
                let mut footnote_line = Line::new();
                footnote_line.push(
                    StyledText::new(format!("[{}] ", idx + 1))
                        .with_fg(ctx.link_fg)
                        .with_modifier(Modifier::BOLD),
                );
                footnote_line.push(StyledText::new(&def.content));
                ctx.lines.push(footnote_line);
            }
        }

        while ctx.lines.last().map(|l| l.is_empty()).unwrap_or(false) {
            ctx.lines.pop();
        }

        ctx.lines
    }

    fn handle_start_tag(&self, ctx: &mut parser::ParserContext, tag: Tag) {
        match tag {
            Tag::Heading { level, .. } => {
                ctx.in_heading = true;
                ctx.heading_level = match level {
                    pulldown_cmark::HeadingLevel::H1 => 1,
                    pulldown_cmark::HeadingLevel::H2 => 2,
                    pulldown_cmark::HeadingLevel::H3 => 3,
                    pulldown_cmark::HeadingLevel::H4 => 4,
                    pulldown_cmark::HeadingLevel::H5 => 5,
                    pulldown_cmark::HeadingLevel::H6 => 6,
                };
                ctx.heading_text.clear();
                ctx.current_modifier |= Modifier::BOLD;
                ctx.current_fg = Some(ctx.heading_fg);
            }
            Tag::Strong => {
                ctx.current_modifier |= Modifier::BOLD;
            }
            Tag::Emphasis => {
                ctx.current_modifier |= Modifier::ITALIC;
            }
            Tag::Strikethrough => {
                // Strikethrough not supported by terminal modifier
            }
            Tag::Link { .. } => {
                ctx.current_fg = Some(ctx.link_fg);
                ctx.current_modifier |= Modifier::UNDERLINE;
            }
            Tag::Image { .. } => {
                ctx.current_fg = Some(ctx.link_fg);
            }
            Tag::CodeBlock(kind) => {
                ctx.in_code_block = true;
                match kind {
                    CodeBlockKind::Fenced(_) => {
                        // Language will be determined from the next event
                    }
                    CodeBlockKind::Indented => {}
                }
            }
            Tag::List(num) => {
                ctx.list_depth += 1;
                ctx.ordered_list_num = num;
            }
            Tag::Item => {
                let indent = "  ".repeat(ctx.list_depth.saturating_sub(1));
                ctx.add_text(&indent);

                // For ordered lists, add the number now
                if let Some(n) = ctx.ordered_list_num {
                    ctx.ordered_list_num = Some(n + 1);
                    ctx.add_text(&format!("{}. ", n));
                    ctx.item_needs_bullet = false;
                } else {
                    // For unordered lists, wait to see if it's a task list
                    ctx.item_needs_bullet = true;
                }
            }
            Tag::Paragraph => {
                // Start new line if not empty
                ctx.flush_line();
            }
            Tag::Table(_) | Tag::TableHead | Tag::TableRow | Tag::TableCell => {
                ctx.in_table = true;
                if matches!(tag, Tag::TableHead) {
                    ctx.in_table_head = true;
                }
            }
            Tag::FootnoteDefinition(name) => {
                ctx.in_footnote_definition = true;
                ctx.current_footnote_label = name.to_string();
                ctx.current_footnote_content.clear();
            }
            Tag::BlockQuote(_) => {
                ctx.in_blockquote = true;
                ctx.blockquote_first_text = true;
                ctx.current_admonition = None;
            }
            _ => {}
        }
    }

    fn handle_end_tag(&self, ctx: &mut parser::ParserContext, tag_end: TagEnd) {
        match tag_end {
            TagEnd::Heading(_) => {
                // Add the heading text to the current line
                if !ctx.heading_text.is_empty() {
                    let text = ctx.heading_text.clone();
                    ctx.add_text(&text);
                }
                ctx.in_heading = false;
                ctx.current_modifier &= !Modifier::BOLD;
                ctx.current_fg = None;
                ctx.new_line();
            }
            TagEnd::Paragraph => {
                ctx.flush_line();
                ctx.new_line();
            }
            TagEnd::Strong => {
                ctx.current_modifier &= !Modifier::BOLD;
            }
            TagEnd::Emphasis => {
                ctx.current_modifier &= !Modifier::ITALIC;
            }
            TagEnd::Strikethrough => {
                ctx.current_modifier &= !Modifier::CROSSED_OUT;
            }
            TagEnd::Link => {
                ctx.current_fg = None;
                ctx.current_modifier &= !Modifier::UNDERLINE;
            }
            TagEnd::CodeBlock => {
                self.render_code_block(ctx);
            }
            TagEnd::FootnoteDefinition => {
                ctx.footnote_definitions.push(FootnoteDefinition {
                    label: ctx.current_footnote_label.clone(),
                    content: ctx.current_footnote_content.clone(),
                });
                ctx.in_footnote_definition = false;
            }
            TagEnd::BlockQuote(_) => {
                ctx.in_blockquote = false;
                ctx.flush_line();
                // Add empty line after admonition
                if ctx.current_admonition.is_some() {
                    ctx.lines.push(std::mem::take(&mut ctx.current_line));
                    let empty_line = Line::new();
                    ctx.lines.push(empty_line);
                }
                ctx.current_admonition = None;
                ctx.accumulated_blockquote.clear();
            }
            TagEnd::List(_) => {
                ctx.list_depth = ctx.list_depth.saturating_sub(1);
                ctx.flush_line();
            }
            TagEnd::Item => {
                // Add bullet if needed (wasn't a task list)
                if ctx.item_needs_bullet {
                    ctx.add_text("â€ĸ ");
                }
                ctx.flush_line();
                ctx.item_needs_bullet = false;
            }
            _ => {}
        }
    }

    fn handle_text(&self, ctx: &mut parser::ParserContext, text: &str) {
        if ctx.in_code_block {
            ctx.code_block_lines.push(text.to_string());
        } else if ctx.in_footnote_definition {
            ctx.current_footnote_content.push_str(text);
        } else if ctx.in_table {
            ctx.current_cell.push_str(text);
        } else if ctx.in_heading {
            ctx.heading_text.push_str(text);
        } else if ctx.blockquote_first_text {
            // Accumulate text for admonition detection
            ctx.accumulated_blockquote.push_str(text);

            // Try to detect admonition marker
            let full_text = ctx.accumulated_blockquote.trim().to_string();
            if let Some(admonition) = AdmonitionType::from_marker(&full_text) {
                ctx.current_admonition = Some(admonition);
                ctx.flush_line();
                // Render admonition header with icon and label
                let color = admonition.color();
                ctx.current_fg = Some(color);
                ctx.current_modifier |= Modifier::BOLD;
                ctx.add_text(&format!("{} {}", admonition.icon(), admonition.label()));
                ctx.new_line();
                ctx.accumulated_blockquote.clear();
                ctx.blockquote_first_text = false;
            } else {
                // Not a complete admonition marker yet, keep accumulating
                if !full_text.ends_with(']') {
                    // If text doesn't contain '[', it's definitely not an admonition
                    if !full_text.contains('[') {
                        ctx.flush_line();
                        let color = ctx.quote_fg;
                        ctx.current_modifier |= Modifier::ITALIC;
                        ctx.current_fg = Some(color);
                        ctx.add_text("│ ");
                        ctx.add_text(&full_text);
                        ctx.accumulated_blockquote.clear();
                        ctx.blockquote_first_text = false;
                    }
                    // Otherwise keep accumulating
                } else {
                    // Complete text but not an admonition
                    ctx.flush_line();
                    let color = ctx.quote_fg;
                    ctx.current_modifier |= Modifier::ITALIC;
                    ctx.current_fg = Some(color);
                    ctx.add_text("│ ");
                    ctx.add_text(&full_text);
                    ctx.accumulated_blockquote.clear();
                    ctx.blockquote_first_text = false;
                }
            }
        } else if let Some(_admonition) = ctx.current_admonition {
            // Admonition content - add quote prefix
            ctx.add_text(&format!("│ {}", text));
        } else if ctx.in_blockquote {
            // Regular blockquote continuation
            ctx.add_text(&format!("│ {}", text));
        } else {
            ctx.add_text(text);
        }
    }

    fn handle_code(&self, ctx: &mut parser::ParserContext, text: &str) {
        if !ctx.in_code_block {
            ctx.add_text(text);
        }
    }

    fn handle_html(&self, ctx: &mut parser::ParserContext, text: &str) {
        if let Some(admonition) = AdmonitionType::from_marker(text) {
            ctx.current_admonition = Some(admonition);
            ctx.flush_line();
            // Render admonition header with icon and label
            let color = admonition.color();
            ctx.current_fg = Some(color);
            ctx.current_modifier |= Modifier::BOLD;
            ctx.add_text(&format!("{} {}", admonition.icon(), admonition.label()));
            ctx.new_line();
            ctx.blockquote_first_text = false;
        }
    }

    fn handle_footnote_reference(&self, ctx: &mut parser::ParserContext, text: &str) {
        // Track footnote references
        if !ctx.footnote_label_map.contains_key(text) {
            ctx.footnote_counter += 1;
            ctx.footnote_label_map
                .insert(text.to_string(), ctx.footnote_counter);
        }

        let num = ctx.footnote_label_map.get(text).copied().unwrap_or(1);
        ctx.add_text(&format!("[^{}]", num));
    }

    fn render_code_block(&self, ctx: &mut parser::ParserContext) {
        ctx.in_code_block = false;
        ctx.new_line();

        // Code border
        if ctx.code_border {
            let mut border_line = Line::new();
            border_line.push(StyledText::new("┌").with_fg(DISABLED_FG));
            for _ in 0..30 {
                border_line.push(StyledText::new("─").with_fg(DISABLED_FG));
            }
            border_line.push(StyledText::new("┐").with_fg(DISABLED_FG));
            ctx.lines.push(border_line);
        }

        for (line_num, line) in ctx.code_block_lines.iter().enumerate() {
            let mut code_line = Line::new();

            if ctx.code_line_numbers {
                code_line
                    .push(StyledText::new(format!("{:3} │ ", line_num + 1)).with_fg(DISABLED_FG));
            } else if ctx.code_border {
                code_line.push(StyledText::new("│ ").with_fg(DISABLED_FG));
            }

            // Apply syntax highlighting if enabled
            if ctx.syntax_highlight && ctx.code_block_lang != Language::Unknown {
                let tokens = ctx.highlighter.highlight_line(line, ctx.code_block_lang);
                if !tokens.is_empty() {
                    // Render highlighted code - tokens contain the text directly
                    for token in &tokens {
                        let fg = ctx.highlighter.token_color(token.token_type);
                        code_line.push(StyledText::new(token.text.clone()).with_fg(fg));
                    }
                } else {
                    code_line.push(StyledText::new(line.clone()).with_fg(ctx.code_fg));
                }
            } else {
                code_line.push(StyledText::new(line.clone()).with_fg(ctx.code_fg));
            }

            ctx.lines.push(code_line);
        }

        ctx.code_block_lines.clear();

        if ctx.code_border {
            let mut border_line = Line::new();
            border_line.push(StyledText::new("└").with_fg(DISABLED_FG));
            for _ in 0..30 {
                border_line.push(StyledText::new("─").with_fg(DISABLED_FG));
            }
            border_line.push(StyledText::new("┘").with_fg(DISABLED_FG));
            ctx.lines.push(border_line);
        }

        ctx.new_line();
    }

    // Builder methods for configuration
    pub fn show_toc(mut self, show: bool) -> Self {
        self.config.show_toc = show;
        self.lines = self.parse_with_options();
        self
    }

    pub fn toc_title(mut self, title: impl Into<String>) -> Self {
        self.config.toc_title = title.into();
        self.lines = self.parse_with_options();
        self
    }

    pub fn toc_fg(mut self, color: Color) -> Self {
        self.config.toc_fg = color;
        self.lines = self.parse_with_options();
        self
    }

    pub fn figlet_headings(mut self, enable: bool) -> Self {
        self.config.figlet_font = if enable {
            Some(crate::utils::figlet::FigletFont::Block)
        } else {
            None
        };
        self.lines = self.parse_with_options();
        self
    }

    pub fn link_fg(mut self, color: Color) -> Self {
        self.config.link_fg = color;
        self.lines = self.parse_with_options();
        self
    }

    pub fn code_fg(mut self, color: Color) -> Self {
        self.config.code_fg = color;
        self.lines = self.parse_with_options();
        self
    }

    pub fn heading_fg(mut self, color: Color) -> Self {
        self.config.heading_fg = color;
        self.lines = self.parse_with_options();
        self
    }

    pub fn syntax_highlight(mut self, enable: bool) -> Self {
        self.config.syntax_highlight = enable;
        self.lines = self.parse_with_options();
        self
    }

    pub fn syntax_theme(mut self, theme: SyntaxTheme) -> Self {
        self.config.syntax_theme = theme;
        self.lines = self.parse_with_options();
        self
    }

    pub fn code_line_numbers(mut self, enable: bool) -> Self {
        self.config.code_line_numbers = enable;
        self.lines = self.parse_with_options();
        self
    }

    pub fn code_border(mut self, enable: bool) -> Self {
        self.config.code_border = enable;
        self.lines = self.parse_with_options();
        self
    }

    /// Get source markdown
    pub fn source(&self) -> &str {
        &self.source
    }

    /// Get rendered line count
    pub fn line_count(&self) -> usize {
        self.lines.len()
    }
}

impl Default for Markdown {
    fn default() -> Self {
        Self::new("")
    }
}

impl View for Markdown {
    crate::impl_view_meta!("Markdown");

    fn render(&self, ctx: &mut RenderContext) {
        let area = ctx.area;
        if area.width < 1 || area.height < 1 {
            return;
        }

        for (y, line) in self.lines.iter().enumerate() {
            if y as u16 >= area.height {
                break;
            }

            let mut x: u16 = 0;
            for segment in &line.segments {
                for ch in segment.text.chars() {
                    let cw = crate::utils::char_width(ch) as u16;
                    if x + cw > area.width {
                        break;
                    }
                    let mut cell = Cell::new(ch);
                    cell.fg = segment.fg;
                    cell.bg = segment.bg;
                    cell.modifier = segment.modifier;
                    ctx.set(x, y as u16, cell);
                    x += cw;
                }
            }
        }
    }
}

impl_styled_view!(Markdown);
impl_props_builders!(Markdown);

// KEEP HERE - Private implementation tests (AdmonitionType internals: from_marker, icon, label, color)
// Public API tests extracted to tests/widget/markdown/markdown_tests.rs
#[cfg(test)]
mod tests {
    //! Markdown widget private implementation tests

    use super::*;
    use crate::style::Color;

    #[test]
    fn test_admonition_type_from_marker() {
        assert_eq!(
            AdmonitionType::from_marker("[!NOTE]"),
            Some(AdmonitionType::Note)
        );
        assert_eq!(
            AdmonitionType::from_marker("[!TIP]"),
            Some(AdmonitionType::Tip)
        );
        assert_eq!(
            AdmonitionType::from_marker("[!IMPORTANT]"),
            Some(AdmonitionType::Important)
        );
        assert_eq!(
            AdmonitionType::from_marker("[!WARNING]"),
            Some(AdmonitionType::Warning)
        );
        assert_eq!(
            AdmonitionType::from_marker("[!CAUTION]"),
            Some(AdmonitionType::Caution)
        );
        assert_eq!(
            AdmonitionType::from_marker("[!note]"),
            Some(AdmonitionType::Note)
        );
        assert_eq!(AdmonitionType::from_marker("NOTE"), None);
        assert_eq!(AdmonitionType::from_marker("[NOTE]"), None);
        assert_eq!(AdmonitionType::from_marker("[!UNKNOWN]"), None);
    }

    #[test]
    fn test_admonition_icon() {
        assert_eq!(AdmonitionType::Note.icon(), "â„šī¸ ");
        assert_eq!(AdmonitionType::Tip.icon(), "💡");
        assert_eq!(AdmonitionType::Important.icon(), "❗");
        assert_eq!(AdmonitionType::Warning.icon(), "âš ī¸ ");
        assert_eq!(AdmonitionType::Caution.icon(), "🔴");
    }

    #[test]
    fn test_admonition_label() {
        assert_eq!(AdmonitionType::Note.label(), "Note");
        assert_eq!(AdmonitionType::Tip.label(), "Tip");
        assert_eq!(AdmonitionType::Important.label(), "Important");
        assert_eq!(AdmonitionType::Warning.label(), "Warning");
        assert_eq!(AdmonitionType::Caution.label(), "Caution");
    }

    #[test]
    fn test_admonition_color() {
        assert_ne!(AdmonitionType::Note.color(), Color::BLACK);
        assert_ne!(AdmonitionType::Tip.color(), Color::BLACK);
        assert_ne!(AdmonitionType::Important.color(), Color::BLACK);
        assert_ne!(AdmonitionType::Warning.color(), Color::BLACK);
        assert_ne!(AdmonitionType::Caution.color(), Color::BLACK);
    }
}