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
//! Parse and render Markdown to ANSI-styled terminal output.
//!
//! # Quick start
//!
//! One-shot rendering to a string:
//!
//! ```rust
//! use smart_markdown::render_to_string;
//!
//! let output = render_to_string("# Hello\n\n**bold** and *italic*\n", 80);
//! println!("{output}");
//! ```
//!
//! Live in-place terminal rendering with cursor control:
//!
//! ```rust
//! use smart_markdown::Markdown;
//!
//! let mut md = Markdown::parse("# Loading...\n\n*please wait*");
//! md.render(); // prints to stdout with ANSI escape codes
//!
//! // Update content and re-render in-place
//! // (requires modifying parsed elements — see append_to_cell, set_cell_content)
//! ```
//!
//! Streaming LLM output with real-time table updates:
//!
//! ```rust
//! use smart_markdown::{StreamRenderer, ThemeMode, is_light_terminal};
//!
//! let width = 80;
//! let theme = if is_light_terminal() { ThemeMode::Light } else { ThemeMode::Dark };
//! let mut sr = StreamRenderer::new(width, theme)
//!     .with_ascii_table_borders(true);
//!
//! // Feed chunks as they arrive from the LLM
//! for line in sr.push("# Hello\n\n") {
//!     println!("{line}");
//! }
//! for line in sr.push("| Name | Value |\n") {
//!     println!("{line}");
//! }
//! for line in sr.push("|------|-------|\n") {
//!     println!("{line}");
//! }
//! // Table will render and re-render as new rows are added
//! for line in sr.push("| CPU  | 45%   |\n") {
//!     println!("{line}");
//! }
//! for line in sr.push("| Mem  | 67%   |\n") {
//!     println!("{line}");
//! }
//! for line in sr.flush_remaining() {
//!     println!("{line}");
//! }
//! ```

mod elements;
#[cfg(feature = "syntax-highlight")]
pub mod highlight;
mod parser;
mod renderer;
mod stream_renderer;

use elements::*;
use parser::parse_document;
use renderer::render_element;

pub use stream_renderer::StreamRenderer;

#[cfg(feature = "syntax-highlight")]
pub use highlight::ThemeMode;

#[cfg(not(feature = "syntax-highlight"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ThemeMode {
    Dark,
    Light,
    Auto,
}

/// A parsed Markdown document with support for live in-place terminal rendering.
///
/// `Markdown` parses markdown text into an internal element tree, then renders it
/// with ANSI escape codes. It tracks line counts between renders so subsequent
/// calls to [`render`](Self::render) overwrite the previous output in-place
/// using terminal cursor control sequences.
///
/// # Examples
///
/// ```rust
/// use smart_markdown::{Markdown, ThemeMode};
///
/// let mut md = Markdown::parse("## Status\n\n**Running...**")
///     .theme_mode(ThemeMode::Dark)
///     .code_theme("base16-ocean.dark");
///
/// md.render(); // outputs to stdout
///
/// // Update a table cell and re-render
/// md.set_cell_content(0, 1, "new data");
/// md.render(); // overwrites previous output in-place
/// ```
pub struct Markdown {
    elements: Vec<MarkdownElement>,
    last_width: usize,
    last_rendered_lines: usize,
    has_rendered: bool,
    theme_mode: ThemeMode,
    code_theme: Option<String>,
}

impl Markdown {
    /// Parse a markdown string into a `Markdown` document.
    ///
    /// Supports: headings (ATX and setext), paragraphs, fenced/indented code blocks,
    /// blockquotes, ordered/unordered/task lists, tables, definition lists,
    /// horizontal rules, HTML blocks, footnotes, and reference links.
    pub fn parse(text: &str) -> Self {
        Markdown {
            elements: parse_document(text),
            last_width: 0,
            last_rendered_lines: 0,
            has_rendered: false,
            theme_mode: ThemeMode::Auto,
            code_theme: None,
        }
    }

    /// Set the syntax highlighting theme mode.
    ///
    /// When the `syntax-highlight` feature is enabled (on by default),
    /// this controls which syntect color theme is used for fenced code blocks.
    /// - `ThemeMode::Dark` — "Base16 Eighties Dark"
    /// - `ThemeMode::Light` — "Solarized (light)"
    /// - `ThemeMode::Auto` — detects terminal background color at render time
    pub fn theme_mode(mut self, mode: ThemeMode) -> Self {
        self.theme_mode = mode;
        self
    }

    /// Override the syntax highlighting theme by name.
    ///
    /// See [`highlight::list_themes`] for available theme names.
    /// When the `syntax-highlight` feature is disabled, this has no effect.
    pub fn code_theme(mut self, theme: &str) -> Self {
        self.code_theme = Some(theme.to_string());
        self
    }

