koda-cli 0.2.15

A high-performance AI coding agent for macOS and Linux
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
//! Streaming markdown → ratatui `Line` renderer.
//!
//! Converts raw markdown text (line by line) into styled ratatui
//! `Line`s with headers, bold, italic, inline code, fenced code
//! blocks (with syntax highlighting), lists, blockquotes, and HRs.
//!
//! This replaces the old ANSI-based `markdown.rs` with native ratatui types.

use crate::highlight::CodeHighlighter;
use ratatui::{
    style::{Color, Modifier, Style},
    text::{Line, Span},
};

const INDENT: &str = "  ";

// ── Styles ──────────────────────────────────────────────────

const HEADING_STYLE: Style = Style::new().fg(Color::Cyan).add_modifier(Modifier::BOLD);
const CODE_STYLE: Style = Style::new().fg(Color::Yellow);
const DIM_STYLE: Style = Style::new().fg(Color::DarkGray);
const BLOCKQUOTE_STYLE: Style = Style::new().fg(Color::DarkGray);
const HR_STYLE: Style = Style::new().fg(Color::DarkGray);

// ── State machine ───────────────────────────────────────────

/// Streaming markdown renderer that tracks fenced code block state.
pub struct MarkdownRenderer {
    /// Inside a fenced code block?
    in_code_block: bool,
    /// Syntax highlighter for the current code block.
    highlighter: Option<CodeHighlighter>,
}

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

impl MarkdownRenderer {
    pub fn new() -> Self {
        Self {
            in_code_block: false,
            highlighter: None,
        }
    }

    /// Render a single raw markdown line into a styled `Line`.
    pub fn render_line(&mut self, raw: &str) -> Line<'static> {
        // ── Code block fence ────────────────────────────────
        if raw.starts_with("```") {
            if self.in_code_block {
                // Closing fence
                self.in_code_block = false;
                self.highlighter = None;
                return Line::from(vec![Span::raw(INDENT), Span::styled("```", DIM_STYLE)]);
            } else {
                // Opening fence — extract lang hint
                let lang = raw.trim_start_matches('`').trim();
                self.in_code_block = true;
                self.highlighter = if lang.is_empty() {
                    None
                } else {
                    Some(CodeHighlighter::new(lang))
                };
                return Line::from(vec![
                    Span::raw(INDENT),
                    Span::styled(raw.to_string(), DIM_STYLE),
                ]);
            }
        }

        // ── Inside code block: syntax highlight ─────────────
        if self.in_code_block {
            let spans = match &mut self.highlighter {
                Some(h) => {
                    let mut s = vec![Span::raw(format!("{INDENT}  "))];
                    s.extend(h.highlight_spans(raw));
                    s
                }
                None => vec![
                    Span::raw(format!("{INDENT}  ")),
                    Span::styled(raw.to_string(), CODE_STYLE),
                ],
            };
            return Line::from(spans);
        }

        // ── Horizontal rule ─────────────────────────────────
        if is_horizontal_rule(raw) {
            return Line::from(vec![
                Span::raw(INDENT),
                Span::styled("".repeat(60), HR_STYLE),
            ]);
        }

        // ── Heading ─────────────────────────────────────────
        if let Some((level, text)) = parse_heading(raw) {
            let prefix = match level {
                1 => "",
                2 => "",
                3 => "",
                _ => "  ",
            };
            return Line::from(vec![
                Span::raw(INDENT),
                Span::styled(format!("{prefix}{text}"), HEADING_STYLE),
            ]);
        }

        // ── Blockquote ──────────────────────────────────────
        if let Some(text) = raw.strip_prefix('>') {
            let text = text.strip_prefix(' ').unwrap_or(text);
            let mut spans = vec![Span::raw(INDENT), Span::styled("", BLOCKQUOTE_STYLE)];
            spans.extend(render_inline(text, BLOCKQUOTE_STYLE));
            return Line::from(spans);
        }

        // ── Unordered list ──────────────────────────────────
        if let Some((indent_level, text)) = parse_list_item(raw) {
            let bullet_indent = " ".repeat(indent_level * 2);
            let mut spans = vec![Span::raw(format!("{INDENT}{bullet_indent}"))];
            spans.extend(render_inline(text, Style::default()));
            return Line::from(spans);
        }

        // ── Ordered list ────────────────────────────────────
        if let Some((num, text)) = parse_ordered_item(raw) {
            let mut spans = vec![Span::raw(format!("{INDENT}{num}. "))];
            spans.extend(render_inline(text, Style::default()));
            return Line::from(spans);
        }

        // ── Regular prose ───────────────────────────────────
        let mut spans = vec![Span::raw(INDENT.to_string())];
        spans.extend(render_inline(raw, Style::default()));
        Line::from(spans)
    }
}

// ── Inline formatting parser ────────────────────────────────

