juglans 0.2.16

Compiler and runtime for Juglans Workflow Language
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
use ratatui::{
    style::{Color, Modifier, Style},
    text::{Line, Span},
};
use unicode_width::UnicodeWidthChar;

use super::theme::Theme;

const CODE_BG: Color = Color::Rgb(30, 30, 35);

/// Render markdown content into styled ratatui Lines.
/// Custom line-by-line parser — no external dependencies, streaming-friendly.
/// `width` is used to pre-wrap list items so continuation lines are indented.
pub fn render_markdown(
    content: &str,
    theme: &Theme,
    width: u16,
) -> (Vec<Line<'static>>, Vec<(String, String)>) {
    let mut lines: Vec<Line<'static>> = Vec::new();
    let mut all_links: Vec<(String, String)> = Vec::new();
    let mut in_code_block = false;
    let w = width as usize;

    // Pre-scan for table blocks: collect consecutive lines starting with '|'
    let raw_lines: Vec<&str> = content.lines().collect();
    let mut table_rows: Vec<Vec<String>> = Vec::new();
    let mut table_start: Option<usize> = None;

    // We'll process line-by-line but need lookahead for tables, so use index
    let mut idx = 0;
    while idx < raw_lines.len() {
        let raw_line = raw_lines[idx];

        // --- Code block toggle ---
        if raw_line.trim_start().starts_with("```") {
            // Flush any pending table
            if !table_rows.is_empty() {
                render_table(&table_rows, theme, &mut lines);
                table_rows.clear();
                table_start = None;
            }
            if in_code_block {
                in_code_block = false;
            } else {
                in_code_block = true;
                let lang = raw_line
                    .trim_start()
                    .strip_prefix("```")
                    .unwrap_or("")
                    .trim();
                if !lang.is_empty() {
                    lines.push(Line::from(vec![
                        Span::styled("  ", Style::default()),
                        Span::styled(
                            format!(" {} ", lang),
                            Style::default().fg(theme.muted).bg(CODE_BG),
                        ),
                    ]));
                }
            }
            idx += 1;
            continue;
        }

        // --- Inside code block ---
        if in_code_block {
            lines.push(Line::from(vec![
                Span::styled("  ", Style::default()),
                Span::styled("", Style::default().fg(theme.border).bg(CODE_BG)),
                Span::styled(
                    raw_line.to_string(),
                    Style::default().fg(theme.code).bg(CODE_BG),
                ),
            ]));
            idx += 1;
            continue;
        }

        // --- Table detection ---
        let trimmed_line = raw_line.trim();
        if trimmed_line.starts_with('|') && trimmed_line.ends_with('|') {
            if table_start.is_none() {
                table_start = Some(idx);
            }
            // Check if this is a separator row (| --- | --- |)
            let is_separator = trimmed_line
                .split('|')
                .filter(|s| !s.is_empty())
                .all(|cell| {
                    let t = cell.trim();
                    t.chars().all(|c| c == '-' || c == ':' || c == ' ') && t.contains('-')
                });
            if !is_separator {
                let cells: Vec<String> = trimmed_line
                    .split('|')
                    .filter(|s| !s.is_empty())
                    .map(|s| s.trim().to_string())
                    .collect();
                table_rows.push(cells);
            }
            idx += 1;
            continue;
        }

        // Flush any pending table before processing non-table line
        if !table_rows.is_empty() {
            render_table(&table_rows, theme, &mut lines);
            table_rows.clear();
            table_start = None;
        }

        // --- Empty line: collapse consecutive blank lines into one ---
        if raw_line.trim().is_empty() {
            if lines.last().is_some_and(|l| l.width() <= 2) {
                idx += 1;
                continue;
            }
            lines.push(Line::from(Span::styled("", Style::default())));
            idx += 1;
            continue;
        }

        // --- Headers ---
        if let Some(text) = raw_line.strip_prefix("### ") {
            let mut spans = vec![Span::styled(
                "  ### ",
                Style::default()
                    .fg(theme.heading)
                    .add_modifier(Modifier::BOLD),
            )];
            spans.extend(parse_inline_collecting(
                text,
                Style::default()
                    .fg(theme.heading)
                    .add_modifier(Modifier::BOLD),
                theme,
                &mut all_links,
            ));
            lines.push(Line::from(spans));
            idx += 1;
            continue;
        }
        if let Some(text) = raw_line.strip_prefix("## ") {
            let mut spans = vec![Span::styled(
                "  ## ",
                Style::default()
                    .fg(theme.heading)
                    .add_modifier(Modifier::BOLD),
            )];
            spans.extend(parse_inline_collecting(
                text,
                Style::default()
                    .fg(theme.heading)
                    .add_modifier(Modifier::BOLD),
                theme,
                &mut all_links,
            ));
            lines.push(Line::from(spans));
            idx += 1;
            continue;
        }
        if let Some(text) = raw_line.strip_prefix("# ") {
            let mut spans = vec![Span::styled(
                "  # ",
                Style::default()
                    .fg(theme.heading)
                    .add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
            )];
            spans.extend(parse_inline_collecting(
                text,
                Style::default()
                    .fg(theme.heading)
                    .add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
                theme,
                &mut all_links,
            ));
            lines.push(Line::from(spans));
            idx += 1;
            continue;
        }

        // --- Horizontal rule ---
        if (trimmed_line.starts_with("---")
            || trimmed_line.starts_with("***")
            || trimmed_line.starts_with("___"))
            && trimmed_line
                .chars()
                .all(|c| c == '-' || c == '*' || c == '_' || c == ' ')
            && trimmed_line.len() >= 3
        {
            lines.push(Line::from(Span::styled(
                "  ───────────────────────────────",
                Style::default().fg(theme.border),
            )));
            idx += 1;
            continue;
        }

        // --- Blockquote ---
        if let Some(text) = raw_line.strip_prefix("> ") {
            let mut spans = vec![Span::styled("", Style::default().fg(theme.thinking))];
            spans.extend(parse_inline_collecting(
                text,
                Style::default().fg(theme.thinking),
                theme,
                &mut all_links,
            ));
            lines.push(Line::from(spans));
            idx += 1;
            continue;
        }

        // --- Unordered list ---
        if raw_line.starts_with("- ") || raw_line.starts_with("* ") {
            let text = &raw_line[2..];
            let prefix_w = 4; // "  ● " = 4 columns
            render_wrapped_list(
                &mut lines,
                "",
                "  ",
                prefix_w,
                text,
                w,
                Style::default().fg(theme.accent),
                Style::default().fg(theme.fg),
                theme,
                &mut all_links,
            );
            idx += 1;
            continue;
        }
        // Nested list (2-4 spaces + - or *)
        if let Some(rest) = raw_line
            .strip_prefix("  - ")
            .or_else(|| raw_line.strip_prefix("  * "))
        {
            let prefix_w = 6; // "    ◦ " = 6 columns
            render_wrapped_list(
                &mut lines,
                "",
                "    ",
                prefix_w,
                rest,
                w,
                Style::default().fg(theme.accent),
                Style::default().fg(theme.fg),
                theme,
                &mut all_links,
            );
            idx += 1;
            continue;
        }

        // --- Ordered list ---
        if let Some(pos) = raw_line.find(". ") {
            let prefix = &raw_line[..pos];
            if !prefix.is_empty() && prefix.chars().all(|c| c.is_ascii_digit()) {
                let text = &raw_line[pos + 2..];
                let bullet = format!("{}. ", prefix);
                let prefix_w = 2 + display_width(&bullet); // "  " + "N. "
                render_wrapped_list(
                    &mut lines,
                    &bullet,
                    "  ",
                    prefix_w,
                    text,
                    w,
                    Style::default().fg(theme.accent),
                    Style::default().fg(theme.fg),
                    theme,
                    &mut all_links,
                );
                idx += 1;
                continue;
            }
        }

        // --- Empty line ---
        if raw_line.trim().is_empty() {
            lines.push(Line::from(""));
            idx += 1;
            continue;
        }

        // --- Normal paragraph line (with inline formatting) ---
        let mut spans = vec![Span::styled("  ", Style::default())];
        spans.extend(parse_inline_collecting(
            raw_line,
            Style::default().fg(theme.fg),
            theme,
            &mut all_links,
        ));
        lines.push(Line::from(spans));
        idx += 1;
    }

    // Flush any trailing table
    if !table_rows.is_empty() {
        render_table(&table_rows, theme, &mut lines);
    }

    (lines, all_links)
}

