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
//! The whole window: a project folder with its file tree, the open files
//! in tabs, quick open, and the language servers they share.
//!
//! Each open file is an `Editor`. The workspace decides which one is in
//! front, routes keys, mouse clicks and language-server messages to the
//! right place, and puts the pieces of the screen together.

use std::cell::RefCell;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender};
use std::time::{Duration, Instant};

use crossterm::event::{
    Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent, MouseEventKind,
};
use serde_json::Value;

use crate::agent::{self, Account, AgentSpec, Change, ChangeKind, Format, Panel, Request, Snapshot, Who};
use crate::document::Document;
use crate::editor::Editor;
use crate::finder::{self, Finder};
use crate::git::{self, GitInfo};
use crate::lsp::{find_root, Client, Reply, ServerSpec};
use crate::runner::{self, Output};
use crate::screen::{fit, overlay, place, widen, Row, Screen, Span, Style, Zone};
use crate::theme::Theme;
use crate::search::{self, Hit};
use crate::terminal::Terminal;
use crate::tree::Tree;

mod files;
mod servers;
mod git_menu;
mod run_panel;
mod commands;
mod assistants;
mod events;
mod draw;
#[cfg(test)]
mod tests;

use git_menu::*;
use commands::*;
use assistants::*;

/// How long typing must pause before edits are sent to the language server.
/// Sending them in batches keeps the server from re-checking on every key.
const LSP_DEBOUNCE: Duration = Duration::from_millis(30);
/// Width of the file tree, on screens wide enough for it.
const TREE_WIDTH: usize = 30;
/// Lines moved by one notch of the mouse wheel.
const WHEEL_LINES: isize = 3;
/// Two clicks on the same spot within this long are a double click.
const DOUBLE_CLICK: Duration = Duration::from_millis(400);
/// Shown at the start of the tab bar when there are tabs before the
/// first one in view.
const MORE_TABS: &str = " < ";
/// The mark on each tab that closes it when clicked.
const CLOSE_ICON: char = '×';
/// How often the screen is redrawn while Claude works, to show the time.
const AGENT_TICK: Duration = Duration::from_millis(120);
/// With this much room beside the file tree, the Claude panel stands to
/// the right of the text, the full height of the window; with less, it
/// lies under the text.
const AGENT_SIDE_MIN: usize = 100;
/// The least room the text keeps beside the panel, and the panel's least.
const TEXT_MIN_WIDTH: usize = 40;
const AGENT_MIN_WIDTH: usize = 30;
/// The most selected text sent along with a question to Claude.
const MAX_SELECTION_CHARS: usize = 8000;
/// Most matches shown by quick open.
const FINDER_ROWS: usize = 8;
/// The widest a list that pops up over the text gets.
const POPUP_WIDTH: usize = 80;
/// What the keys do in a list, shown at its right where there is room.
const POPUP_HINT: &str = "↑↓ choose  Enter pick  Esc close ";

/// What the list over the text is being used for.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Picker {
    /// Quick open.
    Files,
    /// Asking what to search the project for.
    Search,
    /// The lines a project search found.
    Results,
    /// The git commands.
    Git,
    Branches,
    /// Asking for a commit message.
    Commit,
    /// Asking for the name of a new branch.
    NewBranch,
    /// The earlier conversations with Claude.
    Sessions,
    /// Asking for a command to run.
    Run,
    /// Asking for the name of a new file, a new folder, or a new name.
    NewFile,
    NewFolder,
    Rename,
    /// Every command of the editor, with its key.
    Commands,
    /// The `/` commands of the Claude panel.
    Slash,
    /// A file to attach to the next question for Claude.
    Attach,
    /// The models Claude can answer with.
    Model,
    /// Asking for a model by its full name.
    ModelName,
    /// The assistants the panel can talk to.
    Agent,
}

impl Picker {
    fn prompt(self) -> &'static str {
        match self {
            Self::Files => " Open file: ",
            Self::Search => " Search project: ",
            Self::Results => " Matches: ",
            Self::Git => " Git: ",
            Self::Branches => " Switch to branch: ",
            Self::Commit => " Commit message: ",
            Self::NewBranch => " New branch: ",
            Self::Sessions => " Earlier conversations: ",
            Self::Run => " Run: ",
            Self::NewFile => " New file: ",
            Self::NewFolder => " New folder: ",
            Self::Rename => " Rename to: ",
            Self::Commands => " Command: ",
            Self::Slash => " /",
            Self::Attach => " Attach file: ",
            Self::Model => " Model: ",
            Self::ModelName => " Model name: ",
            Self::Agent => " Assistant: ",
        }
    }

    /// True for the ones that belong to the Claude panel: they open there,
    /// over the question, not over the text.
    fn is_for_claude(self) -> bool {
        matches!(
            self,
            Self::Slash | Self::Attach | Self::Model | Self::ModelName | Self::Sessions | Self::Agent
        )
    }

    /// True for the ones that ask for text instead of offering a list.
    fn is_question(self) -> bool {
        matches!(
            self,
            Self::Search
                | Self::Commit
                | Self::NewBranch
                | Self::Run
                | Self::NewFile
                | Self::NewFolder
                | Self::Rename
                | Self::ModelName
        )
    }
}

