claux 20260727.0.0

Terminal AI coding assistant with tool execution
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
//! Markdown-to-ratatui renderer using pulldown-cmark.
//!
//! Full CommonMark support with proper parsing for code blocks, headers,
//! lists, links, emphasis, and more.

use pulldown_cmark::{Event, HeadingLevel, Options, Parser, Tag, TagEnd};
use ratatui::{
    style::{Color, Modifier, Style},
    text::{Line, Span},
};

const AQUA: Color = Color::Rgb(142, 192, 124); // gruvbox aqua
const ORANGE: Color = Color::Rgb(254, 128, 25); // gruvbox orange
const YELLOW: Color = Color::Rgb(250, 189, 47); // gruvbox yellow
const GRAY: Color = Color::Rgb(146, 131, 116); // gruvbox gray
const BLUE: Color = Color::Rgb(131, 165, 152); // gruvbox blue
const BG_CODE: Color = Color::Rgb(60, 56, 54); // gruvbox bg1

/// Parse markdown text into styled ratatui Lines using pulldown-cmark.
pub fn render(text: &str, base_style: Style) -> Vec<Line<'static>> {
    let mut lines: Vec<Line<'static>> = Vec::new();
    let mut current_line: Vec<Span<'static>> = Vec::new();
    let mut style_stack: Vec<Style> = vec![base_style];
    let mut in_code_block = false;
    let mut code_block_lang = String::new();
    let mut list_depth: usize = 0;
    let mut _in_heading = false;
    let mut _heading_level = HeadingLevel::H1;
    let mut first_table_cell = false;
    let mut table_col_count: usize = 0;

    let options = Options::all();
    let parser = Parser::new_ext(text, options);

    for event in parser {
        match event {
            Event::Start(tag) => match tag {
                // Start new line for paragraph
                Tag::Paragraph if !current_line.is_empty() => {
                    lines.push(Line::from(current_line.clone()));
                    current_line.clear();
                }
                Tag::Heading { level, .. } => {
                    _in_heading = true;
                    _heading_level = level;
                    let heading_style = match level {
                        HeadingLevel::H1 => Style::default()
                            .fg(YELLOW)
                            .add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
                        HeadingLevel::H2 | HeadingLevel::H3 => {
                            Style::default().fg(ORANGE).add_modifier(Modifier::BOLD)
                        }
                        _ => Style::default().fg(ORANGE),
                    };
                    style_stack.push(heading_style);
                }
                Tag::BlockQuote(_) => {
                    current_line.push(Span::styled("", Style::default().fg(GRAY)));
                    style_stack.push(Style::default().fg(GRAY));
                }
                Tag::CodeBlock(kind) => {
                    in_code_block = true;
                    code_block_lang = match kind {
                        pulldown_cmark::CodeBlockKind::Fenced(lang) => lang.to_string(),
                        pulldown_cmark::CodeBlockKind::Indented => String::new(),
                    };

                    let label = if code_block_lang.is_empty() {
                        "┌─ code ".to_string()
                    } else {
                        format!("┌─ {code_block_lang} ")
                    };
                    lines.push(Line::from(Span::styled(
                        format!("{label}─────────────────────────"),
                        Style::default().fg(GRAY),
                    )));
                }
                Tag::List(_) => {
                    list_depth += 1;
                }
                Tag::Item => {
                    let indent = "  ".repeat(list_depth.saturating_sub(1));
                    current_line.push(Span::styled(
                        format!("{indent}"),
                        Style::default().fg(GRAY),
                    ));
                }
                Tag::Emphasis => {
                    let current_style = *style_stack.last().unwrap_or(&base_style);
                    style_stack.push(current_style.add_modifier(Modifier::ITALIC));
                }
                Tag::Strong => {
                    let current_style = *style_stack.last().unwrap_or(&base_style);
                    style_stack.push(current_style.add_modifier(Modifier::BOLD));
                }
                Tag::Link { .. } => {
                    style_stack.push(Style::default().fg(BLUE).add_modifier(Modifier::UNDERLINED));
                    // We'll append the URL in parentheses after the link text
                    current_line.push(Span::raw("["));
                }
                Tag::Image { dest_url, .. } => {
                    current_line.push(Span::styled(
                        format!("![image: {dest_url}]"),
                        Style::default().fg(BLUE),
                    ));
                }
                // Tables render as pipe-separated rows: without these
                // handlers the cell text concatenates into one word soup.
                Tag::Table(alignments) => {
                    if !current_line.is_empty() {
                        lines.push(Line::from(current_line.clone()));
                        current_line.clear();
                    }
                    table_col_count = alignments.len();
                }
                Tag::TableHead => {
                    first_table_cell = true;
                    let current_style = *style_stack.last().unwrap_or(&base_style);
                    style_stack.push(current_style.add_modifier(Modifier::BOLD));
                }
                Tag::TableRow => {
                    first_table_cell = true;
                }
                Tag::TableCell => {
                    if !first_table_cell {
                        current_line.push(Span::styled("", Style::default().fg(GRAY)));
                    }
                    first_table_cell = false;
                }
                _ => {}
            },

            Event::End(tag_end) => match tag_end {
                TagEnd::Paragraph => {
                    if !current_line.is_empty() {
                        lines.push(Line::from(current_line.clone()));
                        current_line.clear();
                    }
                    // Add blank line after paragraph
                    lines.push(Line::from(""));
                }
                TagEnd::Heading(_) => {
                    _in_heading = false;
                    if !current_line.is_empty() {
                        lines.push(Line::from(current_line.clone()));
                        current_line.clear();
                    }
                    lines.push(Line::from(""));
                    style_stack.pop();
                }
                TagEnd::BlockQuote(_) => {
                    if !current_line.is_empty() {
                        lines.push(Line::from(current_line.clone()));
                        current_line.clear();
                    }
                    style_stack.pop();
                }
                TagEnd::CodeBlock => {
                    in_code_block = false;
                    lines.push(Line::from(Span::styled(
                        "└─────────────────────────────",
                        Style::default().fg(GRAY),
                    )));
                    code_block_lang.clear();
                }
                TagEnd::List(_) => {
                    list_depth = list_depth.saturating_sub(1);
                    if !current_line.is_empty() {
                        lines.push(Line::from(current_line.clone()));
                        current_line.clear();
                    }
                }
                TagEnd::Item if !current_line.is_empty() => {
                    lines.push(Line::from(current_line.clone()));
                    current_line.clear();
                }
                TagEnd::Emphasis | TagEnd::Strong => {
                    style_stack.pop();
                }
                TagEnd::Link => {
                    current_line.push(Span::raw("]"));
                    style_stack.pop();
                }
                TagEnd::TableHead => {
                    style_stack.pop();
                    if !current_line.is_empty() {
                        lines.push(Line::from(current_line.clone()));
                        current_line.clear();
                    }
                    // Rule under the header row, sized loosely to the table
                    lines.push(Line::from(Span::styled(
                        "".repeat((table_col_count.max(1) * 12).min(60)),
                        Style::default().fg(GRAY),
                    )));
                }
                TagEnd::TableRow => {
                    if !current_line.is_empty() {
                        lines.push(Line::from(current_line.clone()));
                        current_line.clear();
                    }
                }
                TagEnd::Table => {
                    lines.push(Line::from(""));
                }
                _ => {}
            },

            Event::Text(text) => {
                if in_code_block {
                    // Code block content
                    for line in text.lines() {
                        lines.push(Line::from(Span::styled(
                            format!("{line}"),
                            Style::default().fg(AQUA).bg(BG_CODE),
                        )));
                    }
                } else {
                    let current_style = *style_stack.last().unwrap_or(&base_style);
                    current_line.push(Span::styled(text.to_string(), current_style));
                }
            }

            Event::Code(code) => {
                current_line.push(Span::styled(
                    code.to_string(),
                    Style::default().fg(AQUA).bg(BG_CODE),
                ));
            }

            Event::SoftBreak => {
                current_line.push(Span::raw(" "));
            }

            Event::HardBreak if !current_line.is_empty() => {
                lines.push(Line::from(current_line.clone()));
                current_line.clear();
            }

            Event::Rule => {
                lines.push(Line::from(Span::styled(
                    "────────────────────────────────",
                    Style::default().fg(GRAY),
                )));
            }

            _ => {}
        }
    }

    // Flush remaining line
    if !current_line.is_empty() {
        lines.push(Line::from(current_line));
    }

    // Remove trailing empty lines
    while lines.last().map(|l| l.spans.is_empty()).unwrap_or(false) {
        lines.pop();
    }

    lines
}

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

    #[test]
    fn plain_text_unchanged() {
        let lines = render("hello world", Style::default());
        assert!(!lines.is_empty());
    }

    #[test]
    fn code_block_detected() {
        let text = "before\n\n```rust\nlet x = 1;\n```\n\nafter";
        let lines = render(text, Style::default());
        // Should have: before, blank, opening fence, code line, closing fence, blank, after
        assert!(lines.len() >= 5);
    }

    #[test]
    fn headers_styled() {
        let text = "# Big\n\n## Medium\n\n### Small";
        let lines = render(text, Style::default());
        assert!(lines.len() >= 3);
    }

    #[test]
    fn horizontal_rule() {
        let lines = render("---", Style::default());
        assert!(!lines.is_empty());
        let content: String = lines[0].spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(content.contains("────"));
    }

    #[test]
    fn inline_code() {
        let lines = render("use `cargo build` here", Style::default());
        assert!(!lines.is_empty());
        // Check that there's a span with code styling
        let has_code = lines.iter().any(|line| {
            line.spans
                .iter()
                .any(|span| span.content.as_ref().contains("cargo build"))
        });
        assert!(has_code);
    }

    #[test]
    fn bold_text() {
        let lines = render("this is **bold** text", Style::default());
        assert!(!lines.is_empty());
        // Check that there's a bold span
        let has_bold = lines.iter().any(|line| {
            line.spans
                .iter()
                .any(|span| span.style.add_modifier.contains(Modifier::BOLD))
        });
        assert!(has_bold);
    }

    #[test]
    fn lists_rendered() {
        let text = "- item 1\n- item 2\n- item 3";
        let lines = render(text, Style::default());
        assert!(lines.len() >= 3);
        // Each item should have a bullet
        let has_bullets = lines.iter().any(|line| {
            line.spans
                .iter()
                .any(|span| span.content.as_ref().contains(""))
        });
        assert!(has_bullets);
    }

    #[test]
    fn links_rendered() {
        let text = "Check out [this link](https://example.com)";
        let lines = render(text, Style::default());
        assert!(!lines.is_empty());
        // Should have link text with brackets
        let content: String = lines[0].spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(content.contains("[") && content.contains("]"));
    }

    #[test]
    fn nested_lists() {
        let text = "- item 1\n  - nested 1\n  - nested 2\n- item 2";
        let lines = render(text, Style::default());
        // Just check that we got some output
        assert!(!lines.is_empty());
        // Check that nested items have more indentation
        let has_nested_indent = lines.iter().any(|line| {
            line.spans
                .iter()
                .any(|span| span.content.as_ref().contains(""))
        });
        assert!(has_nested_indent);
    }

    #[test]
    fn empty_input() {
        let lines = render("", Style::default());
        // Empty string should result in empty lines vec
        assert!(lines.is_empty() || lines.len() == 1);
    }

    #[test]
    fn table_cells_are_separated() {
        // Regression: cells used to concatenate into "PatternWhereRisk"
        let text = "| Pattern | Where | Risk |\n|---|---|---|\n| lock | query.rs | panic |";
        let lines = render(text, Style::default());

        let rows: Vec<String> = lines
            .iter()
            .map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect())
            .collect();

        let header = rows
            .iter()
            .find(|r| r.contains("Pattern"))
            .expect("header row rendered");
        assert!(
            header.contains("Pattern │ Where │ Risk"),
            "cells must be separated, got: {header}"
        );

        let body = rows
            .iter()
            .find(|r| r.contains("lock"))
            .expect("body row rendered");
        assert!(body.contains("lock │ query.rs │ panic"), "got: {body}");

        // Header and body are distinct lines with a rule between
        assert!(rows.iter().any(|r| r.contains("───")));
    }

    #[test]
    fn table_head_is_bold() {
        let text = "| A | B |\n|---|---|\n| 1 | 2 |";
        let lines = render(text, Style::default());
        let header_bold = lines.iter().any(|line| {
            line.spans.iter().any(|span| {
                span.content.as_ref() == "A" && span.style.add_modifier.contains(Modifier::BOLD)
            })
        });
        assert!(header_bold, "header cells should be bold");
    }
}