    /// Returns `true` if the terminal width has changed since the last render.
    ///
    /// Useful for deciding whether to re-render on SIGWINCH.
    pub fn has_terminal_resized(&self) -> bool {
        let current = current_terminal_width();
        current != self.last_width && self.last_width > 0
    }

    /// Append text to a table cell identified by row and column index.
    ///
    /// Panics if the document doesn't contain a table or the indices are out of bounds.
    pub fn append_to_cell(&mut self, row: usize, col: usize, text: &str) {
        for elem in &mut self.elements {
            if let MarkdownElement::Table(td) = elem {
                if row < td.rows.len() && col < td.headers.len() {
                    td.rows[row][col].push_str(text);
                }
                return;
            }
        }
    }

    /// Replace the content of a table cell identified by row and column index.
    ///
    /// Panics if the document doesn't contain a table or the indices are out of bounds.
    pub fn set_cell_content(&mut self, row: usize, col: usize, text: &str) {
        for elem in &mut self.elements {
            if let MarkdownElement::Table(td) = elem {
                if row < td.rows.len() && col < td.headers.len() {
                    td.rows[row][col] = text.to_string();
                }
                return;
            }
        }
    }

    /// Render the document to stdout with ANSI escape codes.
    ///
    /// On first call, output is simply printed. On subsequent calls, the previous
    /// output is overwritten in-place using cursor-up and line-clear sequences.
    /// Lines that shrink between renders are properly cleared.
    pub fn render(&mut self) {
        let width = current_terminal_width();
        let mode = self.theme_mode;
        let mut output: Vec<String> = Vec::new();

        for elem in &self.elements {
            let lines = render_element(elem, width, mode, self.code_theme.as_deref());
            output.extend(lines);
        }

        let new_line_count = output.len();

        if self.has_rendered {
            print!("\x1b[{}A", self.last_rendered_lines);
        }

        for line in &output {
            if self.has_rendered {
                print!("\x1b[2K\r");
            }
            println!("{line}");
        }

        if self.has_rendered && new_line_count < self.last_rendered_lines {
            for _ in new_line_count..self.last_rendered_lines {
                print!("\x1b[2K\r");
                println!();
            }
            if self.last_rendered_lines > new_line_count {
                print!(
                    "\x1b[{}A",
                    self.last_rendered_lines.saturating_sub(new_line_count)
                );
            }
        }

        self.last_rendered_lines = new_line_count;
        self.last_width = width;
        self.has_rendered = true;
    }
}

/// Render a markdown string to a single `String` with ANSI styling.
///
/// This is a stateless convenience function that parses the input, renders
/// each element, and joins with `\n`. For incremental rendering with terminal
/// cursor control, use [`Markdown::render`] or [`StreamRenderer`].
///
/// Always uses `ThemeMode::Auto` and no custom code theme.
pub fn render_to_string(markdown: &str, width: usize) -> String {
    let elements = parse_document(markdown);
    let mut output: Vec<String> = Vec::new();
    for elem in &elements {
        output.extend(render_element(elem, width, ThemeMode::Auto, None));
    }
    output.join("\n")
}

fn current_terminal_width() -> usize {
    terminal_size::terminal_size()
        .map(|(w, _)| w.0 as usize)
        .unwrap_or(80)
}

