curd-editor 0.27.3

A terminal code editor: file tree, tabs, git, language servers, run and jump to errors, and a panel for Claude or any other assistant
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
//! The panel itself: the conversation so far, the question being typed, and
//! how both are drawn.

use super::*;

/// Who a line in the panel is from.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Who {
    You,
    Claude,
    /// The editor itself: what Claude did, and problems.
    Note,
    /// What an edit changed: lines put in and lines taken out.
    Diff,
    /// What a command printed.
    Output,
}

/// The panel under the text: the conversation so far and the line being
/// typed.
#[derive(Default)]
pub struct Panel {
    pub entries: Vec<(Who, String)>,
    /// The question being typed, and where the cursor is in it.
    pub input: String,
    pub(super) cursor: usize,
    /// The questions asked before, oldest first, for the Up key.
    pub(super) history: Vec<String>,
    /// Which of them is in `input`, while going through them.
    pub(super) history_at: Option<usize>,
    pub session: Option<String>,
    /// What the assistant is called, for the title ("Claude", if empty),
    /// and whether the panel decides what it may do.
    pub name: String,
    pub fixed_mode: bool,
    /// What is known about its account: shown while nothing has been
    /// asked yet.
    pub account: Account,
    /// Set where the title has to share its row: the reminder of a key
    /// in brackets is then left out.
    pub brief: bool,
    /// The model asked for (`None`: the command's own choice), and the
    /// one that last answered, by its full name.
    pub model: Option<String>,
    pub answered_by: Option<String>,
    /// Files to go along with the next question, from the project folder.
    pub attached: Vec<String>,
    pub can_edit: bool,
    /// Whether it may also run commands. Only counts with `can_edit`.
    pub can_run: bool,
    /// True while Claude is working on an answer.
    pub running: bool,
    /// When it started on the answer.
    pub(super) started: Option<Instant>,
    /// True after a step that ran a command: what comes back is shown.
    pub(super) ran_command: bool,
    /// True while the last entry is an answer still being written.
    pub(super) partial: bool,
    /// The conversation as it was last drawn: for each entry its rows,
    /// with whose it was and how long, to tell when it has changed.
    /// Drawing an answer (its Markdown, its coloured code) takes far
    /// longer than showing it, and nearly all of a long conversation
    /// stays as it is from one frame to the next.
    pub(super) drawn: Vec<(Who, usize, Vec<Row>)>,
    /// The width those rows were drawn for.
    pub(super) drawn_width: usize,
    /// The first entry that must be drawn again whatever it looks like.
    pub(super) stale_from: usize,
    /// How many rows the view is scrolled up from the newest line.
    pub(super) scroll: usize,
}

pub(super) const SPINNER: [char; 10] = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
/// The most rows the question being typed takes.
pub(super) const MAX_INPUT_ROWS: usize = 5;

pub(super) const HINTS: [&str; 6] = [
    "Ask about this project and press Enter. Alt+Enter starts a new line.",
    "Type / for commands (model, new conversation, ...) and @ to attach a file.",
    "Text selected in the file is sent along with the question.",
    "It may change files. Alt+M: read only, or also run commands. Alt+U undoes.",
    "Ctrl+R lists the earlier conversations. Ctrl+N starts a new one.",
    "Esc goes back to the text. Alt+Z makes this panel bigger.",
];

impl Panel {
    /// A panel as the editor starts with: Claude may change files.
    pub fn new() -> Self {
        Self {
            can_edit: true,
            ..Self::default()
        }
    }

    pub fn say(&mut self, who: Who, text: impl Into<String>) {
        self.entries.push((who, text.into()));
        self.stale_from = self.stale_from.min(self.entries.len() - 1);
        self.partial = false;
        // Something new: show it.
        self.scroll = 0;
    }

    /// Notes that Claude has started on an answer.
    pub fn start(&mut self) {
        self.running = true;
        self.started = Some(Instant::now());
    }

