procyon 0.3.0

Terminal development harness for Stellar and Soroban smart contracts, driven by a language model
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
//! Markdown rendering for the transcript.
//!
//! The model answers in markdown whether or not anything reads it, so the transcript used to
//! carry `**bold**`, `### heading` and fence rows as literal characters — noise the user has to
//! parse around. This turns that into terminal styling.
//!
//! Two rules keep it honest. Colour comes only from the six [`ColorPalette`] roles, like the rest
//! of `ui.rs`, so a theme still owns the palette. And nothing is dropped: an unmatched `**`, a
//! fence that never closes, a table row we do not model — all of it still reaches the screen as
//! text. A renderer that swallows what it cannot parse loses the answer.

use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};

use crate::ui::ColorPalette;

/// Styles for the block and inline roles, derived from the palette once per render.
pub struct MarkdownStyles {
    body: Style,
    heading: Style,
    subheading: Style,
    code: Style,
    marker: Style,
    quote: Style,
    rule: Style,
    link: Style,
}

impl MarkdownStyles {
    pub fn new(palette: &ColorPalette, body: Style) -> Self {
        Self {
            body,
            heading: body.add_modifier(Modifier::BOLD).fg(palette.accent),
            subheading: body.add_modifier(Modifier::BOLD),
            // Code keeps body weight and takes the network hue: it has to stay legible in a wall
            // of prose, which `dim` is not.
            code: body.fg(palette.network),
            marker: body.fg(palette.accent),
            quote: body.fg(palette.dim).add_modifier(Modifier::ITALIC),
            rule: body.fg(palette.dim),
            link: body.fg(palette.network).add_modifier(Modifier::UNDERLINED),
        }
    }
}

/// Render `content` as markdown into `width` columns, every line prefixed with `indent`.
pub fn render(
    content: &str,
    styles: &MarkdownStyles,
    width: usize,
    indent: &str,
) -> Vec<Line<'static>> {
    let indent_width = indent.chars().count();
    let budget = width.saturating_sub(indent_width).max(1);
    let mut out = Vec::new();
    let mut fence: Option<char> = None;

    for raw in content.split('\n') {
        let trimmed = raw.trim_start();

        // A fence toggles verbatim mode. Inside it nothing is parsed — that is the whole point of
        // asking for a code block.
        if let Some(marker) = fence_marker(trimmed) {
            match fence {
                Some(open) if open == marker => fence = None,
                Some(_) => push_code(&mut out, raw, styles, budget, indent),
                None => fence = Some(marker),
            }
            continue;
        }
        if fence.is_some() {
            push_code(&mut out, raw, styles, budget, indent);
            continue;
        }

        if trimmed.is_empty() {
            out.push(Line::from(Span::raw(indent.to_string())));
            continue;
        }

        if is_rule(trimmed) {
            out.push(Line::from(vec![
                Span::raw(indent.to_string()),
                Span::styled("".repeat(budget), styles.rule),
            ]));
            continue;
        }

        if let Some((level, text)) = heading(trimmed) {
            let style = if level <= 2 {
                styles.heading
            } else {
                styles.subheading
            };
            let spans = parse_inline(text, style, styles);
            out.extend(wrap_spans(spans, budget, indent, ""));
            continue;
        }

        if let Some(text) = trimmed
            .strip_prefix("> ")
            .or_else(|| (trimmed == ">").then_some(""))
        {
            let mut spans = vec![Span::styled("", styles.rule)];
            spans.extend(parse_inline(text, styles.quote, styles));
            out.extend(wrap_spans(spans, budget, indent, "  "));
            continue;
        }

        // Lists keep their own indentation, so nested items still read as nested.
        let lead = raw.len() - trimmed.len();
        if let Some((marker, text)) = list_item(trimmed) {
            let pad = " ".repeat(lead);
            let mut spans = vec![
                Span::raw(pad.clone()),
                Span::styled(marker.clone(), styles.marker),
            ];
            spans.extend(parse_inline(text, styles.body, styles));
            let hang = format!("{pad}{}", " ".repeat(marker.chars().count()));
            out.extend(wrap_spans(spans, budget, indent, &hang));
            continue;
        }

        out.extend(wrap_spans(
            parse_inline(raw, styles.body, styles),
            budget,
            indent,
            "",
        ));
    }

    out
}