/// Render a list item with manual wrapping so continuation lines are indented.
/// Parses inline markdown FIRST, then wraps the resulting spans by display width.
#[allow(clippy::too_many_arguments)]
fn render_wrapped_list(
    lines: &mut Vec<Line<'static>>,
    bullet: &str,
    outer_pad: &str,
    prefix_w: usize,
    text: &str,
    width: usize,
    bullet_style: Style,
    text_style: Style,
    theme: &Theme,
    all_links: &mut Vec<(String, String)>,
) {
    let avail = if width > prefix_w {
        width - prefix_w
    } else {
        width.max(1)
    };

    // Parse inline markdown first (links, bold, etc. stay intact)
    let parsed_spans = parse_inline_collecting(text, text_style, theme, all_links);
    let wrapped = wrap_spans(parsed_spans, avail);

    if wrapped.is_empty() {
        lines.push(Line::from(vec![
            Span::styled(outer_pad.to_string(), Style::default()),
            Span::styled(bullet.to_string(), bullet_style),
        ]));
        return;
    }

    for (i, visual_spans) in wrapped.into_iter().enumerate() {
        let mut row_spans = if i == 0 {
            vec![
                Span::styled(outer_pad.to_string(), Style::default()),
                Span::styled(bullet.to_string(), bullet_style),
            ]
        } else {
            vec![Span::styled(" ".repeat(prefix_w), Style::default())]
        };
        row_spans.extend(visual_spans);
        lines.push(Line::from(row_spans));
    }
}