    /// Takes in what a line of output said. Returns true when the answer
    /// has ended, one way or the other.
    pub fn apply(&mut self, update: Update) -> bool {
        match update {
            Update::Session(session) => self.session = Some(session),
            Update::Model(model) => self.answered_by = Some(model),
            Update::Partial(words) => match self.entries.last_mut() {
                Some((Who::Claude, text)) if self.partial => {
                    text.push_str(&words);
                    self.stale_from = self.stale_from.min(self.entries.len() - 1);
                }
                _ => {
                    self.say(Who::Claude, words);
                    self.partial = true;
                }
            },
            // The finished piece replaces what was shown while it was
            // being written.
            Update::Text(text) => {
                if self.partial {
                    self.entries.pop();
                    self.stale_from = self.stale_from.min(self.entries.len());
                }
                self.say(Who::Claude, text);
            }
            Update::Step(step) => {
                self.ran_command = step.starts_with("Bash") || step.starts_with("Shell");
                self.say(Who::Note, step);
            }
            Update::Diff(lines) => self.say(Who::Diff, shortened(lines).join("\n")),
            // What reading or searching gave back is for the assistant;
            // what a command printed is worth seeing.
            Update::Output(printed) => {
                if std::mem::take(&mut self.ran_command) {
                    let lines = printed.trim_end().lines().map(crate::runner::clean).collect();
                    self.say(Who::Output, shortened(lines).join("\n"));
                }
            }
            Update::Problem(problem) => self.say(Who::Note, problem),
            Update::Done => self.running = false,
            Update::Failed(why) => {
                self.running = false;
                self.say(Who::Note, format!("Stopped: {why}"));
            }
        }
        !self.running
    }

    /// Alt+M: goes on to the next of what Claude may do. It may change
    /// files; then only read; then change files and run commands as well.
    pub fn next_mode(&mut self) {
        (self.can_edit, self.can_run) = match (self.can_edit, self.can_run) {
            (true, false) => (false, false),
            (false, _) => (true, true),
            (true, true) => (true, false),
        };
    }

    /// Shows an earlier conversation, to carry it on.
    pub fn resume(&mut self, id: String, entries: Vec<(Who, String)>) {
        self.entries = entries;
        self.stale_from = 0;
        self.session = Some(id);
        self.partial = false;
        self.scroll = 0;
    }

    /// Forgets the conversation, to start a new one.
    pub fn clear(&mut self) {
        self.entries.clear();
        self.stale_from = 0;
        self.session = None;
        self.scroll = 0;
    }

    /// The last thing Claude said.
    pub fn last_answer(&self) -> Option<&str> {
        self.entries
            .iter()
            .rev()
            .find(|(who, _)| *who == Who::Claude)
            .map(|(_, text)| text.as_str())
    }

    /// Scrolls `rows` towards older lines (newer, when negative).
    pub fn scroll_by(&mut self, rows: isize) {
        self.scroll = (self.scroll as isize + rows).max(0) as usize;
    }

    // ---- The line being typed ------------------------------------------

    /// Where character `at` of the question starts, in bytes.
    fn byte(&self, at: usize) -> usize {
        self.input.char_indices().nth(at).map_or(self.input.len(), |(byte, _)| byte)
    }

    pub fn type_char(&mut self, c: char) {
        let at = self.byte(self.cursor);
        self.input.insert(at, c);
        self.cursor += 1;
    }

    /// Deletes the character before the cursor. On an empty line it takes
    /// off the file attached last.
    pub fn backspace(&mut self) {
        if self.cursor > 0 {
            self.cursor -= 1;
            self.delete();
        } else if self.input.is_empty() {
            self.attached.pop();
        }
    }

    /// Attaches `file` to the next question, once.
    pub fn attach(&mut self, file: String) {
        if !self.attached.contains(&file) {
            self.attached.push(file);
        }
    }

    /// Puts `text` on the line in place of what is there.
    pub fn set_input(&mut self, text: &str) {
        self.input = text.to_string();
        self.cursor = self.input.chars().count();
    }

    /// The question as rows of at most `room` characters, and the row and
    /// column the cursor is at. Rows break where a line break was typed
    /// and where a row is full.
    fn input_rows(&self, room: usize) -> (Vec<String>, (usize, usize)) {
        let mut rows = vec![String::new()];
        let mut used = 0;
        let mut cursor = (0, 0);
        for (index, c) in self.input.chars().chain(std::iter::once('\0')).enumerate() {
            use unicode_width::UnicodeWidthChar;
            // Cells the character takes: two for a wide one, none for a
            // mark that joins the letter before it.
            let cells = c.width().unwrap_or(0);
            if used + cells.max(1) > room && c != '\n' {
                rows.push(String::new());
                used = 0;
            }
            if index == self.cursor {
                cursor = (rows.len() - 1, used);
            }
            match c {
                '\n' => {
                    rows.push(String::new());
                    used = 0;
                }
                c if cells > 0 => {
                    let row = rows.last_mut().unwrap();
                    row.push(c);
                    if cells == 2 {
                        row.push(WIDE_PAD);
                    }
                    used += cells;
                }
                _ => {}
            }
        }
        (rows, cursor)
    }