/// Returns `true` if the terminal background is light-colored.
///
/// Checks the `COLORFGBG` environment variable (set by many terminal
/// emulators). Returns `false` if the variable is unset or unparseable,
/// defaulting to a dark-background assumption.
pub fn is_light_terminal() -> bool {
    if let Ok(colorfgbg) = std::env::var("COLORFGBG") {
        let parts: Vec<&str> = colorfgbg.split(';').collect();
        if let Some(bg) = parts.get(1)
            && let Ok(bg_num) = bg.parse::<u8>()
        {
            return bg_num >= 7;
        }
    }
    false
}

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

    #[test]
    fn parse_heading_setext_level_1() {
        let result = render_to_string("Hello\n=====\n", 40);
        assert!(result.contains("Hello"));
        assert!(result.contains(""));
    }

    #[test]
    fn parse_heading_setext_level_2() {
        let result = render_to_string("Hello\n-----\n", 40);
        assert!(result.contains("Hello"));
        assert!(result.contains(""));
    }

    #[test]
    fn parse_heading_atx() {
        let result = render_to_string("### Level 3\n", 40);
        assert!(result.contains("Level 3"));
        assert!(result.contains(""));
    }

    #[test]
    fn parse_bold_and_italic() {
        let result = render_to_string("**bold** and *italic*\n", 40);
        assert!(result.contains("\x1b[1mbold\x1b[0m"));
        assert!(result.contains("\x1b[3mitalic\x1b[0m"));
    }

    #[test]
    fn parse_strikethrough() {
        let result = render_to_string("~~deleted~~\n", 40);
        assert!(result.contains("\x1b[9mdeleted\x1b[0m"));
    }

    #[test]
    fn parse_inline_code() {
        let result = render_to_string("`code`\n", 40);
        assert!(result.contains("\x1b[7m code \x1b[0m"));
    }

    #[test]
    fn parse_link() {
        let result = render_to_string("[example](https://example.com)\n", 40);
        assert!(result.contains("\x1b[4mexample\x1b[0m"));
    }

    #[test]
    fn parse_unordered_list() {
        let result = render_to_string("- one\n- two\n- three\n", 40);
        assert_eq!(result.lines().filter(|l| l.starts_with("")).count(), 3);
    }

    #[test]
    fn parse_ordered_list() {
        let result = render_to_string("1. first\n2. second\n3. third\n", 40);
        assert_eq!(result.lines().filter(|l| l.starts_with("1.")).count(), 1);
        assert_eq!(result.lines().filter(|l| l.starts_with("2.")).count(), 1);
    }

    #[test]
    fn parse_table() {
        let result = render_to_string("| a | b |\n|---|---|\n| 1 | 2 |\n| 3 | 4 |\n", 80);
        assert!(result.contains("│ a"));
        assert!(result.contains("│ 1"));
    }

    #[test]
    fn parse_code_block() {
        let result = render_to_string("```\nlet x = 1;\n```\n", 80);
        assert!(result.contains("let x = 1;"));
    }

    #[test]
    fn parse_blockquote() {
        let result = render_to_string("> quoted text here\n", 40);
        assert!(result.contains("quoted text here"));
    }

    #[test]
    fn parse_horizontal_rule() {
        let result = render_to_string("---\n", 40);
        assert!(result.starts_with(""));
    }

    #[test]
    fn markdown_parse_and_streaming() {
        let mut md = Markdown::parse("| col |\n|-----|\n| a   |\n");
        md.append_to_cell(0, 0, "ppended");
        let after = render_to_string("| col |\n|-----|\n| appended |\n", 80);
        assert!(after.contains("appended"));
    }

    #[test]
    fn set_cell_content_replaces() {
        let mut md = Markdown::parse("| col |\n|-----|\n| old |\n");
        md.set_cell_content(0, 0, "new");
        let result = render_to_string("| col |\n|-----|\n| new |\n", 80);
        assert!(result.contains("new"));
        assert!(!result.contains("old"));
    }

    #[test]
    fn table_fill_column() {
        let result = render_to_string("| a |  |\n|---|---|\n| 1 |  |\n", 100);
        assert!(result.contains("│ a"));
    }

    #[test]
    fn indented_table_render() {
        let input = "  | Name | Desc |\n  |---|---|\n  | A | B |\n";
        let result = render_to_string(input, 80);
        assert!(result.contains(""), "no top border: {result}");
        assert!(result.contains("Name"), "no Name header: {result}");
        assert!(result.contains("A"), "no data A: {result}");
    }

    #[test]
    fn table_alignment_center() {
        let result = render_to_string("| a |\n|:---:|\n| 1 |\n", 80);
        assert!(result.contains(""));
    }

    #[test]
    fn table_alignment_right() {
        let result = render_to_string("| a |\n|---:|\n| 1 |\n", 80);
        assert!(result.contains(""));
    }

    #[test]
    fn paragraph_soft_wrap() {
        let long = "a ".repeat(50);
        let result = render_to_string(&format!("{long}\n"), 40);
        assert!(result.contains('\n'));
    }

    #[test]
    fn blank_line_preserved() {
        let result = render_to_string("para 1\n\npara 2\n", 40);
        let empties = result.lines().filter(|l| l.is_empty()).count();
        assert!(empties >= 1);
    }

    #[test]
    fn parse_reference_link() {
        let result = render_to_string("[text][ref]\n\n[ref]: https://example.com\n", 80);
        assert!(result.contains("\x1b[4mtext\x1b[0m"));
    }

    #[test]
    fn parse_reference_link_implicit() {
        let result = render_to_string("[text][]\n\n[text]: https://example.com\n", 80);
        assert!(result.contains("\x1b[4mtext\x1b[0m"));
    }

    #[test]
    fn reference_link_case_insensitive() {
        let result = render_to_string("[text][REF]\n\n[ref]: https://example.com\n", 80);
        assert!(result.contains("\x1b[4mtext\x1b[0m"));
    }
}