seq-repl 7.7.2

TUI REPL for the Seq programming language with IR visualization
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
//! REPL Pane Widget
//!
//! Displays the REPL interface with:
//! - Command history with syntax highlighting
//! - Current input line with cursor
//! - Output/result display

use crate::ui::highlight::{TokenKind, tokenize};
use ratatui::{
    buffer::Buffer,
    layout::Rect,
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Paragraph, Widget, Wrap},
};
use vim_line::history::{Recall, Store as HistoryStore};

/// Prompt shown for continuation lines in multiline input
const CONTINUATION_PROMPT: &str = ".... ";

/// Map a token kind to its display style.
fn token_style(kind: TokenKind) -> Style {
    match kind {
        TokenKind::Keyword => Style::default()
            .fg(Color::Magenta)
            .add_modifier(Modifier::BOLD),
        TokenKind::Builtin => Style::default().fg(Color::Cyan),
        TokenKind::DefMarker | TokenKind::DefEnd => Style::default()
            .fg(Color::Yellow)
            .add_modifier(Modifier::BOLD),
        TokenKind::Integer | TokenKind::Float => Style::default().fg(Color::Blue),
        TokenKind::Boolean => Style::default().fg(Color::Magenta),
        TokenKind::String => Style::default().fg(Color::Green),
        TokenKind::Comment => Style::default().fg(Color::DarkGray),
        TokenKind::TypeName => Style::default().fg(Color::Green),
        TokenKind::StackEffect => Style::default().fg(Color::DarkGray),
        TokenKind::Quotation => Style::default()
            .fg(Color::Yellow)
            .add_modifier(Modifier::BOLD),
        TokenKind::Include => Style::default()
            .fg(Color::Magenta)
            .add_modifier(Modifier::BOLD),
        TokenKind::ModulePath => Style::default().fg(Color::Cyan),
        TokenKind::Identifier => Style::default().fg(Color::White),
        TokenKind::Whitespace => Style::default(),
        TokenKind::Unknown => Style::default().fg(Color::Red),
    }
}

/// A single entry in the REPL history
#[derive(Debug, Clone)]
pub(crate) struct HistoryEntry {
    /// The input that was entered
    pub(crate) input: String,
    /// The output/result (if any)
    pub(crate) output: Option<String>,
    /// Whether this entry had an error
    pub(crate) is_error: bool,
}

impl HistoryEntry {
    /// Create a new history entry
    pub(crate) fn new(input: impl Into<String>) -> Self {
        Self {
            input: input.into(),
            output: None,
            is_error: false,
        }
    }

    /// Set the output
    pub(crate) fn with_output(mut self, output: impl Into<String>) -> Self {
        self.output = Some(output.into());
        self
    }

    /// Mark as an error
    pub(crate) fn with_error(mut self, error: impl Into<String>) -> Self {
        self.output = Some(error.into());
        self.is_error = true;
        self
    }
}

/// The REPL pane state.
///
/// Two related-but-distinct collections live here:
///
/// - `history` is the *rendered transcript* — every input with its output /
///   error, drawn by [`ReplPane`]. Duplicates and failures are preserved
///   so the user sees their session as it actually happened.
/// - `store` is the *navigation store* — a deduped ring of just the input
///   strings, owning recall (`k`/`j`, arrows), search, and the draft stash.
///   It is the [`vim_line::history::Store`] shared with other vim-line
///   consumers; persistence reads/writes it.
#[derive(Debug, Clone, Default)]
pub(crate) struct ReplState {
    /// Rendered transcript of past inputs + outputs.
    pub(crate) history: Vec<HistoryEntry>,
    /// Navigation/search store backing `k`/`j`/`/`.
    pub(crate) store: HistoryStore,
    /// Current input line
    pub(crate) input: String,
    /// Cursor position in the input
    pub(crate) cursor: usize,
}

impl ReplState {
    /// Create a new REPL state
    pub(crate) fn new() -> Self {
        Self::default()
    }

    /// Append `entry` to the transcript and record its input in the
    /// navigation store. The store handles dedup/bounds internally.
    pub(crate) fn add_entry(&mut self, entry: HistoryEntry) {
        self.store.push(entry.input.clone());
        self.history.push(entry);
    }

    /// Clear the current input and abandon any in-progress history browse,
    /// restoring the draft via the store.
    pub(crate) fn clear_input(&mut self) {
        let _ = self.store.cancel_recall();
        self.input.clear();
        self.cursor = 0;
    }

    /// Get the current input
    pub(crate) fn current_input(&self) -> &str {
        &self.input
    }