fn fence_marker(trimmed: &str) -> Option<char> {
    for marker in ['`', '~'] {
        let run: String = std::iter::repeat_n(marker, 3).collect();
        if trimmed.starts_with(&run) {
            return Some(marker);
        }
    }
    None
}

fn is_rule(trimmed: &str) -> bool {
    let t = trimmed.trim_end();
    ['-', '*', '_']
        .iter()
        .any(|c| t.len() >= 3 && t.chars().all(|ch| ch == *c))
}

fn heading(trimmed: &str) -> Option<(usize, &str)> {
    let hashes = trimmed.chars().take_while(|c| *c == '#').count();
    if hashes == 0 || hashes > 6 {
        return None;
    }
    let rest = &trimmed[hashes..];
    let text = rest.strip_prefix(' ')?;
    Some((hashes, text.trim_end()))
}

/// A bullet or an ordered item, returned as the marker to draw and the text after it. The bullet
/// glyph replaces `-`/`*`/`+` so a list looks like a list rather than like arithmetic.
fn list_item(trimmed: &str) -> Option<(String, &str)> {
    for bullet in ["- ", "* ", "+ "] {
        if let Some(rest) = trimmed.strip_prefix(bullet) {
            return Some(("".to_string(), rest));
        }
    }

    let digits = trimmed.chars().take_while(char::is_ascii_digit).count();
    if digits == 0 || digits > 3 {
        return None;
    }
    let rest = &trimmed[digits..];
    for sep in [". ", ") "] {
        if let Some(text) = rest.strip_prefix(sep) {
            return Some((format!("{}{}", &trimmed[..digits], sep), text));
        }
    }
    None
}

fn push_code(
    out: &mut Vec<Line<'static>>,
    raw: &str,
    styles: &MarkdownStyles,
    budget: usize,
    indent: &str,
) {
    // The bar costs two columns and buys the one thing a code block needs: an edge, so leading
    // whitespace is visible and the block does not merge into the prose above it.
    let inner = budget.saturating_sub(2).max(1);
    let chars: Vec<char> = raw.chars().collect();
    let chunks: Vec<String> = if chars.is_empty() {
        vec![String::new()]
    } else {
        chars.chunks(inner).map(|c| c.iter().collect()).collect()
    };
    for chunk in chunks {
        out.push(Line::from(vec![
            Span::raw(indent.to_string()),
            Span::styled("", styles.rule),
            Span::styled(chunk, styles.code),
        ]));
    }
}

/// Inline emphasis, code spans and links, parsed over `base` so nesting keeps the outer style.
///
/// Underscore emphasis is deliberately not handled: in a harness whose transcripts are full of
/// `snake_case` and `__init__`, italicising on `_` corrupts more identifiers than it decorates.
fn parse_inline(text: &str, base: Style, styles: &MarkdownStyles) -> Vec<Span<'static>> {
    let chars: Vec<char> = text.chars().collect();
    let mut out: Vec<Span<'static>> = Vec::new();
    let mut buf = String::new();
    let mut i = 0;

    while i < chars.len() {
        if chars[i] == '`' {
            if let Some(end) = find(&chars, i + 1, "`") {
                flush(&mut buf, base, &mut out);
                let inner: String = chars[i + 1..end].iter().collect();
                out.push(Span::styled(inner, styles.code));
                i = end + 1;
                continue;
            }
        }

        // Longest delimiter first: `**` must not be read as an empty `*…*`.
        let mut emphasised = false;
        for (delim, modifier) in [
            ("**", Modifier::BOLD),
            ("~~", Modifier::CROSSED_OUT),
            ("*", Modifier::ITALIC),
        ] {
            if !starts_with(&chars, i, delim) {
                continue;
            }
            let open = i + delim.len();
            // An empty pair (`****`) is not emphasis; leaving it as text is what the author wrote.
            if let Some(end) = find(&chars, open, delim).filter(|end| *end > open) {
                flush(&mut buf, base, &mut out);
                let inner: String = chars[open..end].iter().collect();
                out.extend(parse_inline(&inner, base.add_modifier(modifier), styles));
                i = end + delim.len();
                emphasised = true;
            }
            break;
        }
        if emphasised {
            continue;
        }

        if chars[i] == '[' {
            if let Some(close) = find(&chars, i + 1, "]") {
                if starts_with(&chars, close + 1, "(") {
                    if let Some(paren) = find(&chars, close + 2, ")") {
                        flush(&mut buf, base, &mut out);
                        let label: String = chars[i + 1..close].iter().collect();
                        let url: String = chars[close + 2..paren].iter().collect();
                        out.extend(parse_inline(&label, base.patch(styles.link), styles));
                        out.push(Span::styled(format!(" ({url})"), styles.rule));
                        i = paren + 1;
                        continue;
                    }
                }
            }
        }

        buf.push(chars[i]);
        i += 1;
    }

    flush(&mut buf, base, &mut out);
    if out.is_empty() {
        out.push(Span::styled(String::new(), base));
    }
    out
}