/// Wrap pre-parsed spans into visual lines that fit within `max_w` display columns.
/// Splits individual spans at character boundaries when needed.
fn wrap_spans(spans: Vec<Span<'static>>, max_w: usize) -> Vec<Vec<Span<'static>>> {
    if max_w == 0 {
        return vec![spans];
    }
    let mut result: Vec<Vec<Span<'static>>> = Vec::new();
    let mut current_line: Vec<Span<'static>> = Vec::new();
    let mut current_w = 0usize;

    for span in spans {
        let chars: Vec<char> = span.content.chars().collect();
        let style = span.style;
        let mut pos = 0;

        while pos < chars.len() {
            let remaining = max_w.saturating_sub(current_w);

            // If current line is full, start a new one
            if remaining == 0 {
                result.push(std::mem::take(&mut current_line));
                current_w = 0;
                continue;
            }

            // Take as many chars as fit in remaining width
            let mut col = 0usize;
            let mut end = pos;
            while end < chars.len() {
                let cw = UnicodeWidthChar::width(chars[end]).unwrap_or(1);
                if col + cw > remaining {
                    break;
                }
                col += cw;
                end += 1;
            }

            if end == pos {
                // Can't fit even one char on current line
                if !current_line.is_empty() {
                    result.push(std::mem::take(&mut current_line));
                    current_w = 0;
                    continue;
                }
                // Empty line but still can't fit — force one char
                let cw = UnicodeWidthChar::width(chars[pos]).unwrap_or(1);
                let ch: String = chars[pos..pos + 1].iter().collect();
                current_line.push(Span::styled(ch, style));
                current_w += cw;
                pos += 1;
                continue;
            }

            let chunk: String = chars[pos..end].iter().collect();
            current_line.push(Span::styled(chunk, style));
            current_w += col;
            pos = end;
        }
    }

    if !current_line.is_empty() {
        result.push(current_line);
    }

    result
}

/// Calculate display width of a string.
fn display_width(s: &str) -> usize {
    s.chars()
        .map(|c| UnicodeWidthChar::width(c).unwrap_or(1))
        .sum()
}

/// Render a table block.
fn render_table(rows: &[Vec<String>], theme: &Theme, lines: &mut Vec<Line<'static>>) {
    if rows.is_empty() {
        return;
    }
    // Compute column widths
    let ncols = rows.iter().map(|r| r.len()).max().unwrap_or(0);
    let mut col_widths = vec![0usize; ncols];
    for row in rows {
        for (ci, cell) in row.iter().enumerate() {
            if ci < ncols {
                col_widths[ci] = col_widths[ci].max(display_width(cell));
            }
        }
    }

    for (ri, row) in rows.iter().enumerate() {
        let is_header = ri == 0 && rows.len() > 1;
        let mut spans = vec![Span::styled("  ", Style::default())];

        for (ci, cell) in row.iter().enumerate() {
            let cw = if ci < ncols { col_widths[ci] } else { 0 };
            let cell_w = display_width(cell);
            let pad = cw.saturating_sub(cell_w);

            if ci > 0 {
                spans.push(Span::styled("", Style::default().fg(theme.border)));
            }

            let style = if is_header {
                Style::default().fg(theme.fg).add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(theme.fg)
            };
            spans.push(Span::styled(cell.clone(), style));
            if pad > 0 {
                spans.push(Span::styled(" ".repeat(pad), Style::default()));
            }
        }

        lines.push(Line::from(spans));

        // Separator after header
        if is_header {
            let total: usize = col_widths.iter().sum::<usize>() + (ncols.saturating_sub(1)) * 3;
            lines.push(Line::from(vec![
                Span::styled("  ", Style::default()),
                Span::styled("".repeat(total), Style::default().fg(theme.border)),
            ]));
        }
    }
}

fn parse_inline_collecting(
    text: &str,
    base_style: Style,
    theme: &Theme,
    links: &mut Vec<(String, String)>,
) -> Vec<Span<'static>> {
    parse_inline_with_links(text, base_style, theme, Some(links))
}