/// Parse inline markdown: **bold**, *italic*, `code`, and plain text.
fn render_inline(text: &str, base: Style) -> Vec<Span<'static>> {
    let mut spans = Vec::new();
    let mut chars = text.char_indices().peekable();
    let mut plain_start = 0;

    while let Some(&(i, c)) = chars.peek() {
        match c {
            '`' => {
                // Flush plain text before this marker
                if i > plain_start {
                    spans.push(Span::styled(text[plain_start..i].to_string(), base));
                }
                chars.next();
                // Find closing backtick
                let code_start = i + 1;
                let mut found = false;
                while let Some(&(j, c2)) = chars.peek() {
                    chars.next();
                    if c2 == '`' {
                        spans.push(Span::styled(text[code_start..j].to_string(), CODE_STYLE));
                        plain_start = j + 1;
                        found = true;
                        break;
                    }
                }
                if !found {
                    // No closing backtick — treat as plain
                    spans.push(Span::styled(text[i..].to_string(), base));
                    return spans;
                }
            }
            '*' => {
                // Check for ** (bold) or * (italic)
                let next_char = text.get(i + 1..i + 2);
                if next_char == Some("*") {
                    // Bold: **text**
                    if i > plain_start {
                        spans.push(Span::styled(text[plain_start..i].to_string(), base));
                    }
                    chars.next(); // consume first *
                    chars.next(); // consume second *
                    let bold_start = i + 2;
                    if let Some(end) = text[bold_start..].find("**") {
                        let end_abs = bold_start + end;
                        spans.push(Span::styled(
                            text[bold_start..end_abs].to_string(),
                            base.add_modifier(Modifier::BOLD),
                        ));
                        // Skip past closing **
                        plain_start = end_abs + 2;
                        // Advance chars iterator past the closing **
                        while let Some(&(j, _)) = chars.peek() {
                            if j >= plain_start {
                                break;
                            }
                            chars.next();
                        }
                    } else {
                        // No closing ** — treat as plain
                        spans.push(Span::styled(text[i..].to_string(), base));
                        return spans;
                    }
                } else {
                    // Italic: *text*
                    if i > plain_start {
                        spans.push(Span::styled(text[plain_start..i].to_string(), base));
                    }
                    chars.next(); // consume *
                    let italic_start = i + 1;
                    if let Some(end) = text[italic_start..].find('*') {
                        let end_abs = italic_start + end;
                        spans.push(Span::styled(
                            text[italic_start..end_abs].to_string(),
                            base.add_modifier(Modifier::ITALIC),
                        ));
                        plain_start = end_abs + 1;
                        while let Some(&(j, _)) = chars.peek() {
                            if j >= plain_start {
                                break;
                            }
                            chars.next();
                        }
                    } else {
                        spans.push(Span::styled(text[i..].to_string(), base));
                        return spans;
                    }
                }
            }
            _ => {
                chars.next();
            }
        }
    }

    // Flush remaining plain text
    if plain_start < text.len() {
        spans.push(Span::styled(text[plain_start..].to_string(), base));
    }

    spans
}

// ── Helpers ─────────────────────────────────────────────────

fn parse_heading(line: &str) -> Option<(usize, &str)> {
    let trimmed = line.trim_start();
    let level = trimmed.bytes().take_while(|&b| b == b'#').count();
    if (1..=6).contains(&level) {
        let rest = trimmed[level..].strip_prefix(' ')?;
        Some((level, rest))
    } else {
        None
    }
}

fn parse_list_item(line: &str) -> Option<(usize, &str)> {
    let indent = line.bytes().take_while(|&b| b == b' ').count();
    let after_indent = &line[indent..];
    if let Some(rest) = after_indent
        .strip_prefix("- ")
        .or_else(|| after_indent.strip_prefix("* "))
        .or_else(|| after_indent.strip_prefix("+ "))
    {
        Some((indent / 2, rest))
    } else {
        None
    }
}

fn parse_ordered_item(line: &str) -> Option<(&str, &str)> {
    let trimmed = line.trim_start();
    let num_end = trimmed.bytes().take_while(|b| b.is_ascii_digit()).count();
    if num_end > 0 {
        let rest = &trimmed[num_end..];
        if let Some(text) = rest.strip_prefix(". ") {
            return Some((&trimmed[..num_end], text));
        }
    }
    None
}