fn flush(buf: &mut String, style: Style, out: &mut Vec<Span<'static>>) {
    if !buf.is_empty() {
        out.push(Span::styled(std::mem::take(buf), style));
    }
}

fn starts_with(chars: &[char], at: usize, needle: &str) -> bool {
    let n: Vec<char> = needle.chars().collect();
    at + n.len() <= chars.len() && chars[at..at + n.len()] == n[..]
}

fn find(chars: &[char], from: usize, needle: &str) -> Option<usize> {
    (from..chars.len()).find(|i| starts_with(chars, *i, needle))
}

/// Wrap a styled run at word boundaries, splitting spans as needed so a bold phrase can straddle
/// a line break without losing its style.
fn wrap_spans(
    spans: Vec<Span<'static>>,
    width: usize,
    indent: &str,
    hang: &str,
) -> Vec<Line<'static>> {
    let mut lines: Vec<Line<'static>> = Vec::new();
    let mut current: Vec<Span<'static>> = vec![Span::raw(indent.to_string())];
    let mut used = 0usize;
    // The separator is held back until the next word is placed, so a break never leaves a space
    // dangling at the right margin.
    let mut pending: Option<Style> = None;

    // `indent` sits outside the budget (it was already subtracted); `hang` sits inside it, so a
    // wrapped bullet stays within the same right margin as its first line.
    let hang_width = hang.chars().count();
    let mut push_line = |current: &mut Vec<Span<'static>>, used: &mut usize| {
        lines.push(Line::from(std::mem::take(current)));
        *current = vec![Span::raw(format!("{indent}{hang}"))];
        *used = hang_width;
    };

    for span in spans {
        let style = span.style;
        let content = span.content.into_owned();
        // Leading structural spans (the bullet's own indentation) are placed verbatim.
        if !content.is_empty() && used == 0 && content.chars().all(|c| c == ' ') {
            used += content.chars().count();
            current.push(Span::styled(content, style));
            continue;
        }

        for (index, word) in content.split(' ').enumerate() {
            if index > 0 {
                pending = Some(style);
            }
            if word.is_empty() {
                continue;
            }

            let mut remaining: Vec<char> = word.chars().collect();
            let mut first_chunk = true;
            while !remaining.is_empty() {
                let gap = usize::from(pending.is_some() && used > 0);
                // A word that fits on a line of its own is moved down whole rather than split.
                if first_chunk
                    && used > 0
                    && used + gap + remaining.len() > width
                    && remaining.len() + hang_width <= width
                {
                    pending = None;
                    push_line(&mut current, &mut used);
                    continue;
                }
                if let Some(space) = pending.take() {
                    if used > 0 {
                        current.push(Span::styled(" ".to_string(), space));
                        used += 1;
                    }
                }
                let room = width.saturating_sub(used);
                if room == 0 {
                    push_line(&mut current, &mut used);
                    continue;
                }
                let take = room.min(remaining.len());
                let text: String = remaining[..take].iter().collect();
                remaining.drain(..take);
                current.push(Span::styled(text, style));
                used += take;
                first_chunk = false;
                if !remaining.is_empty() {
                    push_line(&mut current, &mut used);
                }
            }
        }
    }

    lines.push(Line::from(current));
    lines
}

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

    fn styles() -> MarkdownStyles {
        MarkdownStyles::new(
            &ColorPalette::from_theme(&crate::config::Theme::Dark),
            Style::default(),
        )
    }

    fn line_width(line: &Line<'static>) -> usize {
        line.spans.iter().map(|s| s.content.chars().count()).sum()
    }

    fn text(lines: &[Line<'static>]) -> Vec<String> {
        lines
            .iter()
            .map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect())
            .collect()
    }

    #[test]
    fn heading_loses_its_hashes_and_gains_weight() {
        let lines = render("## Deploy", &styles(), 40, "");
        assert_eq!(text(&lines), vec!["Deploy"]);
        assert!(lines[0].spans[1]
            .style
            .add_modifier
            .contains(Modifier::BOLD));
    }

    #[test]
    fn bullet_becomes_a_glyph_and_wraps_under_itself() {
        let lines = render("- alpha beta gamma delta", &styles(), 12, "");
        assert_eq!(text(&lines), vec!["• alpha beta", "  gamma", "  delta"]);
        assert!(lines.iter().all(|l| line_width(l) <= 12));
    }

    #[test]
    fn ordered_items_keep_their_numbers() {
        let lines = render("1. first\n2. second", &styles(), 40, "");
        assert_eq!(text(&lines), vec!["1. first", "2. second"]);
    }

    #[test]
    fn bold_markers_are_consumed_and_the_text_is_bold() {
        let lines = render("run **now** please", &styles(), 40, "");
        assert_eq!(text(&lines), vec!["run now please"]);
        let bold = lines[0]
            .spans
            .iter()
            .find(|s| s.content.contains("now"))
            .expect("bold span");
        assert!(bold.style.add_modifier.contains(Modifier::BOLD));
    }

    #[test]
    fn code_span_keeps_its_content_without_backticks() {
        let lines = render("call `stellar keys ls` first", &styles(), 40, "");
        assert_eq!(text(&lines), vec!["call stellar keys ls first"]);
    }

    #[test]
    fn fenced_block_is_verbatim_and_the_fences_disappear() {
        let src = "```rust\nlet x = **1**;\n```";
        let lines = render(src, &styles(), 40, "");
        assert_eq!(text(&lines), vec!["▏ let x = **1**;"]);
    }

    #[test]
    fn unclosed_emphasis_is_left_alone() {
        let lines = render("2 ** 3 is eight", &styles(), 40, "");
        assert_eq!(text(&lines), vec!["2 ** 3 is eight"]);
    }

    #[test]
    fn underscores_are_never_emphasis() {
        let lines = render("call __init__ on snake_case_name", &styles(), 60, "");
        assert_eq!(text(&lines), vec!["call __init__ on snake_case_name"]);
    }

    #[test]
    fn link_shows_label_and_target() {
        let lines = render("see [docs](https://x.dev)", &styles(), 60, "");
        assert_eq!(text(&lines), vec!["see docs (https://x.dev)"]);
    }

    #[test]
    fn rule_fills_the_width() {
        let lines = render("---", &styles(), 8, "");
        assert_eq!(text(&lines), vec!["────────"]);
    }

    #[test]
    fn indent_applies_to_every_wrapped_line() {
        let lines = render("alpha beta gamma", &styles(), 12, "  ");
        assert_eq!(text(&lines), vec!["  alpha beta", "  gamma"]);
    }

    #[test]
    fn blank_lines_survive() {
        let lines = render("one\n\ntwo", &styles(), 20, "");
        assert_eq!(text(&lines), vec!["one", "", "two"]);
    }

    #[test]
    fn a_word_longer_than_the_width_is_split_not_dropped() {
        let lines = render("CAAAAAAAAAAAAAAAA", &styles(), 8, "");
        assert_eq!(text(&lines), vec!["CAAAAAAA", "AAAAAAAA", "A"]);
    }
}