/// How long the thread that reads keys waits for one before it looks
/// whether another program has been given the terminal.
pub const INPUT_WAIT: Duration = Duration::from_millis(250);

/// Everything the workspace reacts to. Input, language-server messages and
/// git results come from separate threads into one queue, so the editor
/// sleeps until there is something to do instead of polling.
pub enum AppEvent {
    Input(Event),
    /// A message from the language server with this number, or `None` when
    /// it has exited.
    Lsp(usize, Option<Value>),
    /// Fresh git state for the project (`None` if it is not in git).
    Git(Option<GitInfo>),
    /// The lines of the file at this path as they were in the last commit
    /// (`None` if it is not in one).
    Committed(String, Option<Vec<String>>),
    /// The name of the last commit, as it is now (see `git::head`).
    Head(Option<String>),
    /// A git command from the menu finished: what to say about it.
    GitDone(String),
    /// A line printed by run number so-and-so of the `claude` command, or
    /// `None` when it has finished.
    Agent(u64, Option<String>),
    /// Something from run number so-and-so of a command the user ran.
    Run(u64, runner::Event),
    /// What the assistant at this place said when asked who is signed in,
    /// and whether its command ended well.
    Account(usize, String, bool),
}

/// Which part of the window the keys go to.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Focus {
    Editor,
    Tree,
    /// The Claude panel.
    Agent,
    /// What the command that was run printed.
    Output,
}

/// A running language server and what it was started for.
struct Server {
    id: usize,
    /// Command and project folder: files with the same key share a server.
    key: String,
    client: Rc<RefCell<Client>>,
}

/// Where a list that pops up is on the screen.
#[derive(Clone, Copy, Debug, PartialEq)]
struct Popup {
    /// Its left edge and its width.
    x: usize,
    width: usize,
    /// The row that is typed on.
    input_y: usize,
    /// The row of the first item shown, and how many rows the list can
    /// take at most.
    list_y: usize,
    capacity: usize,
}

/// Where the parts of the window are.
struct Layout {
    /// Rows taken by the tab bar: 1 when several files are open, else 0.
    tabs: usize,
    /// Columns taken by the file tree and the line beside it; 0 if hidden.
    tree: usize,
    /// Rows taken under the text by what a command printed; 0 if hidden.
    output: usize,
    /// Rows taken by the Claude panel when it lies under the text; 0 if
    /// it is hidden or stands beside the text.
    agent: usize,
    /// Columns taken by the Claude panel and the line beside it when it
    /// stands to the right of the text; 0 otherwise.
    agent_side: usize,
    pane_width: usize,
    /// Rows for the text and its status bar, above the Claude panel.
    pane_height: usize,
}

pub struct Workspace {
    /// The open files, in tab order.
    editors: Vec<Editor>,
    /// The one in front.
    active: usize,
    tree: Tree,
    show_tree: bool,
    focus: Focus,
    git: Option<GitInfo>,
    /// The last commit the open files were compared with. `None` until
    /// git has answered the first time: `Some(None)` then means there is
    /// no commit to compare with.
    git_head: Option<Option<String>>,
    /// Quick open, while it is on screen.
    finder: Option<Finder>,
    /// What that list is for.
    picker: Picker,
    /// The lines the last project search found, in the order listed.
    hits: Vec<Hit>,
    /// The text last copied or cut, which Ctrl+V pastes.
    clipboard: String,
    /// What the command that was last run printed.
    output: Output,
    show_output: bool,
    /// That command, while it runs.
    run_child: Option<std::process::Child>,
    /// Counts the runs, so output from one that was stopped is ignored.
    run_number: u64,
    /// The folder a new file or folder goes in, while its name is asked
    /// for; the file or folder being renamed, while its new name is.
    file_target: PathBuf,
    /// What `d` in the tree was pressed on once, waiting for the second
    /// press that deletes it.
    delete_pending: Option<PathBuf>,
    /// The page of keyboard shortcuts, while it is open: its first row.
    help: Option<usize>,
    /// The Claude panel and its conversation.
    agent: Panel,
    show_agent: bool,
    /// The height the panel was given with the keys or the mouse; `None`
    /// for the usual two fifths.
    agent_rows: Option<usize>,
    /// The same for its width, when it stands beside the text.
    agent_cols: Option<usize>,
    /// The earlier conversations on offer in the list, in its order.
    agent_sessions: Vec<agent::SessionInfo>,
    /// The folder `~/.claude` is in, when it is not the user's home (tests).
    agent_home: Option<PathBuf>,
    /// True while the mouse is dragging the panel's top edge.
    resizing_agent: bool,
    /// The `claude` command while it is working on an answer.
    agent_child: Option<std::process::Child>,
    /// The project's files as they were before Claude's last answer, and
    /// what it changed in them: for the summary and for undoing it.
    agent_snapshot: Option<Snapshot>,
    agent_changes: Vec<Change>,
    /// Counts the runs, so output from one that was stopped is ignored.
    agent_run: u64,
    /// The CURD_AGENT setting: "off", or a command to use instead.
    pub agent_setting: Option<String>,
    /// The assistants the panel can talk to, and which one it does.
    agents: Vec<AgentSpec>,
    /// The file the choice of assistant is kept in (agents.json), if it
    /// is to be kept.
    pub agents_file: Option<PathBuf>,
    /// The panels of the assistants that are not in front, by the
    /// assistant's place in `agents`. (The place of the one in front
    /// holds nothing.)
    parked: Vec<Parked>,
    /// The number given to the last answer asked for, of any assistant.
    next_run: u64,
    /// Where each assistant's tab is in the title of the panel, on the
    /// screen as last drawn: row, first column, column after the last.
    agent_tabs: Vec<(usize, usize, usize)>,
    agent_index: usize,
    /// A command waiting to be given the whole terminal (to sign in, or
    /// one that asks questions), and what to call it.
    terminal_job: Option<(Vec<String>, String)>,
    /// Set while another program has the terminal: the thread that reads
    /// keys leaves them alone.
    pub input_paused: std::sync::Arc<std::sync::atomic::AtomicBool>,
    /// When and where the text was last clicked, to tell a double click.
    last_click: Option<(Instant, usize, usize)>,
    /// Copied text still to be handed to the terminal's clipboard.
    clipboard_out: Option<String>,
    servers: Vec<Server>,
    next_server: usize,
    /// Where background threads send their results. `None` in tests, which
    /// start no language servers and no git.
    events: Option<Sender<AppEvent>>,
    /// The CURD_LSP setting: "off", or a command to use instead.
    lsp_setting: Option<String>,
    /// Shown in the status bar when no file is open.
    message: String,
    /// True after Ctrl+Q was pressed once with unsaved changes.
    quit_pending: bool,
    /// The same for Ctrl+W.
    close_pending: bool,
    should_quit: bool,
    size: (usize, usize),
    screen: Screen,
}