    /// Navigate to the previous command in history (up arrow / k at first line).
    pub(crate) fn history_up(&mut self) {
        if let Some(Recall::Entry(entry)) = self.store.prev(&self.input) {
            self.input = entry.to_string();
            self.cursor = self.input.len();
        }
    }

    /// Navigate to the next command in history (down arrow / j at last line).
    pub(crate) fn history_down(&mut self) {
        match self.store.next() {
            Some(Recall::Entry(entry)) => {
                self.input = entry.to_string();
                self.cursor = self.input.len();
            }
            Some(Recall::Draft(draft)) => {
                self.input = draft.to_string();
                self.cursor = self.input.len();
            }
            None => {} // not browsing — leave input alone
        }
    }
}

/// The REPL pane widget
pub(crate) struct ReplPane<'a> {
    /// The REPL state
    state: &'a ReplState,
    /// Whether this pane is focused
    focused: bool,
    /// The prompt string
    prompt: &'a str,
}

impl<'a> ReplPane<'a> {
    /// Create a new REPL pane
    pub(crate) fn new(state: &'a ReplState) -> Self {
        Self {
            state,
            focused: true,
            prompt: "seq> ",
        }
    }

    /// Set whether the pane is focused
    pub(crate) fn focused(mut self, focused: bool) -> Self {
        self.focused = focused;
        self
    }

    /// Set the prompt string
    pub(crate) fn prompt(mut self, prompt: &'a str) -> Self {
        self.prompt = prompt;
        self
    }

    /// Styled prompt for the `i`-th line of a (possibly multiline) input —
    /// main prompt on line 0, continuation prompt elsewhere.
    fn prompt_span(&self, i: usize) -> Span<'a> {
        let prompt = if i == 0 {
            self.prompt
        } else {
            CONTINUATION_PROMPT
        };
        Span::styled(prompt.to_string(), Style::default().fg(Color::Green))
    }

    /// Highlight a line of Seq code
    fn highlight_code(&self, code: &str) -> Line<'a> {
        let spans: Vec<Span> = tokenize(code)
            .into_iter()
            .map(|token| Span::styled(token.text, token_style(token.kind)))
            .collect();
        Line::from(spans)
    }

    /// Build the display lines
    fn build_lines(&self) -> Vec<Line<'a>> {
        let mut lines = Vec::new();

        // Render history (with multiline support)
        for entry in &self.state.history {
            // Split input by newlines for multiline history entries
            for (i, input_line) in entry.input.split('\n').enumerate() {
                let mut spans = vec![self.prompt_span(i)];
                spans.extend(self.highlight_code(input_line).spans);
                lines.push(Line::from(spans));
            }

            // Output line (if any)
            if let Some(output) = &entry.output {
                let style = if entry.is_error {
                    Style::default().fg(Color::Red)
                } else {
                    Style::default().fg(Color::White)
                };
                for line in output.lines() {
                    lines.push(Line::from(Span::styled(format!("  {}", line), style)));
                }
            }
        }

        // Current input with multiline support
        let input_lines: Vec<&str> = self.state.input.split('\n').collect();

        // Find which line the cursor is on and the column within that line
        let (cursor_line, cursor_col) = if self.focused {
            let mut line_idx = 0;
            let mut col = self.state.cursor;
            let mut pos = 0;
            for (i, line_text) in input_lines.iter().enumerate() {
                let line_end = pos + line_text.len();
                if self.state.cursor <= line_end {
                    line_idx = i;
                    col = self.state.cursor - pos;
                    break;
                }
                pos = line_end + 1; // +1 for the newline character
                line_idx = i + 1; // cursor is past this line
            }
            // Clamp line_idx to valid range (handles cursor after trailing newline)
            line_idx = line_idx.min(input_lines.len().saturating_sub(1));
            let col = col.min(input_lines.get(line_idx).map_or(0, |l| l.len()));
            (line_idx, col)
        } else {
            (0, 0)
        };

        // Render each input line
        for (i, line_text) in input_lines.iter().enumerate() {
            let mut spans = vec![self.prompt_span(i)];

            if self.focused && i == cursor_line {
                // This line has the cursor - split at cursor position
                let col = cursor_col.min(line_text.len());
                let (before, after) = line_text.split_at(col);

                if !before.is_empty() {
                    spans.extend(self.highlight_code(before).spans);
                }

                // Cursor character (block cursor)
                let cursor_char = if after.is_empty() {
                    " "
                } else {
                    &after[..after.chars().next().map_or(0, |c| c.len_utf8())]
                };
                spans.push(Span::styled(
                    cursor_char.to_string(),
                    Style::default().bg(Color::White).fg(Color::Black),
                ));

                // Rest after cursor
                if !after.is_empty() && after.len() > cursor_char.len() {
                    spans.extend(self.highlight_code(&after[cursor_char.len()..]).spans);
                }
            } else {
                // No cursor on this line
                spans.extend(self.highlight_code(line_text).spans);
            }

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

        lines
    }
}

