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, Change, ChangeKind, 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;
#[cfg(test)]
mod tests;
const LSP_DEBOUNCE: Duration = Duration::from_millis(30);
const TREE_WIDTH: usize = 30;
const WHEEL_LINES: isize = 3;
const DOUBLE_CLICK: Duration = Duration::from_millis(400);
const CLOSE_ICON: char = '×';
const AGENT_TICK: Duration = Duration::from_millis(120);
const AGENT_SIDE_MIN: usize = 100;
const TEXT_MIN_WIDTH: usize = 40;
const AGENT_MIN_WIDTH: usize = 30;
const MAX_SELECTION_CHARS: usize = 8000;
const FINDER_ROWS: usize = 8;
const POPUP_WIDTH: usize = 80;
const POPUP_HINT: &str = "↑↓ choose Enter pick Esc close ";
#[derive(Clone, Copy, Debug, PartialEq)]
enum Picker {
Files,
Search,
Results,
Git,
Branches,
Commit,
NewBranch,
Sessions,
Run,
NewFile,
NewFolder,
Rename,
Commands,
Slash,
Attach,
Model,
ModelName,
}
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: ",
}
}
fn is_for_claude(self) -> bool {
matches!(self, Self::Slash | Self::Attach | Self::Model | Self::ModelName | Self::Sessions)
}
fn is_question(self) -> bool {
matches!(
self,
Self::Search
| Self::Commit
| Self::NewBranch
| Self::Run
| Self::NewFile
| Self::NewFolder
| Self::Rename
| Self::ModelName
)
}
}
#[derive(Clone, Copy, PartialEq)]
enum Target {
Window,
Text,
Tree,
Claude,
}
const NONE: KeyModifiers = KeyModifiers::NONE;
const CTRL: KeyModifiers = KeyModifiers::CONTROL;
const ALT: KeyModifiers = KeyModifiers::ALT;
const COMMANDS: [(&str, &str, Target, KeyCode, KeyModifiers); 48] = [
("Open a file by name", "Ctrl+P", Target::Window, KeyCode::Char('p'), CTRL),
("Search the whole project", "Alt+S", Target::Window, KeyCode::Char('s'), ALT),
("Show or hide the file tree", "Ctrl+B", Target::Window, KeyCode::Char('b'), CTRL),
("New file", "n in the tree", Target::Tree, KeyCode::Char('n'), NONE),
("New folder", "f in the tree", Target::Tree, KeyCode::Char('f'), NONE),
("Rename the selected file or folder", "r in the tree", Target::Tree, KeyCode::Char('r'), NONE),
("Delete the selected file or folder", "d in the tree", Target::Tree, KeyCode::Char('d'), NONE),
("Save", "Ctrl+S", Target::Text, KeyCode::Char('s'), CTRL),
("Close this file", "Ctrl+W", Target::Window, KeyCode::Char('w'), CTRL),
("Next tab", "Alt+.", Target::Window, KeyCode::Char('.'), ALT),
("Previous tab", "Alt+,", Target::Window, KeyCode::Char(','), ALT),
("Run a command (build, test, start)", "Ctrl+T", Target::Window, KeyCode::Char('t'), CTRL),
("Run the last command again", "F5", Target::Window, KeyCode::F(5), NONE),
("Show or hide what the command printed", "Alt+T", Target::Window, KeyCode::Char('t'), ALT),
("Go to the next error in what it printed", "F8", Target::Window, KeyCode::F(8), NONE),
("Go to the error before", "Shift+F8", Target::Window, KeyCode::F(8), KeyModifiers::SHIFT),
("Ask Claude", "Alt+I", Target::Claude, KeyCode::Null, NONE),
("Claude: earlier conversations", "Ctrl+R there", Target::Claude, KeyCode::Char('r'), CTRL),
("Claude: new conversation", "Ctrl+N there", Target::Claude, KeyCode::Char('n'), CTRL),
("Claude: what it may do", "Alt+M there", Target::Claude, KeyCode::Char('m'), ALT),
("Claude: undo its changes", "Alt+U there", Target::Claude, KeyCode::Char('u'), ALT),
("Claude: open the files it changed", "Alt+O there", Target::Claude, KeyCode::Char('o'), ALT),
("Git: stage, commit, branches, pull, push", "Ctrl+G", Target::Window, KeyCode::Char('g'), CTRL),
("Undo", "Ctrl+Z", Target::Text, KeyCode::Char('z'), CTRL),
("Redo", "Ctrl+Y", Target::Text, KeyCode::Char('y'), CTRL),
("Find in this file", "Ctrl+F", Target::Text, KeyCode::Char('f'), CTRL),
("Find the next match", "F3", Target::Text, KeyCode::F(3), NONE),
("Replace in this file", "Ctrl+R", Target::Text, KeyCode::Char('r'), CTRL),
("Go to a line by number", "Ctrl+L", Target::Text, KeyCode::Char('l'), CTRL),
("Select everything", "Ctrl+A", Target::Text, KeyCode::Char('a'), CTRL),
("Copy", "Ctrl+C", Target::Text, KeyCode::Char('c'), CTRL),
("Cut", "Ctrl+X", Target::Text, KeyCode::Char('x'), CTRL),
("Paste", "Ctrl+V", Target::Text, KeyCode::Char('v'), CTRL),
("Comment or uncomment lines", "Alt+C", Target::Text, KeyCode::Char('c'), ALT),
("Duplicate the line", "Alt+D", Target::Text, KeyCode::Char('d'), ALT),
("Move the line up", "Alt+Up", Target::Text, KeyCode::Up, ALT),
("Move the line down", "Alt+Down", Target::Text, KeyCode::Down, ALT),
("Indent the selected lines", "Tab", Target::Text, KeyCode::Tab, NONE),
("Unindent the line or the selected lines", "Shift+Tab", Target::Text, KeyCode::BackTab, NONE),
("Fold or unfold the block here", "Alt+K", Target::Text, KeyCode::Char('k'), ALT),
("Fold or unfold every block", "Alt+A", Target::Text, KeyCode::Char('a'), ALT),
("Suggestions from the language server", "Ctrl+Space", Target::Text, KeyCode::Char(' '), CTRL),
("Explain what is under the cursor (hover)", "Alt+H", Target::Text, KeyCode::Char('h'), ALT),
("Go to the definition", "Alt+G", Target::Text, KeyCode::Char('g'), ALT),
("Go to the start of the file", "Ctrl+Home", Target::Text, KeyCode::Home, CTRL),
("Go to the end of the file", "Ctrl+End", Target::Text, KeyCode::End, CTRL),
("Move between the tree and the text", "Alt+E", Target::Window, KeyCode::Char('e'), ALT),
("Quit", "Ctrl+Q", Target::Window, KeyCode::Char('q'), CTRL),
];
const SLASH: [(&str, &str, KeyCode, KeyModifiers); 12] = [
("model", "choose the model that answers", KeyCode::Null, NONE),
("attach", "attach a file to the next question (also @)", KeyCode::Null, NONE),
("detach", "take the attached files off again", KeyCode::Null, NONE),
("new", "start a new conversation", KeyCode::Char('n'), CTRL),
("resume", "carry on an earlier conversation", KeyCode::Char('r'), CTRL),
("mode", "what Claude may do: change files, read, run commands", KeyCode::Char('m'), ALT),
("undo", "put the files Claude changed back as they were", KeyCode::Char('u'), ALT),
("changes", "open the files Claude changed", KeyCode::Char('o'), ALT),
("copy", "copy the last answer", KeyCode::Char('c'), ALT),
("bigger", "make this panel as big as it goes, and back", KeyCode::Char('z'), ALT),
("help", "every command of the editor", KeyCode::F(1), NONE),
("hide", "hide this panel", KeyCode::Char('i'), ALT),
];
const MODELS: [&str; 5] = [
"default (the claude command's own choice)",
"opus",
"sonnet",
"haiku",
"another model, by its full name...",
];
const GIT_MENU: [&str; 9] = [
"Stage this file",
"Unstage this file",
"Stage all changes",
"Unstage everything",
"Commit...",
"Switch branch...",
"New branch...",
"Pull",
"Push",
];
pub enum AppEvent {
Input(Event),
Lsp(usize, Option<Value>),
Git(Option<GitInfo>),
Committed(String, Option<Vec<String>>),
GitDone(String),
Agent(u64, Option<String>),
Run(u64, runner::Event),
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum Focus {
Editor,
Tree,
Agent,
Output,
}
struct Server {
id: usize,
key: String,
client: Rc<RefCell<Client>>,
}
#[derive(Clone, Copy, Debug, PartialEq)]
struct Popup {
x: usize,
width: usize,
input_y: usize,
list_y: usize,
capacity: usize,
}
struct Layout {
tabs: usize,
tree: usize,
output: usize,
agent: usize,
agent_side: usize,
pane_width: usize,
pane_height: usize,
}
pub struct Workspace {
editors: Vec<Editor>,
active: usize,
tree: Tree,
show_tree: bool,
focus: Focus,
git: Option<GitInfo>,
finder: Option<Finder>,
picker: Picker,
hits: Vec<Hit>,
clipboard: String,
output: Output,
show_output: bool,
run_child: Option<std::process::Child>,
run_number: u64,
file_target: PathBuf,
delete_pending: Option<PathBuf>,
agent: Panel,
show_agent: bool,
agent_rows: Option<usize>,
agent_cols: Option<usize>,
agent_sessions: Vec<agent::SessionInfo>,
agent_home: Option<PathBuf>,
resizing_agent: bool,
agent_child: Option<std::process::Child>,
agent_snapshot: Option<Snapshot>,
agent_changes: Vec<Change>,
agent_run: u64,
pub agent_setting: Option<String>,
last_click: Option<(Instant, usize, usize)>,
clipboard_out: Option<String>,
servers: Vec<Server>,
next_server: usize,
events: Option<Sender<AppEvent>>,
lsp_setting: Option<String>,
message: String,
quit_pending: bool,
close_pending: bool,
should_quit: bool,
size: (usize, usize),
screen: Screen,
}
impl Workspace {
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,
finder: None,
picker: Picker::Files,
hits: Vec::new(),
clipboard: String::new(),
output: Output::default(),
show_output: false,
run_child: None,
run_number: 0,
file_target: PathBuf::new(),
delete_pending: None,
agent: Panel::new(),
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,
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(),
}
}
pub fn open_empty(&mut self) {
self.editors.push(Editor::new(Document::default()));
self.active = self.editors.len() - 1;
self.focus = Focus::Editor;
}
pub fn show_folder(&mut self) {
self.show_tree = true;
self.focus = Focus::Tree;
}
pub fn set_theme(&mut self, theme: Theme) {
self.screen.theme = theme;
}
pub fn has_files(&self) -> bool {
!self.editors.is_empty()
}
fn say(&mut self, text: String) {
match self.editors.get_mut(self.active) {
Some(editor) => editor.message = text,
None => self.message = text,
}
}
pub fn open(&mut self, path: &Path) -> bool {
let path = std::fs::canonicalize(path)
.or_else(|_| std::path::absolute(path))
.unwrap_or_else(|_| path.to_path_buf());
let text = path.to_string_lossy().into_owned();
let name = path.file_name().map_or_else(
|| text.clone(),
|name| name.to_string_lossy().into_owned(),
);
if let Some(index) = self
.editors
.iter()
.position(|editor| editor.abs_path.as_deref() == Some(text.as_str()))
{
self.active = index;
} else if path.is_dir() {
self.say(format!("{name} is a folder"));
return false;
} else {
let document = match Document::open(&text) {
Ok(document) => document,
Err(error) => {
self.say(format!("Could not open {name}: {error}"));
return false;
}
};
let mut editor = Editor::new(document);
self.attach_lsp(&mut editor);
let placeholder = self.editors.len() == 1
&& self.editors[0].document.path.is_none()
&& !self.editors[0].document.dirty;
if placeholder {
self.editors.clear();
}
self.editors.push(editor);
self.active = self.editors.len() - 1;
self.refresh_git();
}
self.focus = Focus::Editor;
self.tree.reveal(&path);
true
}
fn activate(&mut self, index: usize) {
if index < self.editors.len() {
self.active = index;
self.focus = Focus::Editor;
if let Some(path) = self.editors[index].abs_path.clone() {
self.tree.reveal(Path::new(&path));
}
}
}
fn next_tab(&mut self, step: isize) {
let count = self.editors.len() as isize;
if count > 0 {
self.activate((self.active as isize + step).rem_euclid(count) as usize);
}
}
fn close_active(&mut self, was_pending: bool) {
let Some(editor) = self.editors.get_mut(self.active) else {
return;
};
if editor.document.dirty && !was_pending {
self.close_pending = true;
editor.message = "Unsaved changes! Close again to discard".into();
return;
}
let editor = self.editors.remove(self.active);
if let (Some(lsp), Some(path)) = (&editor.lsp, &editor.abs_path) {
lsp.borrow_mut().close(path);
}
drop(editor);
self.servers.retain(|server| !server.client.borrow().is_unused());
self.active = self.active.min(self.editors.len().saturating_sub(1));
if self.editors.is_empty() {
self.show_folder();
} else {
self.activate(self.active);
}
}
fn close_tab(&mut self, index: usize) {
let pending = std::mem::take(&mut self.close_pending) && index == self.active;
if index < self.editors.len() {
self.activate(index);
self.close_active(pending);
}
}
fn quit(&mut self, was_pending: bool) {
let unsaved = self.editors.iter().filter(|editor| editor.document.dirty).count();
if unsaved == 0 || was_pending {
self.should_quit = true;
return;
}
self.quit_pending = true;
if !self.editors[self.active].document.dirty {
let first = self.editors.iter().position(|editor| editor.document.dirty);
self.activate(first.unwrap_or(self.active));
}
self.say(match unsaved {
1 => "Unsaved changes! Ctrl+Q again to quit".into(),
_ => format!("Unsaved changes in {unsaved} files! Ctrl+Q again to quit"),
});
}
fn attach_lsp(&mut self, editor: &mut Editor) {
let (Some(events), Some(path)) = (&self.events, editor.abs_path.clone()) else {
return;
};
let setting = self.lsp_setting.as_deref();
let Some(spec) = ServerSpec::for_file(editor.language, &path, setting) else {
return;
};
let folder = Path::new(&path).parent().unwrap_or(Path::new("/"));
let root = find_root(folder, spec.root_markers);
let key = format!("{} {:?} {}", spec.command, spec.args, root.display());
let client = match self.servers.iter().find(|server| server.key == key) {
Some(server) => server.client.clone(),
None => {
let id = self.next_server;
self.next_server += 1;
let events = events.clone();
let forward = move |message| {
let _ = events.send(AppEvent::Lsp(id, message));
};
match Client::start(&spec, &root, forward) {
Ok(client) => {
editor.message = format!("Starting {}...", client.name);
let client = Rc::new(RefCell::new(client));
self.servers.push(Server {
id,
key,
client: client.clone(),
});
client
}
Err(_) => {
editor.message =
format!("No language server: {} not found", spec.command);
return;
}
}
}
};
let lines = &editor.document.lines;
client
.borrow_mut()
.open(&path, spec.language_id, &|| lines.join("\n"));
editor.attach_lsp(client);
}
fn handle_lsp(&mut self, id: usize, message: Option<Value>) {
let Some(position) = self.servers.iter().position(|server| server.id == id) else {
return;
};
let client = self.servers[position].client.clone();
let uses_it = |editor: &Editor| editor.lsp.as_ref().is_some_and(|lsp| Rc::ptr_eq(lsp, &client));
let Some(message) = message else {
let name = client.borrow().name.clone();
self.servers.remove(position);
for (index, editor) in self.editors.iter_mut().enumerate() {
if uses_it(editor) {
editor.detach_lsp();
if index == self.active {
editor.message = format!("Language server {name} stopped");
}
}
}
return;
};
let editors = &self.editors;
let text_of = |path: &str| {
editors
.iter()
.find(|editor| editor.abs_path.as_deref() == Some(path))
.map(|editor| editor.document.lines.join("\n"))
.unwrap_or_default()
};
let (path, reply) = client.borrow_mut().handle(&message, &text_of);
let in_front = self.editors.get(self.active).and_then(|editor| editor.abs_path.clone());
match reply {
Reply::Nothing => {}
Reply::Ready => {
if let Some(editor) = self.editors.get_mut(self.active).filter(|editor| uses_it(editor))
{
editor.apply_reply(Reply::Ready);
}
}
Reply::Hover(_) | Reply::Definition(_) if path != in_front => {}
Reply::Definition(Some(mut location)) => {
if Some(&location.path) != in_front.as_ref()
&& Path::new(&location.path).is_file()
&& self.open(Path::new(&location.path))
&& let Some(opened) = self.editors[self.active].abs_path.clone()
{
location.path = opened;
}
self.editors[self.active].apply_reply(Reply::Definition(Some(location)));
}
reply => {
if let Some(editor) = self
.editors
.iter_mut()
.find(|editor| editor.abs_path.is_some() && editor.abs_path == path)
{
editor.apply_reply(reply);
}
}
}
}
fn refresh_git(&self) {
if let Some(events) = &self.events {
let events = events.clone();
let root = self.tree.root().to_path_buf();
let open: Vec<String> = self
.editors
.iter()
.filter_map(|editor| editor.abs_path.clone())
.collect();
std::thread::spawn(move || {
let _ = events.send(AppEvent::Git(git::load(&root)));
for path in open {
let lines = git::committed_lines(Path::new(&path));
let _ = events.send(AppEvent::Committed(path, lines));
}
});
}
}
fn pick(&mut self, picker: Picker, items: Vec<String>) {
self.picker = picker;
self.finder = Some(match picker {
Picker::Files => Finder::with_files(items),
_ => Finder::list(items),
});
}
fn search_project(&mut self, query: &str) {
let files = finder::project_files(self.tree.root());
self.hits = search::in_files(self.tree.root(), &files, query);
if self.hits.is_empty() {
self.say(format!("No match for {query} in the project"));
return;
}
let lines = self
.hits
.iter()
.map(|hit| format!("{}:{}: {}", hit.file, hit.y + 1, hit.text))
.collect();
self.pick(Picker::Results, lines);
}
fn open_hit(&mut self, index: usize) {
let Some(hit) = self.hits.get(index) else {
return;
};
let (path, x, y) = (self.tree.root().join(&hit.file), hit.x, hit.y);
if self.open(&path) {
self.editors[self.active].jump_to(x, y);
}
}
fn open_git_menu(&mut self) {
if self.git.is_some() {
self.pick(Picker::Git, GIT_MENU.iter().map(|item| item.to_string()).collect());
} else {
self.say("This folder is not in git".into());
}
}
fn git_target(&self) -> Option<PathBuf> {
match (self.focus, self.tree.selected()) {
(Focus::Tree, Some(entry)) => Some(entry.path.clone()),
_ => self.editors.get(self.active)?.abs_path.as_ref().map(PathBuf::from),
}
}
fn git_command(&mut self, index: usize) {
let unsaved = self.editors.iter().any(|editor| editor.document.dirty);
match GIT_MENU[index] {
"Stage this file" | "Unstage this file" => {
let Some(path) = self.git_target() else {
return self.say("No file to stage: open or select one first".into());
};
let name = path.file_name().unwrap_or_default().to_string_lossy().into_owned();
let path = path.to_string_lossy().into_owned();
if GIT_MENU[index] == "Stage this file" {
self.run_git(format!("Staged {name}"), move |root| {
git::action(root, &["add", "--", &path])
});
} else {
self.run_git(format!("Unstaged {name}"), move |root| {
git::action(root, &["restore", "--staged", "--", &path])
});
}
}
"Stage all changes" => {
self.run_git("Staged all changes".into(), |root| git::action(root, &["add", "--all"]));
}
"Unstage everything" => {
self.run_git("Unstaged everything".into(), |root| git::action(root, &["reset", "--quiet"]));
}
"Commit..." => self.pick(Picker::Commit, Vec::new()),
"New branch..." => self.pick(Picker::NewBranch, Vec::new()),
"Switch branch..." | "Pull" if unsaved => {
self.say("Save your changes first: this changes the files on disk".into());
}
"Switch branch..." => {
let branches = git::branches(self.tree.root());
self.pick(Picker::Branches, branches);
}
"Pull" => {
self.run_git("Pulled".into(), |root| git::action(root, &["pull", "--no-edit"]));
}
_ => self.run_git("Pushed".into(), git::push),
}
}
fn run_git(
&mut self,
done: String,
job: impl FnOnce(&Path) -> Result<(), String> + Send + 'static,
) {
let root = self.tree.root().to_path_buf();
let report = move || match job(&root) {
Ok(()) => done,
Err(error) => format!("git: {error}"),
};
match &self.events {
Some(events) => {
let events = events.clone();
std::thread::spawn(move || {
let _ = events.send(AppEvent::GitDone(report()));
});
self.say("Running git...".into());
}
None => {
let message = report();
self.git_done(message);
}
}
}
fn git_done(&mut self, message: String) {
self.tree.refresh();
self.reload_changed();
self.refresh_git();
self.say(message);
}
fn reload_changed(&mut self) {
for editor in &mut self.editors {
let Some(path) = editor.abs_path.clone().filter(|path| Path::new(path).is_file()) else {
continue;
};
if editor.document.dirty {
continue;
}
if let Ok(on_disk) = Document::open(&path)
&& on_disk.lines.join("\n") != editor.document.lines.join("\n")
{
editor.reload(&on_disk.lines);
}
}
}
fn ask_command(&mut self) {
self.pick(Picker::Run, Vec::new());
if let Some(finder) = &mut self.finder {
finder.query = self.output.command.clone();
}
}
fn run_command(&mut self, command: &str) {
self.stop_command();
let Some(events) = &self.events else {
return self.say("Commands cannot be run here".into());
};
self.run_number += 1;
let run = self.run_number;
let events = events.clone();
let forward = move |event| {
let _ = events.send(AppEvent::Run(run, event));
};
self.output.begin(command);
self.show_output = true;
if !self.agent_is_beside() {
self.show_agent = false;
if self.focus == Focus::Agent {
self.leave_agent();
}
}
match runner::start(command, self.tree.root(), forward) {
Ok(child) => self.run_child = Some(child),
Err(error) => {
self.output.push(&format!("Could not run it: {error}"));
self.output.finish(None);
}
}
}
fn run_again(&mut self) {
if self.output.command.is_empty() {
self.ask_command();
} else {
let command = self.output.command.clone();
self.run_command(&command);
}
}
fn stop_command(&mut self) {
if let Some(mut child) = self.run_child.take() {
let _ = child.kill();
let _ = child.wait();
self.run_number += 1;
self.output.finish(None);
}
}
fn handle_run(&mut self, run: u64, event: runner::Event) {
if run != self.run_number {
return;
}
match event {
runner::Event::Line(line) => self.output.push(&line),
runner::Event::Exit => {
let code = self
.run_child
.take()
.and_then(|mut child| child.wait().ok())
.and_then(|status| status.code());
self.output.finish(code);
self.tree.refresh();
self.reload_changed();
self.refresh_git();
}
}
}
fn toggle_output(&mut self) {
if self.show_output && self.focus == Focus::Output {
self.show_output = false;
self.leave_agent();
} else if self.output.command.is_empty() {
self.ask_command();
} else {
self.show_output = true;
self.focus = Focus::Output;
if !self.agent_is_beside() {
self.show_agent = false;
}
}
}
fn output_key(&mut self, key: KeyEvent) {
let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
let page = self.layout(self.size.0, self.size.1).output.saturating_sub(1).max(1) as isize;
match key.code {
KeyCode::Char('c') if ctrl => self.stop_command(),
KeyCode::Esc => self.leave_agent(),
KeyCode::Up => self.output.move_by(-1),
KeyCode::Down => self.output.move_by(1),
KeyCode::PageUp => self.output.move_by(-page),
KeyCode::PageDown => self.output.move_by(page),
KeyCode::Home => self.output.move_by(isize::MIN),
KeyCode::End => self.output.move_by(isize::MAX),
KeyCode::Enter => {
let place = self.output.selected_location();
self.go_to_place(place);
}
_ => {}
}
}
fn go_to_place(&mut self, place: Option<(String, usize, usize)>) {
let Some((file, row, column)) = place else {
return self.say("No file and line named there".into());
};
let path = self.tree.root().join(&file);
if path.is_file() && self.open(&path) {
self.editors[self.active].jump_to(column - 1, row - 1);
} else {
self.say(format!("{file} is not a file in this project"));
}
}
fn next_error(&mut self, forward: bool) {
match self.output.next_location(forward) {
Some(place) => self.go_to_place(Some(place)),
None => self.say("No more places named in what the command printed".into()),
}
}
fn selected_folder(&self) -> PathBuf {
match self.tree.selected() {
Some(entry) if entry.is_dir => entry.path.clone(),
Some(entry) => entry.path.parent().unwrap_or(self.tree.root()).to_path_buf(),
None => self.tree.root().to_path_buf(),
}
}
fn ask_new(&mut self, picker: Picker) {
self.file_target = self.selected_folder();
self.pick(picker, Vec::new());
}
fn ask_rename(&mut self) {
let Some(entry) = self.tree.selected() else {
return;
};
self.file_target = entry.path.clone();
let name = entry.name.clone();
self.pick(Picker::Rename, Vec::new());
if let Some(finder) = &mut self.finder {
finder.query = name;
}
}
fn open_under(&self, path: &Path) -> Vec<usize> {
(0..self.editors.len())
.filter(|index| {
let file = self.editors[*index].abs_path.as_deref().map(Path::new);
file.is_some_and(|file| file.starts_with(path))
})
.collect()
}
fn close_under(&mut self, path: &Path) -> Vec<PathBuf> {
let mut closed = Vec::new();
for index in self.open_under(path).into_iter().rev() {
let editor = self.editors.remove(index);
if let (Some(lsp), Some(file)) = (&editor.lsp, &editor.abs_path) {
lsp.borrow_mut().close(file);
}
let file = PathBuf::from(editor.abs_path.unwrap_or_default());
closed.push(file.strip_prefix(path).unwrap_or(Path::new("")).to_path_buf());
}
self.servers.retain(|server| !server.client.borrow().is_unused());
self.active = self.active.min(self.editors.len().saturating_sub(1));
closed
}
fn unsaved_under(&mut self, path: &Path) -> bool {
let unsaved = self.open_under(path).iter().any(|index| self.editors[*index].document.dirty);
if unsaved {
self.say("Save or close the file first: it has unsaved changes".into());
}
unsaved
}
fn make_new(&mut self, name: &str, folder: bool) {
let path = self.file_target.join(name);
if path.exists() {
return self.say(format!("{name} already exists"));
}
let made = if folder {
std::fs::create_dir_all(&path)
} else {
std::fs::create_dir_all(path.parent().unwrap_or(&self.file_target))
.and_then(|()| std::fs::write(&path, ""))
};
if let Err(error) = made {
return self.say(format!("Could not make {name}: {error}"));
}
self.tree.refresh();
self.refresh_git();
if folder {
self.tree.reveal(&path);
self.say(format!("Made the folder {name}"));
} else {
self.open(&path);
}
}
fn rename_to(&mut self, name: &str) {
let from = self.file_target.clone();
let to = from.parent().unwrap_or(self.tree.root()).join(name);
if to == from || self.unsaved_under(&from) {
return;
}
if to.exists() {
return self.say(format!("{name} already exists"));
}
if let Err(error) = std::fs::rename(&from, &to) {
return self.say(format!("Could not rename it: {error}"));
}
let moved = self.close_under(&from);
self.tree.refresh();
self.refresh_git();
let focus = self.focus;
for below in moved.into_iter().rev() {
let path = if below.as_os_str().is_empty() { to.clone() } else { to.join(below) };
self.open(&path);
}
self.focus = focus;
self.tree.reveal(&to);
self.say(format!("Renamed to {name}"));
}
fn delete_selected(&mut self, pending: Option<PathBuf>) {
let Some(entry) = self.tree.selected() else {
return;
};
let (path, name, is_dir) = (entry.path.clone(), entry.name.clone(), entry.is_dir);
if self.unsaved_under(&path) {
return;
}
if pending.as_ref() != Some(&path) {
let what = if is_dir { " and everything in it" } else { "" };
self.say(format!("Delete {name}{what}? Press d again"));
self.delete_pending = Some(path);
return;
}
let removed = if is_dir { std::fs::remove_dir_all(&path) } else { std::fs::remove_file(&path) };
if let Err(error) = removed {
return self.say(format!("Could not delete {name}: {error}"));
}
self.close_under(&path);
self.tree.refresh();
self.refresh_git();
if !self.has_files() {
self.show_folder();
}
self.say(format!("Deleted {name}"));
}
fn list_commands(&mut self) {
let lines = COMMANDS
.iter()
.map(|(name, key, ..)| format!("{name:<42}{key}"))
.collect();
self.pick(Picker::Commands, lines);
}
fn run_listed(&mut self, index: usize) {
let (_, _, target, code, modifiers) = COMMANDS[index];
match target {
Target::Window => {}
Target::Text if self.has_files() => self.focus = Focus::Editor,
Target::Text => return self.say("Open a file first".into()),
Target::Tree => self.show_folder(),
Target::Claude => {
self.show_agent = true;
self.focus = Focus::Agent;
}
}
if code != KeyCode::Null {
self.handle_key(KeyEvent::new(code, modifiers));
}
}
fn toggle_agent(&mut self) {
if self.show_agent && self.focus == Focus::Agent {
self.show_agent = false;
self.leave_agent();
} else {
self.show_agent = true;
self.focus = Focus::Agent;
if !self.agent_is_beside() {
self.show_output = false;
}
}
}
fn leave_agent(&mut self) {
self.focus = if self.has_files() { Focus::Editor } else { Focus::Tree };
}
fn agent_key(&mut self, key: KeyEvent) {
let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
let alt = key.modifiers.contains(KeyModifiers::ALT);
match key.code {
KeyCode::Esc if self.agent.running => self.stop_agent("Stopped"),
KeyCode::Esc => self.leave_agent(),
KeyCode::Enter if alt => self.agent.type_char('\n'),
KeyCode::Enter => self.ask_agent(),
KeyCode::Char('/') if !ctrl && !alt && self.agent.input.is_empty() => self.list_slash(),
KeyCode::Char('@') if !ctrl && !alt => {
self.picker = Picker::Attach;
self.finder = Some(Finder::new(self.tree.root()));
}
KeyCode::Char('m') if alt && !self.agent.running => self.agent.next_mode(),
KeyCode::Char('n') if ctrl && !self.agent.running => self.agent.clear(),
KeyCode::Char('z') if alt => self.zoom_agent(),
KeyCode::Char('u') if alt && !self.agent.running => self.undo_agent(),
KeyCode::Char('o') if alt => self.open_agent_changes(),
KeyCode::Char('c') if alt => self.copy_answer(),
KeyCode::Char('r') if (ctrl || alt) && !self.agent.running => self.list_sessions(),
KeyCode::Up if alt => self.grow_agent(true),
KeyCode::Down if alt => self.grow_agent(false),
KeyCode::Char(c) if !ctrl && !alt => self.agent.type_char(c),
KeyCode::Backspace => self.agent.backspace(),
KeyCode::Delete => self.agent.delete(),
KeyCode::Left => self.agent.move_cursor(-1),
KeyCode::Right => self.agent.move_cursor(1),
KeyCode::Home => self.agent.move_cursor(isize::MIN),
KeyCode::End => self.agent.move_cursor(isize::MAX),
KeyCode::Up => self.agent.recall(-1),
KeyCode::Down => self.agent.recall(1),
KeyCode::PageUp => self.agent.scroll_by(self.agent_rows() as isize),
KeyCode::PageDown => self.agent.scroll_by(-(self.agent_rows() as isize)),
_ => {}
}
}
fn list_slash(&mut self) {
let mut lines: Vec<String> = SLASH
.iter()
.map(|(name, what, ..)| format!("{name:<10}{what}"))
.collect();
let own = agent::own_commands(&self.home(), self.tree.root());
lines.extend(own.iter().map(|name| format!("{name:<10} (yours: sent to claude)")));
self.pick(Picker::Slash, lines);
}
fn run_slash(&mut self, index: Option<usize>, chosen: Option<String>, typed: &str) {
match index {
Some(index) if index < SLASH.len() => match SLASH[index] {
("model", ..) => self.pick(Picker::Model, MODELS.iter().map(|name| name.to_string()).collect()),
("attach", ..) => {
self.picker = Picker::Attach;
self.finder = Some(Finder::new(self.tree.root()));
}
("detach", ..) => self.agent.attached.clear(),
(_, _, code, modifiers) => self.handle_key(KeyEvent::new(code, modifiers)),
},
Some(_) => {
let name = chosen.unwrap_or_default();
let name = name.split_whitespace().next().unwrap_or_default();
self.agent.set_input(&format!("/{name} "));
}
None => self.agent.set_input(&format!("/{typed}")),
}
}
fn choose_model(&mut self, index: usize) {
match index {
0 => self.agent.model = None,
last if last + 1 == MODELS.len() => return self.pick(Picker::ModelName, Vec::new()),
index => self.agent.model = Some(MODELS[index].to_string()),
}
let model = self.agent.model.as_deref().unwrap_or("the default model");
self.agent.say(Who::Note, format!("The next answers come from {model}"));
}
fn home(&self) -> PathBuf {
self.agent_home.clone().unwrap_or_else(|| {
let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"));
PathBuf::from(home.unwrap_or_default())
})
}
fn agent_rows(&self) -> usize {
let layout = self.layout(self.size.0, self.size.1);
let height = match layout.agent_side {
0 => layout.agent,
_ => layout.pane_height + layout.output,
};
height.saturating_sub(3).max(1)
}
fn agent_is_beside(&self) -> bool {
self.layout(self.size.0, self.size.1).agent_side > 0
}
fn agent_size(&self) -> usize {
let layout = self.layout(self.size.0, self.size.1);
layout.agent_side.saturating_sub(1).max(layout.agent)
}
fn resize_agent(&mut self, size: usize) {
let beside = self.agent_is_beside();
let wanted = if beside { &mut self.agent_cols } else { &mut self.agent_rows };
*wanted = Some(size);
let size = self.agent_size();
*(if beside { &mut self.agent_cols } else { &mut self.agent_rows }) = Some(size);
}
fn grow_agent(&mut self, bigger: bool) {
let step = if self.agent_is_beside() { 6 } else { 2 };
let size = self.agent_size();
self.resize_agent(if bigger { size + step } else { size.saturating_sub(step) });
}
fn zoom_agent(&mut self) {
let before = self.agent_size();
self.resize_agent(usize::MAX);
if self.agent_size() == before {
(self.agent_rows, self.agent_cols) = (None, None);
}
}
fn list_sessions(&mut self) {
self.agent_sessions = agent::list_sessions(&self.sessions_dir());
if self.agent_sessions.is_empty() {
self.agent.say(Who::Note, "No earlier conversations about this project");
return;
}
let now = std::time::SystemTime::now();
let lines = self
.agent_sessions
.iter()
.map(|session| format!("{:>3} {}", agent::age(session.modified, now), session.title))
.collect();
self.pick(Picker::Sessions, lines);
}
fn sessions_dir(&self) -> PathBuf {
agent::sessions_dir(&self.home(), self.tree.root())
}
fn resume_session(&mut self, index: usize) {
let Some(session) = self.agent_sessions.get(index) else {
return;
};
let entries = agent::load_session(&self.sessions_dir(), &session.id);
self.agent.resume(session.id.clone(), entries);
self.agent.say(Who::Note, "Carrying on this conversation");
self.agent_snapshot = None;
self.agent_changes.clear();
self.show_agent = true;
self.focus = Focus::Agent;
}
fn copy_answer(&mut self) {
if let Some(answer) = self.agent.last_answer() {
self.clipboard = answer.to_string();
self.clipboard_out = Some(self.clipboard.clone());
self.agent.say(Who::Note, "Copied the last answer");
}
}
fn agent_context(&self) -> String {
match self.editors.get(self.active) {
Some(editor) if editor.abs_path.is_some() => {
let unsaved = if editor.document.dirty {
" It has changes that are not saved to disk yet."
} else {
""
};
let selected = match editor.selected_text() {
Some((first, last, text)) => {
let text: String = text.chars().take(MAX_SELECTION_CHARS).collect();
format!(
" The user has selected lines {} to {} of it:\n{text}",
first + 1,
last + 1
)
}
None => String::new(),
};
format!(
"The user is asking from inside the curd text editor. The file in front is {}, with the cursor on line {}.{unsaved}{selected}",
editor.abs_path.as_deref().unwrap_or_default(),
editor.cursor_line() + 1,
)
}
_ => "The user is asking from inside the curd text editor.".into(),
}
}
fn ask_agent(&mut self) {
if self.agent.running {
return;
}
let Some(prompt) = self.agent.take_input() else {
return;
};
let context = self.agent_context();
let attached = std::mem::take(&mut self.agent.attached);
let sent = match attached.len() {
0 => prompt.clone(),
_ => format!(
"{prompt}\n\nThe user attached these files (named from the project folder). Read them first: {}",
attached.join(", ")
),
};
let model = self.agent.model.clone();
let request = Request {
model: model.as_deref(),
prompt: &sent,
session: self.agent.session.as_deref(),
can_edit: self.agent.can_edit,
can_run: self.agent.can_run,
context: &context,
};
let (Some(words), Some(events)) =
(agent::command_line(self.agent_setting.as_deref(), &request), &self.events)
else {
self.agent.say(Who::Note, "The Claude panel is turned off (CURD_AGENT=off)");
return;
};
self.agent_changes.clear();
self.agent_snapshot = self.agent.can_edit.then(|| {
Snapshot::take(self.tree.root(), &finder::project_files(self.tree.root()))
});
self.agent_run += 1;
let run = self.agent_run;
let events = events.clone();
let forward = move |line| {
let _ = events.send(AppEvent::Agent(run, line));
};
self.agent.say(Who::You, prompt);
if !attached.is_empty() {
self.agent.say(Who::Note, format!("With {}", attached.join(", ")));
}
let selection = self.editors.get(self.active).and_then(Editor::selected_text);
if let Some((first, last, _)) = selection {
self.agent.say(Who::Note, format!("With the selected lines {} to {}", first + 1, last + 1));
}
if std::env::var_os("ANTHROPIC_API_KEY").is_some() {
self.agent.say(Who::Note, "ANTHROPIC_API_KEY is set, so claude bills that key and not your subscription");
}
if self.editors.iter().any(|editor| editor.document.dirty) {
self.agent.say(Who::Note, "Unsaved changes are not on disk, so Claude does not see them");
}
match agent::start(&words, self.tree.root(), forward) {
Ok(child) => {
self.agent_child = Some(child);
self.agent.start();
}
Err(_) => self.agent.say(
Who::Note,
format!(
"Could not run {}. Install Claude Code, then run `claude` once in a terminal to sign in with your Claude account.",
words[0]
),
),
}
}
fn stop_agent(&mut self, why: &str) {
if let Some(mut child) = self.agent_child.take() {
let _ = child.kill();
let _ = child.wait();
}
if self.agent.running {
self.agent.running = false;
self.agent_run += 1;
self.agent.say(Who::Note, why);
self.agent_finished();
}
}
fn handle_agent(&mut self, run: u64, line: Option<String>) {
if run != self.agent_run {
return;
}
let ended = match line {
Some(line) => {
let mut ended = false;
for update in agent::parse(&line) {
let update = match update {
agent::Update::Step(step) => {
agent::Update::Step(agent::shorten(&step, self.tree.root()))
}
other => other,
};
ended |= self.agent.apply(update);
}
ended
}
None => {
if let Some(mut child) = self.agent_child.take() {
let _ = child.wait();
}
let unfinished = self.agent.running;
if unfinished {
self.agent.running = false;
self.agent.say(
Who::Note,
"It stopped without an answer. If you are not signed in, run `claude` once in a terminal.",
);
}
unfinished
}
};
if ended && !self.agent.running {
self.agent_finished();
}
}
fn agent_finished(&mut self) {
self.tree.refresh();
self.reload_changed();
self.refresh_git();
if let Some(snapshot) = &self.agent_snapshot {
self.agent_changes = snapshot.changes(&finder::project_files(self.tree.root()));
if !self.agent_changes.is_empty() {
let summary = agent::describe(&self.agent_changes);
self.agent.say(Who::Note, format!("{summary} (Alt+O opens them, Alt+U undoes this)"));
}
}
}
fn undo_agent(&mut self) {
let changes = std::mem::take(&mut self.agent_changes);
let Some(snapshot) = self.agent_snapshot.take().filter(|_| !changes.is_empty()) else {
self.agent.say(Who::Note, "Nothing of Claude's to undo");
return;
};
let (restored, failed) = snapshot.restore(&changes);
let files = if restored == 1 { "file" } else { "files" };
self.agent.say(
Who::Note,
match failed {
0 => format!("Put {restored} {files} back as before"),
_ => format!("Put {restored} {files} back as before; {failed} could not be"),
},
);
self.tree.refresh();
self.reload_changed();
self.refresh_git();
}
fn open_agent_changes(&mut self) {
let files: Vec<String> = self
.agent_changes
.iter()
.filter(|change| change.kind != ChangeKind::Deleted)
.map(|change| change.file.clone())
.collect();
match files.len() {
0 => self.agent.say(Who::Note, "Claude changed no files in its last answer"),
_ => self.pick(Picker::Files, files),
}
}
pub fn run(&mut self, events: &Receiver<AppEvent>) -> std::io::Result<()> {
self.refresh_git();
while !self.should_quit {
self.size = Terminal::size()?;
let (frame, cursor) = self.render(self.size.0, self.size.1);
self.screen.draw(frame, self.size, cursor)?;
if let Some(text) = self.clipboard_out.take() {
Terminal::copy(&text)?;
}
let waiting_to_sync = self
.servers
.iter()
.any(|server| server.client.borrow().has_pending_changes());
let event = if waiting_to_sync || self.agent.running {
let pause = if waiting_to_sync { LSP_DEBOUNCE } else { AGENT_TICK };
match events.recv_timeout(pause) {
Ok(event) => Some(event),
Err(RecvTimeoutError::Timeout) => None,
Err(RecvTimeoutError::Disconnected) => break,
}
} else {
match events.recv() {
Ok(event) => Some(event),
Err(_) => break,
}
};
match event {
Some(event) => {
self.handle_event(event);
while let Ok(event) = events.try_recv() {
self.handle_event(event);
}
}
None => self.editors.iter_mut().for_each(Editor::sync_lsp),
}
}
self.stop_agent("Stopped");
self.stop_command();
Ok(())
}
fn handle_event(&mut self, event: AppEvent) {
match event {
AppEvent::Input(Event::Key(key)) => self.handle_key(key),
AppEvent::Input(Event::Mouse(mouse)) => self.handle_mouse(mouse),
AppEvent::Input(Event::Paste(text)) => self.paste(&text),
AppEvent::Input(Event::FocusGained) => {
self.tree.refresh();
self.reload_changed();
self.refresh_git();
}
AppEvent::Input(_) => {}
AppEvent::Lsp(id, message) => self.handle_lsp(id, message),
AppEvent::Git(git) => self.git = git,
AppEvent::GitDone(message) => self.git_done(message),
AppEvent::Agent(run, line) => self.handle_agent(run, line),
AppEvent::Run(run, event) => self.handle_run(run, event),
AppEvent::Committed(path, lines) => {
if let Some(editor) = self
.editors
.iter_mut()
.find(|editor| editor.abs_path.as_deref() == Some(path.as_str()))
{
editor.set_git_base(lines);
}
}
}
}
fn handle_key(&mut self, key: KeyEvent) {
if key.kind == KeyEventKind::Release {
return;
}
if self.finder.is_some() {
self.finder_key(key);
return;
}
let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
let alt = key.modifiers.contains(KeyModifiers::ALT);
let quit_was_pending = std::mem::take(&mut self.quit_pending);
let close_was_pending = std::mem::take(&mut self.close_pending);
let delete_was_pending = std::mem::take(&mut self.delete_pending);
self.message.clear();
if let Some(editor) = self.editors.get_mut(self.active) {
editor.message.clear();
}
match key.code {
KeyCode::Char('q') if ctrl => self.quit(quit_was_pending),
KeyCode::Char('p') if ctrl || alt => {
self.picker = Picker::Files;
self.finder = Some(Finder::new(self.tree.root()));
}
KeyCode::Char('s') if alt => self.pick(Picker::Search, Vec::new()),
KeyCode::Char('g') if ctrl => self.open_git_menu(),
KeyCode::Char('v') if alt => self.open_git_menu(),
KeyCode::Char('v') if ctrl => {
let text = self.clipboard.clone();
self.paste(&text);
}
KeyCode::Char('b') if ctrl || alt => self.toggle_tree(),
KeyCode::Char('e') if alt => self.switch_focus(),
KeyCode::Char('i') if alt => self.toggle_agent(),
KeyCode::F(1) => self.list_commands(),
KeyCode::Char('x') if alt => self.list_commands(),
KeyCode::Char('t') if ctrl => self.ask_command(),
KeyCode::Char('t') if alt => self.toggle_output(),
KeyCode::F(5) => self.run_again(),
KeyCode::F(8) => self.next_error(!key.modifiers.contains(KeyModifiers::SHIFT)),
KeyCode::Char('w') if ctrl || alt => self.close_active(close_was_pending),
KeyCode::Char('.') if alt => self.next_tab(1),
KeyCode::Char(',') if alt => self.next_tab(-1),
KeyCode::PageDown if ctrl => self.next_tab(1),
KeyCode::PageUp if ctrl => self.next_tab(-1),
KeyCode::Char(digit @ '1'..='9') if alt => self.activate(digit as usize - '1' as usize),
_ if self.focus == Focus::Agent => self.agent_key(key),
_ if self.focus == Focus::Output => self.output_key(key),
KeyCode::Char('d') | KeyCode::Delete if self.focus == Focus::Tree && !ctrl && !alt => {
self.delete_selected(delete_was_pending);
}
_ if self.focus == Focus::Tree => self.tree_key(key),
_ => self.editor_key(key),
}
}
fn editor_key(&mut self, key: KeyEvent) {
let Some(editor) = self.editors.get_mut(self.active) else {
return;
};
editor.handle_key(key);
if let Some(text) = editor.copied.take() {
self.clipboard = text.clone();
self.clipboard_out = Some(text);
}
let saved = std::mem::take(&mut editor.just_saved);
let renamed = std::mem::take(&mut editor.renamed);
if renamed {
let mut editor = self.editors.remove(self.active);
self.attach_lsp(&mut editor);
self.editors.insert(self.active, editor);
}
if saved {
self.tree.refresh();
self.refresh_git();
}
if renamed && let Some(path) = self.editors[self.active].abs_path.clone() {
self.tree.reveal(Path::new(&path));
}
}
fn tree_key(&mut self, key: KeyEvent) {
match key.code {
KeyCode::Up => self.tree.move_by(-1),
KeyCode::Down => self.tree.move_by(1),
KeyCode::PageUp => self.tree.move_by(-10),
KeyCode::PageDown => self.tree.move_by(10),
KeyCode::Home => self.tree.move_by(isize::MIN / 2),
KeyCode::End => self.tree.move_by(isize::MAX / 2),
KeyCode::Left => self.tree.left(),
KeyCode::Right => self.tree.right(),
KeyCode::Enter => {
if let Some(path) = self.tree.activate() {
self.open(&path);
}
}
KeyCode::Char('n') => self.ask_new(Picker::NewFile),
KeyCode::Char('f') => self.ask_new(Picker::NewFolder),
KeyCode::Char('r') | KeyCode::F(2) => self.ask_rename(),
KeyCode::Esc if self.has_files() => self.focus = Focus::Editor,
_ => {}
}
}
fn finder_key(&mut self, key: KeyEvent) {
let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
let Some(finder) = &mut self.finder else {
return;
};
match key.code {
KeyCode::Esc => self.finder = None,
KeyCode::Char('p' | 'q' | 'c') if ctrl => self.finder = None,
KeyCode::Char('p') if key.modifiers.contains(KeyModifiers::ALT) => self.finder = None,
KeyCode::Enter => self.accept_picked(),
KeyCode::Up => finder.move_by(-1),
KeyCode::Down => finder.move_by(1),
KeyCode::Backspace => finder.backspace(),
KeyCode::Char(c) if !ctrl => finder.type_char(c),
_ => {}
}
}
fn accept_picked(&mut self) {
let Some(finder) = &self.finder else {
return;
};
let typed = finder.query.trim().to_string();
let index = finder.chosen_index();
let chosen = finder.chosen().map(String::from);
self.finder = None;
match (self.picker, index, chosen) {
(picker, ..) if picker.is_question() && typed.is_empty() => {}
(Picker::Search, ..) => self.search_project(&typed),
(Picker::Run, ..) => self.run_command(&typed),
(Picker::NewFile, ..) => self.make_new(&typed, false),
(Picker::NewFolder, ..) => self.make_new(&typed, true),
(Picker::Rename, ..) => self.rename_to(&typed),
(Picker::Commands, Some(index), _) => self.run_listed(index),
(Picker::Slash, index, chosen) => self.run_slash(index, chosen, &typed),
(Picker::Attach, _, Some(file)) => self.agent.attach(file),
(Picker::Model, Some(index), _) => self.choose_model(index),
(Picker::ModelName, ..) => {
self.agent.say(Who::Note, format!("The next answers come from {typed}"));
self.agent.model = Some(typed);
}
(Picker::Commit, ..) => {
let message = typed.clone();
self.run_git(format!("Committed: {typed}"), move |root| {
git::action(root, &["commit", "--message", &message])
});
}
(Picker::NewBranch, ..) => {
let name = typed.clone();
self.run_git(format!("On new branch {typed}"), move |root| {
git::action(root, &["switch", "--create", &name])
});
}
(Picker::Files, _, Some(file)) => {
let path = self.tree.root().join(file);
self.open(&path);
}
(Picker::Results, Some(index), _) => self.open_hit(index),
(Picker::Git, Some(index), _) => self.git_command(index),
(Picker::Sessions, Some(index), _) => self.resume_session(index),
(Picker::Branches, _, Some(branch)) => {
let name = branch.clone();
self.run_git(format!("Switched to {branch}"), move |root| {
git::action(root, &["switch", &name])
});
}
_ => {}
}
}
fn paste(&mut self, text: &str) {
if let Some(finder) = &mut self.finder {
text.chars()
.filter(|c| !c.is_control())
.for_each(|c| finder.type_char(c));
} else if self.focus == Focus::Agent {
for c in text.chars().filter(|c| *c == '\n' || !c.is_control()) {
self.agent.type_char(c);
}
} else if self.focus == Focus::Editor
&& let Some(editor) = self.editors.get_mut(self.active)
{
editor.paste(text);
}
}
fn toggle_tree(&mut self) {
if self.show_tree && self.has_files() {
self.show_tree = false;
self.focus = Focus::Editor;
} else {
self.show_folder();
self.tree.refresh();
self.refresh_git();
}
}
fn switch_focus(&mut self) {
if self.focus != Focus::Editor && self.has_files() {
self.focus = Focus::Editor;
} else {
self.show_folder();
}
}
fn picker_mouse(&mut self, mouse: MouseEvent) {
let popup = self.popup(self.size.0, self.size.1);
let Some(finder) = &mut self.finder else {
return;
};
let (x, y) = (mouse.column as usize, mouse.row as usize);
let inside = (popup.x..popup.x + popup.width).contains(&x);
match mouse.kind {
MouseEventKind::ScrollDown => finder.move_by(1),
MouseEventKind::ScrollUp => finder.move_by(-1),
MouseEventKind::Down(MouseButton::Left) => {
let row = y.checked_sub(popup.list_y).filter(|_| inside);
if row.is_some_and(|row| finder.select_row(row, popup.capacity)) {
self.accept_picked();
} else if !(inside && y == popup.input_y) {
self.finder = None;
}
}
_ => {}
}
}
fn popup_rows(&self, capacity: usize) -> usize {
let Some(finder) = &self.finder else {
return 0;
};
let shown = finder.visible(capacity).len();
if shown == 0 && !self.picker.is_question() { 1.min(capacity) } else { shown }
}
fn popup(&self, width: usize, height: usize) -> Popup {
let layout = self.layout(width, height);
let panel = if layout.agent_side > 0 {
let top = layout.tabs;
Some((layout.tree + layout.pane_width + 1, layout.agent_side - 1, top, height.saturating_sub(top)))
} else if layout.agent > 0 {
Some((layout.tree, layout.pane_width, layout.tabs + layout.pane_height, layout.agent))
} else {
None
};
if let (true, Some((x, panel_width, top, panel_height))) = (self.picker.is_for_claude(), panel) {
let question = self.agent.box_rows(panel_width, panel_height);
let input_y = (top + panel_height).saturating_sub(question + 1);
let capacity = FINDER_ROWS.min(input_y.saturating_sub(top + 1));
if input_y > top {
let list_y = input_y - self.popup_rows(capacity);
return Popup { x, width: panel_width, input_y, list_y, capacity };
}
}
let box_width = layout.pane_width.min(POPUP_WIDTH);
Popup {
x: layout.tree + (layout.pane_width - box_width) / 2,
width: box_width,
input_y: layout.tabs,
list_y: layout.tabs + 1,
capacity: FINDER_ROWS.min(layout.pane_height.saturating_sub(2)),
}
}
fn handle_mouse(&mut self, mouse: MouseEvent) {
let layout = self.layout(self.size.0, self.size.1);
if self.finder.is_some() {
return self.picker_mouse(mouse);
}
let (x, y) = (mouse.column as usize, mouse.row as usize);
let over_tree = x < layout.tree && y >= layout.tabs;
let over_tabs = y < layout.tabs;
let beside = layout.agent_side > 0;
let edge = layout.tree + layout.pane_width;
if self.resizing_agent {
match mouse.kind {
MouseEventKind::Drag(MouseButton::Left) if beside => {
self.resize_agent(self.size.0.saturating_sub(x + 1));
}
MouseEventKind::Drag(MouseButton::Left) => {
self.resize_agent(self.size.1.saturating_sub(y));
}
_ => self.resizing_agent = false,
}
return;
}
let over_output = layout.output > 0
&& y >= layout.tabs + layout.pane_height
&& (layout.tree..edge).contains(&x);
if over_output {
match mouse.kind {
MouseEventKind::Down(MouseButton::Left) => {
self.focus = Focus::Output;
if let Some(row) = (y - layout.tabs - layout.pane_height).checked_sub(1) {
self.output.click(row);
if let Some(place) = self.output.selected_location() {
self.go_to_place(Some(place));
}
}
}
MouseEventKind::ScrollUp => self.output.move_by(-WHEEL_LINES),
MouseEventKind::ScrollDown => self.output.move_by(WHEEL_LINES),
_ => {}
}
return;
}
let over_agent = if beside {
x >= edge && y >= layout.tabs
} else {
layout.agent > 0 && !over_tree && y >= layout.tabs + layout.pane_height
};
if over_agent {
match mouse.kind {
MouseEventKind::Down(MouseButton::Left) => {
self.focus = Focus::Agent;
self.resizing_agent = if beside {
x == edge
} else {
y == layout.tabs + layout.pane_height
};
}
MouseEventKind::ScrollUp => self.agent.scroll_by(WHEEL_LINES),
MouseEventKind::ScrollDown => self.agent.scroll_by(-WHEEL_LINES),
_ => {}
}
return;
}
match mouse.kind {
MouseEventKind::Down(MouseButton::Middle) if over_tabs => {
if let Some((tab, _)) = self.tab_at(x) {
self.close_tab(tab);
}
}
MouseEventKind::ScrollDown if over_tabs => self.next_tab(1),
MouseEventKind::ScrollUp if over_tabs => self.next_tab(-1),
MouseEventKind::Down(MouseButton::Left) => {
if over_tabs {
match self.tab_at(x) {
Some((tab, true)) => self.close_tab(tab),
Some((tab, false)) => self.activate(tab),
None => {}
}
} else if over_tree {
self.focus = Focus::Tree;
if let Some(row) = (y - layout.tabs).checked_sub(1)
&& let Some(path) = self.tree.click(row)
{
self.open(&path);
}
} else if let Some(editor) = self.editors.get_mut(self.active) {
self.focus = Focus::Editor;
editor.click(x - layout.tree, y - layout.tabs);
let now = Instant::now();
let double = self.last_click.is_some_and(|(at, last_x, last_y)| {
(last_x, last_y) == (x, y) && now.duration_since(at) < DOUBLE_CLICK
});
if double {
editor.select_word();
}
self.last_click = (!double).then_some((now, x, y));
}
}
MouseEventKind::Drag(MouseButton::Left)
if self.focus == Focus::Editor && y >= layout.tabs && x >= layout.tree =>
{
if let Some(editor) = self.editors.get_mut(self.active) {
editor.drag(x - layout.tree, y - layout.tabs);
}
}
MouseEventKind::ScrollDown | MouseEventKind::ScrollUp => {
let lines = match mouse.kind {
MouseEventKind::ScrollDown => WHEEL_LINES,
_ => -WHEEL_LINES,
};
if over_tree {
self.tree.move_by(lines);
} else if let Some(editor) = self.editors.get_mut(self.active) {
editor.wheel(lines);
}
}
_ => {}
}
}
fn layout(&self, width: usize, height: usize) -> Layout {
let tabs = (self.editors.len() > 1) as usize;
let tree = if self.show_tree {
TREE_WIDTH.min(width / 2) + 1
} else {
0
};
let below_tabs = height.saturating_sub(tabs);
let room = width.saturating_sub(tree);
let agent_side = if self.show_agent && room >= AGENT_SIDE_MIN {
let cols = self.agent_cols.unwrap_or(room * 2 / 5);
cols.clamp(AGENT_MIN_WIDTH, room - TEXT_MIN_WIDTH - 1) + 1
} else {
0
};
let under = |wanted: Option<usize>| {
wanted.unwrap_or(below_tabs * 2 / 5).clamp(3, below_tabs.max(5) - 2)
};
let output = if self.show_output && below_tabs >= 6 { under(None) } else { 0 };
let agent = if self.show_agent && agent_side == 0 && output == 0 && below_tabs >= 6 {
under(self.agent_rows)
} else {
0
};
Layout {
tabs,
tree,
output,
agent,
agent_side,
pane_width: room - agent_side,
pane_height: below_tabs - agent - output,
}
}
fn tab_labels(&self) -> Vec<String> {
self.editors
.iter()
.map(|editor| {
let dot = if editor.document.dirty { " ●" } else { "" };
format!(" {}{dot} {CLOSE_ICON} ", widen(editor.name()))
})
.collect()
}
fn tab_at(&self, x: usize) -> Option<(usize, bool)> {
let mut end = 0;
let tab = self.tab_labels().iter().position(|label| {
end += label.chars().count();
x < end
})?;
Some((tab, x + 2 >= end))
}
fn tab_row(&self, width: usize) -> Row {
let mut row = Row::new();
let mut used = 0;
for (index, label) in self.tab_labels().iter().enumerate() {
let label = fit(label, label.chars().count().min(width - used));
used += label.chars().count();
let style = if index == self.active { Style::TabActive } else { Style::Tab };
row.push(Span::new(style, label));
}
row
}
fn empty_pane(&self, width: usize, height: usize) -> Vec<Row> {
let mut rows = Vec::with_capacity(height);
for y in 0..height.saturating_sub(1) {
let text = match y.checked_sub(height / 3) {
Some(0) => concat!("curd editor -- v", env!("CARGO_PKG_VERSION")),
Some(2) => "Enter open the selected file",
Some(3) => "Ctrl+P find a file by name",
Some(4) => "Alt+I ask Claude",
Some(5) => "F1 every command",
Some(6) => "Ctrl+Q quit",
_ => "",
};
let padding = width.saturating_sub(30) / 2;
let line: String = format!("{}{text}", " ".repeat(padding))
.chars()
.take(width)
.collect();
rows.push(vec![Span::new(Style::Dim, line)]);
}
if height > 0 {
let status = if self.message.is_empty() { "No file open" } else { &self.message };
rows.push(vec![Span::new(Style::Bar, fit(status, width))]);
}
rows
}
fn render(&mut self, width: usize, height: usize) -> (Vec<Row>, Option<(usize, usize)>) {
let layout = self.layout(width, height);
let (pane_width, pane_height) = (layout.pane_width, layout.pane_height);
let mut pane = match self.editors.get_mut(self.active) {
Some(editor) => {
editor.scroll(
pane_width.saturating_sub(editor.gutter_width()),
pane_height.saturating_sub(1),
);
editor.render(pane_width, pane_height)
}
None => self.empty_pane(pane_width, pane_height),
};
let mut cursor = match (self.focus, self.editors.get(self.active)) {
(Focus::Editor, Some(editor)) => Some(editor.cursor_on_screen()),
_ => None,
};
if layout.output > 0 {
let focused = self.focus == Focus::Output && self.finder.is_none();
let mut rows = self.output.render(pane_width, layout.output, focused);
place(&mut rows, Zone::Panel);
pane.extend(rows);
}
if layout.agent > 0 {
let focused = self.focus == Focus::Agent
&& (self.finder.is_none() || self.picker.is_for_claude());
let (mut rows, (x, y)) = self.agent.render(pane_width, layout.agent, focused);
place(&mut rows, Zone::Panel);
if focused {
cursor = Some((x.min(pane_width.saturating_sub(1)), pane.len() + y));
}
pane.extend(rows);
}
if layout.agent_side > 0 {
let focused = self.focus == Focus::Agent
&& (self.finder.is_none() || self.picker.is_for_claude());
let (mut panel, (x, y)) = self.agent.render(layout.agent_side - 1, pane.len(), focused);
place(&mut panel, Zone::Panel);
for (row, panel_row) in pane.iter_mut().zip(panel) {
let used: usize = row.iter().map(|span| span.text.chars().count()).sum();
row.push(Span::new(Style::Plain, " ".repeat(pane_width.saturating_sub(used))));
row.push(Span::new(Style::Border, "│"));
row.extend(panel_row);
}
if focused {
cursor = Some((pane_width + 1 + x, y));
}
}
let mut sidebar = (layout.tree > 0).then(|| {
let focused = self.focus == Focus::Tree && self.finder.is_none();
let mut rows = self.tree.render(layout.tree - 1, pane.len(), focused, self.git.as_ref());
place(&mut rows, Zone::Side);
rows
});
let mut rows = Vec::with_capacity(height);
if layout.tabs > 0 && height > 0 {
rows.push(self.tab_row(width));
}
for (y, pane_row) in pane.into_iter().enumerate() {
let mut row = Row::new();
if let Some(sidebar) = &mut sidebar {
row.append(&mut sidebar[y]);
row.push(Span::new(Style::Border, "│"));
}
row.extend(pane_row);
rows.push(row);
}
let mut cursor = cursor.map(|(x, y)| (x + layout.tree, y + layout.tabs));
if let Some(finder) = &self.finder {
let popup = self.popup(width, height);
let piece = |style, text: &str| Span {
zone: Zone::Popup,
..Span::new(style, fit(text, popup.width))
};
let typed = format!("{}{}", self.picker.prompt(), widen(&finder.query));
if let Some(row) = rows.get_mut(popup.input_y) {
overlay(row, popup.x, &piece(Style::Input, &typed));
let hint = POPUP_HINT.chars().count();
if popup.width >= typed.chars().count() + hint + 8 {
let note = Span { zone: Zone::Popup, ..Span::new(Style::FieldNote, POPUP_HINT) };
overlay(row, popup.x + popup.width - hint, ¬e);
}
}
let matches = finder.visible(popup.capacity);
let mut lines: Vec<Span> = matches
.iter()
.map(|(item, selected)| match selected {
true => piece(Style::Selected, &format!(" > {}", widen(item))),
false => piece(Style::Menu, &format!(" {}", widen(item))),
})
.collect();
if lines.is_empty() && !self.picker.is_question() && popup.capacity > 0 {
let nothing = match self.picker {
Picker::Files | Picker::Attach => " no matching files",
_ => " nothing matches",
};
lines.push(piece(Style::Menu, nothing));
}
for (index, line) in lines.iter().enumerate() {
if let Some(row) = rows.get_mut(popup.list_y + index) {
overlay(row, popup.x, line);
}
}
let x = typed.chars().count().min(popup.width.saturating_sub(1));
cursor = Some((popup.x + x, popup.input_y));
}
(rows, cursor)
}
}