impl Workspace {
    /// A workspace for the project in `root`, with no file open yet.
    pub fn new(
        root: PathBuf,
        events: Option<Sender<AppEvent>>,
        lsp_setting: Option<String>,
    ) -> Self {
        Self {
            editors: Vec::new(),
            active: 0,
            tree: Tree::new(root),
            show_tree: false,
            focus: Focus::Editor,
            git: None,
            git_head: None,
            finder: None,
            picker: Picker::Files,
            hits: Vec::new(),
            clipboard: String::new(),
            // Changing files is what the panel is mostly for; Alt+M makes
            // it read only.
            output: Output::default(),
            show_output: false,
            run_child: None,
            run_number: 0,
            file_target: PathBuf::new(),
            delete_pending: None,
            help: None,
            agent: panel_for(&AgentSpec::claude()),
            agent_snapshot: None,
            agent_changes: Vec::new(),
            show_agent: false,
            agent_rows: None,
            agent_cols: None,
            agent_sessions: Vec::new(),
            agent_home: None,
            resizing_agent: false,
            agent_child: None,
            agent_run: 0,
            agent_setting: None,
            agents: vec![AgentSpec::claude(), AgentSpec::cursor(), AgentSpec::opencode()],
            agents_file: None,
            parked: [AgentSpec::claude(), AgentSpec::cursor(), AgentSpec::opencode()]
                .iter()
                .enumerate()
                .map(|(index, spec)| match index {
                    // Claude's is the one in front.
                    0 => Parked::default(),
                    _ => Parked { panel: panel_for(spec), ..Parked::default() },
                })
                .collect(),
            next_run: 0,
            agent_tabs: Vec::new(),
            agent_index: 0,
            terminal_job: None,
            input_paused: Default::default(),
            last_click: None,
            clipboard_out: None,
            servers: Vec::new(),
            next_server: 0,
            events,
            lsp_setting,
            message: String::new(),
            quit_pending: false,
            close_pending: false,
            should_quit: false,
            size: (0, 0),
            screen: Screen::default(),
        }
    }

    /// Starts with an empty file that has no name, as `curd` with no
    /// arguments does.
    pub fn open_empty(&mut self) {
        self.editors.push(Editor::new(Document::default()));
        self.active = self.editors.len() - 1;
        self.focus = Focus::Editor;
    }

    /// Shows the file tree and puts the keys there.
    pub fn show_folder(&mut self) {
        self.show_tree = true;
        self.focus = Focus::Tree;
    }

    /// Tells every open file which branch the project is on, for its
    /// status bar.
    fn show_branch(&mut self) {
        let branch = self.git.as_ref().map(|git| git.branch.clone());
        for editor in &mut self.editors {
            editor.branch = branch.clone();
        }
    }

    /// Sets the colours the window is drawn in.
    pub fn set_theme(&mut self, theme: Theme) {
        // Everything on screen is drawn again in the new colours.
        self.screen = Screen::with_theme(theme);
    }

    pub fn has_files(&self) -> bool {
        !self.editors.is_empty()
    }
}