impl Widget for &ReplPane<'_> {
    fn render(self, area: Rect, buf: &mut Buffer) {
        // No border for REPL - it's the primary interface
        let lines = self.build_lines();

        // Ask the actual Paragraph how tall it will render at this width
        // (issue #491). Our previous estimate was `ceil(chars/width)` per
        // source line, which underestimates by one row each time a single
        // word is too long to fit in the remaining space: ratatui's
        // word-wrap pushes the long word to a fresh line first, then
        // hard-breaks across columns. After enough such lines the bottom
        // (input prompt) scrolls below the visible area and looks like
        // the REPL has stopped accepting input.
        let paragraph = Paragraph::new(lines).wrap(Wrap { trim: false });
        let display_height = paragraph.line_count(area.width).min(u16::MAX as usize) as u16;
        let scroll = display_height.saturating_sub(area.height);

        paragraph.scroll((scroll, 0)).render(area, buf);
    }
}

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

    #[test]
    fn test_history_entry() {
        let entry = HistoryEntry::new("5 dup").with_output("5 5");
        assert_eq!(entry.input, "5 dup");
        assert_eq!(entry.output.as_deref(), Some("5 5"));
        assert!(!entry.is_error);

        let error = HistoryEntry::new("bad").with_error("unknown word");
        assert!(error.is_error);
    }

    #[test]
    fn test_repl_pane_render() {
        let mut state = ReplState::new();
        state.add_entry(HistoryEntry::new("42 dup").with_output("42 42"));
        state.input = "swap".to_string();

        let pane = ReplPane::new(&state);

        let area = Rect::new(0, 0, 40, 10);
        let mut buf = Buffer::empty(area);
        (&pane).render(area, &mut buf);

        // Just verify it doesn't panic
    }

    #[test]
    fn test_highlight_code() {
        let state = ReplState::new();
        let pane = ReplPane::new(&state);

        let line = pane.highlight_code("42 dup add");
        assert!(!line.spans.is_empty());
    }

    #[test]
    fn test_multiline_input_rendering() {
        let mut state = ReplState::new();
        state.input = "foo\nbar\nbaz".to_string();
        state.cursor = 4; // At 'b' in "bar"

        let pane = ReplPane::new(&state).focused(true);
        let lines = pane.build_lines();

        // Should have 3 lines for the multiline input
        assert_eq!(lines.len(), 3);

        // First line should have the main prompt "seq> "
        let first_line_text: String = lines[0].spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(first_line_text.starts_with("seq> "));
        assert!(first_line_text.contains("foo"));

        // Second line should have continuation prompt ".... "
        let second_line_text: String = lines[1].spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(second_line_text.starts_with(".... "));
    }

    #[test]
    fn test_cursor_position_trailing_newline() {
        let mut state = ReplState::new();
        // Input with trailing newline: "foo\n"
        // After split: ["foo", ""]
        // Cursor at position 4 (after the newline)
        state.input = "foo\n".to_string();
        state.cursor = 4;

        let pane = ReplPane::new(&state).focused(true);
        let lines = pane.build_lines();

        // Should render without panic (the bug was out-of-bounds access)
        assert_eq!(lines.len(), 2); // "foo" and empty line
    }

    #[test]
    fn test_cursor_position_empty_lines() {
        let mut state = ReplState::new();
        // Input with empty line in the middle: "foo\n\nbar"
        state.input = "foo\n\nbar".to_string();
        state.cursor = 4; // At the empty line

        let pane = ReplPane::new(&state).focused(true);
        let lines = pane.build_lines();

        // Should have 3 lines
        assert_eq!(lines.len(), 3);
    }

    #[test]
    fn test_multiline_history_entry() {
        let mut state = ReplState::new();
        state.add_entry(HistoryEntry::new("line1\nline2").with_output("result"));

        let pane = ReplPane::new(&state);
        let lines = pane.build_lines();

        // History: 2 lines for input + 1 for output + 1 for current empty input
        assert!(lines.len() >= 3);
    }
}