    /// How many rows at the bottom of a panel `width` wide and `height`
    /// tall the question takes, with the row above it.
    pub fn box_rows(&self, width: usize, height: usize) -> usize {
        let room = width.saturating_sub(3).max(1);
        let most = MAX_INPUT_ROWS.min(height.saturating_sub(3)).max(1);
        self.input_rows(room).0.len().min(most) + (height >= 5) as usize
    }

    /// One row that says what the next question goes with: the model, and
    /// the attached files.
    fn status(&self) -> String {
        let model = match (&self.model, &self.answered_by) {
            (Some(model), _) => model.clone(),
            (None, Some(answered)) => answered.clone(),
            (None, None) => "default model".into(),
        };
        let files: String = self.attached.iter().map(|file| format!("  @{file}")).collect();
        format!(" {model}{files}")
    }

    /// Deletes the character under the cursor.
    pub fn delete(&mut self) {
        let at = self.byte(self.cursor);
        if at < self.input.len() {
            self.input.remove(at);
        }
    }

    /// Moves the cursor `step` characters right (left, when negative),
    /// staying inside the question.
    pub fn move_cursor(&mut self, step: isize) {
        let end = self.input.chars().count() as isize;
        self.cursor = (self.cursor as isize).saturating_add(step).clamp(0, end) as usize;
    }

    /// Puts an earlier question back on the line (`step` -1), or a later
    /// one (1); past the latest, the line is empty again.
    pub fn recall(&mut self, step: isize) {
        let count = self.history.len() as isize;
        let at = self.history_at.map_or(count, |at| at as isize) + step;
        if at < 0 || count == 0 {
            return;
        }
        self.history_at = (at < count).then_some(at as usize);
        self.input = self.history_at.map(|at| self.history[at].clone()).unwrap_or_default();
        self.cursor = self.input.chars().count();
    }

    /// Takes the question off the line to send it. `None` if it is empty.
    pub fn take_input(&mut self) -> Option<String> {
        let question = self.input.trim().to_string();
        if question.is_empty() {
            return None;
        }
        self.input.clear();
        self.cursor = 0;
        self.history_at = None;
        if self.history.last() != Some(&question) {
            self.history.push(question.clone());
        }
        Some(question)
    }

    // ---- Drawing -------------------------------------------------------

    /// Entry `index` of the conversation as rows of `width` characters.
    fn entry_rows(&self, index: usize, width: usize) -> Vec<Row> {
        let (who, text) = &self.entries[index];
        let mut lines: Vec<Row> = Vec::new();
        let plain = |style: Style, text: String| vec![Span::new(style, fit(&text, width))];
        // An empty row sets each question apart from the answer before.
        if *who == Who::You && index > 0 {
            lines.push(plain(Style::Plain, String::new()));
        }
        let (style, first, rest) = match who {
            Who::You => (Style::Accent, "> ", "  "),
            Who::Note => (Style::Dim, "· ", "  "),
            // Code is shown as it is, a line a row, cut at the edge:
            // what was put in green, what was taken out red.
            Who::Diff | Who::Output => {
                for line in text.lines() {
                    let style = match (who, line.chars().next()) {
                        (Who::Diff, Some('+')) => Style::Colored(Color::Green),
                        (Who::Diff, Some('-')) => Style::Colored(Color::Red),
                        _ => Style::Dim,
                    };
                    lines.push(plain(style, format!("  {}", widen(line))));
                }
                return lines;
            }
            Who::Claude => {
                // An answer that ends in a line break does not end in an
                // empty row.
                lines.extend(markdown(text.trim_end(), width));
                return lines;
            }
        };
        for (index, line) in wrap(&widen(text), width.saturating_sub(2)).into_iter().enumerate() {
            let prefix = if index == 0 { first } else { rest };
            lines.push(plain(style, format!("{prefix}{line}")));
        }
        lines
    }

    /// Brings what is kept of the drawn conversation up to date for a
    /// panel `width` wide: only the entries that are new or have changed
    /// are drawn. Returns how many rows the conversation is.
    fn redraw(&mut self, width: usize) -> usize {
        if width != self.drawn_width {
            self.stale_from = 0;
            self.drawn_width = width;
        }
        // An entry that is not whose it was, or not as long, has changed.
        let same = self
            .entries
            .iter()
            .zip(&self.drawn)
            .take_while(|((who, text), (drawn_who, len, _))| who == drawn_who && text.len() == *len)
            .count();
        self.drawn.truncate(same.min(self.stale_from));
        for index in self.drawn.len()..self.entries.len() {
            let rows = self.entry_rows(index, width);
            let (who, text) = &self.entries[index];
            self.drawn.push((*who, text.len(), rows));
        }
        self.stale_from = self.entries.len();
        self.drawn.iter().map(|(_, _, rows)| rows.len()).sum()
    }