fn is_horizontal_rule(line: &str) -> bool {
    let trimmed = line.trim();
    (trimmed.starts_with("---") && trimmed.chars().all(|c| c == '-' || c == ' '))
        || (trimmed.starts_with("***") && trimmed.chars().all(|c| c == '*' || c == ' '))
        || (trimmed.starts_with("___") && trimmed.chars().all(|c| c == '_' || c == ' '))
}

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

    #[test]
    fn test_heading_parsing() {
        assert_eq!(parse_heading("# Hello"), Some((1, "Hello")));
        assert_eq!(parse_heading("## Sub"), Some((2, "Sub")));
        assert_eq!(parse_heading("### Third"), Some((3, "Third")));
        assert_eq!(parse_heading("Not a heading"), None);
    }

    #[test]
    fn test_list_parsing() {
        assert_eq!(parse_list_item("- item"), Some((0, "item")));
        assert_eq!(parse_list_item("  - nested"), Some((1, "nested")));
        assert_eq!(parse_list_item("    - deep"), Some((2, "deep")));
        assert_eq!(parse_list_item("* star"), Some((0, "star")));
    }

    #[test]
    fn test_ordered_list() {
        assert_eq!(parse_ordered_item("1. First"), Some(("1", "First")));
        assert_eq!(parse_ordered_item("42. Answer"), Some(("42", "Answer")));
        assert_eq!(parse_ordered_item("Not ordered"), None);
    }

    #[test]
    fn test_horizontal_rule() {
        assert!(is_horizontal_rule("---"));
        assert!(is_horizontal_rule("***"));
        assert!(is_horizontal_rule("___"));
        assert!(!is_horizontal_rule("--"));
    }

    #[test]
    fn test_inline_bold() {
        let spans = render_inline("hello **world** end", Style::default());
        assert_eq!(spans.len(), 3);
        assert_eq!(spans[0].content, "hello ");
        assert_eq!(spans[1].content, "world");
        assert!(spans[1].style.add_modifier.contains(Modifier::BOLD));
        assert_eq!(spans[2].content, " end");
    }

    #[test]
    fn test_inline_code() {
        let spans = render_inline("use `foo` here", Style::default());
        assert_eq!(spans.len(), 3);
        assert_eq!(spans[1].content, "foo");
        assert_eq!(spans[1].style.fg, Some(Color::Yellow));
    }

    #[test]
    fn test_inline_italic() {
        let spans = render_inline("hello *world* end", Style::default());
        assert_eq!(spans.len(), 3);
        assert_eq!(spans[1].content, "world");
        assert!(spans[1].style.add_modifier.contains(Modifier::ITALIC));
    }

    #[test]
    fn test_code_block_toggle() {
        let mut r = MarkdownRenderer::new();
        assert!(!r.in_code_block);
        r.render_line("```rust");
        assert!(r.in_code_block);
        r.render_line("fn main() {}");
        assert!(r.in_code_block);
        r.render_line("```");
        assert!(!r.in_code_block);
    }

    #[test]
    fn test_unclosed_bold() {
        let spans = render_inline("**unclosed bold", Style::default());
        // Should fall back to plain text, not panic
        assert_eq!(spans.len(), 1);
        assert_eq!(spans[0].content, "**unclosed bold");
    }

    #[test]
    fn test_unclosed_backtick() {
        let spans = render_inline("`unclosed code", Style::default());
        assert_eq!(spans.len(), 1);
        assert_eq!(spans[0].content, "`unclosed code");
    }

    #[test]
    fn test_unclosed_italic() {
        let spans = render_inline("*unclosed italic", Style::default());
        assert_eq!(spans.len(), 1);
        assert_eq!(spans[0].content, "*unclosed italic");
    }

    #[test]
    fn test_empty_line() {
        let mut r = MarkdownRenderer::new();
        let line = r.render_line("");
        assert!(!line.spans.is_empty());
    }

    #[test]
    fn test_heading_is_bold() {
        let mut r = MarkdownRenderer::new();
        let line = r.render_line("# Hello World");
        assert!(
            line.spans
                .iter()
                .any(|s| s.style.add_modifier.contains(Modifier::BOLD)),
            "Heading should have bold span"
        );
    }

    #[test]
    fn test_heading_levels() {
        let mut r = MarkdownRenderer::new();
        for h in ["# H1", "## H2", "### H3"] {
            let line = r.render_line(h);
            let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
            assert!(!text.is_empty(), "Heading '{h}' should render");
        }
    }

    #[test]
    fn test_list_item_renders() {
        let mut r = MarkdownRenderer::new();
        let line = r.render_line("- item one");
        let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(text.contains("item one"));
    }

    #[test]
    fn test_blockquote_renders() {
        let mut r = MarkdownRenderer::new();
        let line = r.render_line("> quoted text");
        let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(text.contains("quoted text"));
    }

    #[test]
    fn test_plain_text_passthrough() {
        let mut r = MarkdownRenderer::new();
        let line = r.render_line("Just plain text here");
        let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(text.contains("Just plain text here"));
    }

    #[test]
    fn test_hr_renders() {
        let mut r = MarkdownRenderer::new();
        let line = r.render_line("---");
        // HR should produce a styled line
        assert!(!line.spans.is_empty());
    }
}