fn parse_inline_with_links(
    text: &str,
    base_style: Style,
    theme: &Theme,
    mut links_out: Option<&mut Vec<(String, String)>>,
) -> Vec<Span<'static>> {
    let mut spans: Vec<Span<'static>> = Vec::new();
    let chars: Vec<char> = text.chars().collect();
    let len = chars.len();
    let mut i = 0;
    let mut buf = String::new();

    while i < len {
        // --- Inline code: `...` ---
        if chars[i] == '`' {
            if !buf.is_empty() {
                spans.push(Span::styled(std::mem::take(&mut buf), base_style));
            }
            if let Some(end) = find_closing(&chars, i + 1, '`') {
                let code: String = chars[i + 1..end].iter().collect();
                spans.push(Span::styled(
                    format!(" {} ", code),
                    Style::default().fg(theme.code).bg(CODE_BG),
                ));
                i = end + 1;
                continue;
            }
            buf.push('`');
            i += 1;
            continue;
        }

        // --- Link: [text](url) ---
        if chars[i] == '[' {
            if let Some(close_bracket) = find_closing(&chars, i + 1, ']') {
                if close_bracket + 1 < len && chars[close_bracket + 1] == '(' {
                    if let Some(close_paren) = find_closing(&chars, close_bracket + 2, ')') {
                        if !buf.is_empty() {
                            spans.push(Span::styled(std::mem::take(&mut buf), base_style));
                        }
                        let link_text: String = chars[i + 1..close_bracket].iter().collect();
                        let link_url: String =
                            chars[close_bracket + 2..close_paren].iter().collect();
                        if let Some(ref mut links) = links_out {
                            links.push((link_text.clone(), link_url));
                        }
                        spans.push(Span::styled(
                            link_text,
                            base_style
                                .fg(theme.accent)
                                .add_modifier(Modifier::UNDERLINED),
                        ));
                        i = close_paren + 1;
                        continue;
                    }
                }
            }
            buf.push('[');
            i += 1;
            continue;
        }

        // --- Bold: **...** ---
        if i + 1 < len && chars[i] == '*' && chars[i + 1] == '*' {
            if !buf.is_empty() {
                spans.push(Span::styled(std::mem::take(&mut buf), base_style));
            }
            if let Some(end) = find_double_closing(&chars, i + 2, '*') {
                let inner: String = chars[i + 2..end].iter().collect();
                spans.push(Span::styled(inner, base_style.add_modifier(Modifier::BOLD)));
                i = end + 2;
                continue;
            }
            buf.push_str("**");
            i += 2;
            continue;
        }

        // --- Italic: *...* (single, not followed by another *) ---
        if chars[i] == '*' && (i + 1 >= len || chars[i + 1] != '*') {
            if !buf.is_empty() {
                spans.push(Span::styled(std::mem::take(&mut buf), base_style));
            }
            if let Some(end) = find_single_closing(&chars, i + 1, '*') {
                let inner: String = chars[i + 1..end].iter().collect();
                spans.push(Span::styled(
                    inner,
                    base_style.add_modifier(Modifier::ITALIC),
                ));
                i = end + 1;
                continue;
            }
            buf.push('*');
            i += 1;
            continue;
        }

        // --- Regular character ---
        buf.push(chars[i]);
        i += 1;
    }

    if !buf.is_empty() {
        spans.push(Span::styled(buf, base_style));
    }

    spans
}

/// Find closing single delimiter (e.g., ` or *), returns index of the closing char.
fn find_closing(chars: &[char], start: usize, delim: char) -> Option<usize> {
    (start..chars.len()).find(|&i| chars[i] == delim)
}

/// Find closing ** (double delimiter), returns index of first * of **.
fn find_double_closing(chars: &[char], start: usize, delim: char) -> Option<usize> {
    let mut i = start;
    while i + 1 < chars.len() {
        if chars[i] == delim && chars[i + 1] == delim {
            return Some(i);
        }
        i += 1;
    }
    None
}

/// Find closing single * that is NOT followed by another * (for italic).
fn find_single_closing(chars: &[char], start: usize, delim: char) -> Option<usize> {
    for i in start..chars.len() {
        if chars[i] == delim {
            if i + 1 < chars.len() && chars[i + 1] == delim {
                continue;
            }
            if i > start && chars[i - 1] == delim {
                continue;
            }
            return Some(i);
        }
    }
    None
}