    /// Rows `first..first + count` of the conversation as last drawn.
    fn drawn_rows(&self, first: usize, count: usize) -> Vec<Row> {
        let mut shown = Vec::with_capacity(count);
        let mut at = 0;
        for (_, _, rows) in &self.drawn {
            if at >= first + count {
                break;
            }
            if at + rows.len() > first {
                let from = first.saturating_sub(at);
                let to = rows.len().min(first + count - at);
                shown.extend_from_slice(&rows[from..to]);
            }
            at += rows.len();
        }
        shown
    }

    /// The panel as `height` rows: a title, the conversation, a row
    /// saying what the question goes with, and the question being typed.
    /// Also where the cursor goes: column and row.
    pub fn render(&mut self, width: usize, height: usize, focused: bool) -> (Vec<Row>, (usize, usize)) {
        let state = if self.running {
            let waited = self.started.map_or(0, |started| started.elapsed().as_millis());
            let spinner = SPINNER[(waited / 120) as usize % SPINNER.len()];
            format!("{spinner} working {}s (Esc stops it)", waited / 1000)
        } else if self.fixed_mode {
            "its own settings decide what it may do".into()
        } else if self.can_edit && self.can_run {
            "may change files and run commands (Alt+M)".into()
        } else if self.can_edit {
            "may change files (Alt+M: read only)".into()
        } else {
            "read only (Alt+M: also run commands)".into()
        };
        let title_style = if focused { Style::Title } else { Style::Menu };
        let state = match state.split_once(" (") {
            Some((short, _)) if self.brief => short.to_string(),
            _ => state,
        };
        let name = if self.name.is_empty() { "Claude" } else { &self.name };
        let mut rows = vec![vec![Span::new(title_style, fit(&widen(&format!(" {name} · {state}")), width))]];

        // The question: as many rows as it needs, up to a few, keeping
        // the row with the cursor in view.
        let room = width.saturating_sub(3).max(1);
        let (question, (cursor_row, cursor_x)) = self.input_rows(room);
        let most = MAX_INPUT_ROWS.min(height.saturating_sub(3)).max(1);
        let from = (cursor_row + 1).saturating_sub(most);
        let question: Vec<&String> = question.iter().skip(from).take(most).collect();
        // The row above it only where there is room for some conversation.
        let status = (height >= 5) as usize;

        let body = height.saturating_sub(1 + status + question.len());
        let total = self.redraw(width);
        self.scroll = self.scroll.min(total.saturating_sub(body));
        let first = total.saturating_sub(body + self.scroll);
        let mut shown = self.drawn_rows(first, body);
        if shown.is_empty() {
            // Before anything is asked: where things stand with its
            // program and its account, and what to do first.
            let name = if self.name.is_empty() { "Claude" } else { &self.name };
            let first: Vec<(Style, String)> = match &self.account {
                Account::Missing(install) => vec![
                    (Style::Bold, format!("{name} is not installed on this machine.")),
                    (Style::Plain, format!("To install it: {install}")),
                    (Style::Dim, "Then open this panel again.".into()),
                ],
                Account::SignedOut => vec![
                    (Style::Bold, format!("You are not signed in to {name}.")),
                    (Style::Plain, "Press Enter to sign in. Its sign-in page opens in your browser,".into()),
                    (Style::Plain, "and you come back here when it is done.".into()),
                ],
                Account::SignedIn(who) if !who.is_empty() => vec![(Style::Bold, who.clone())],
                _ => Vec::new(),
            };
            let ready = !matches!(self.account, Account::Missing(_) | Account::SignedOut);
            let hints = HINTS.iter().filter(|_| ready).map(|hint| (Style::Dim, hint.to_string()));
            let lines = first.into_iter().chain(hints).take(body);
            shown.extend(lines.map(|(style, line)| vec![Span::new(style, fit(&widen(&line), width))]));
        }
        shown.resize(body, vec![Span::new(Style::Plain, fit("", width))]);
        rows.extend(shown);

        if status > 0 {
            rows.push(vec![Span::new(Style::FieldNote, fit(&self.status(), width))]);
        }
        let first_row = rows.len();
        for (index, row) in question.iter().enumerate() {
            let mark = if index + from == 0 { "> " } else { "  " };
            rows.push(vec![Span::new(Style::Field, fit(&format!("{mark}{row}"), width))]);
        }
        rows.truncate(height);
        let cursor = (2 + cursor_x, (first_row + cursor_row - from).min(height.saturating_sub(1)));
        (rows, cursor)
    }
}