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,
Output,
}
const NONE: KeyModifiers = KeyModifiers::NONE;
const CTRL: KeyModifiers = KeyModifiers::CONTROL;
const ALT: KeyModifiers = KeyModifiers::ALT;
#[derive(Clone, Copy, PartialEq)]
enum Do {
Key(KeyCode, KeyModifiers),
Help,
Git(usize),
Look(Theme),
}
const fn key(c: char, modifiers: KeyModifiers) -> Do {
Do::Key(KeyCode::Char(c), modifiers)
}
const COMMANDS: &[(&str, &str, &str, Target, Do)] = &[
("Help", "Show every keyboard shortcut", "F1 twice or Alt+?", Target::Window, Do::Help),
("File", "Open a file by name", "Ctrl+P or Alt+P", Target::Window, key('p', CTRL)),
("File", "Search the whole project", "Alt+S", Target::Window, key('s', ALT)),
("File", "Save", "Ctrl+S", Target::Text, key('s', CTRL)),
("File", "Close this file", "Ctrl+W or Alt+W", Target::Window, key('w', CTRL)),
("File", "Next tab", "Alt+.", Target::Window, key('.', ALT)),
("File", "Previous tab", "Alt+,", Target::Window, key(',', ALT)),
("File", "Go to the first tab (2, 3 ... likewise)", "Alt+1 ... Alt+9", Target::Window, key('1', ALT)),
("File", "Quit", "Ctrl+Q", Target::Window, key('q', CTRL)),
("Tree", "Show or hide the file tree", "Ctrl+B or Alt+B", Target::Window, key('b', CTRL)),
("Tree", "Move between the tree and the text", "Alt+E", Target::Window, key('e', ALT)),
("Tree", "New file", "n in the tree", Target::Tree, key('n', NONE)),
("Tree", "New folder", "f in the tree", Target::Tree, key('f', NONE)),
("Tree", "Rename the selected file or folder", "r or F2 in the tree", Target::Tree, key('r', NONE)),
("Tree", "Delete the selected file or folder", "d or Delete there", Target::Tree, key('d', NONE)),
("Edit", "Undo", "Ctrl+Z", Target::Text, key('z', CTRL)),
("Edit", "Redo", "Ctrl+Y", Target::Text, key('y', CTRL)),
("Edit", "Select text", "Shift+arrows or drag", Target::Text, Do::Key(KeyCode::Right, KeyModifiers::SHIFT)),
("Edit", "Select everything", "Ctrl+A", Target::Text, key('a', CTRL)),
("Edit", "Copy (the line, if nothing is selected)", "Ctrl+C", Target::Text, key('c', CTRL)),
("Edit", "Cut (the line, if nothing is selected)", "Ctrl+X", Target::Text, key('x', CTRL)),
("Edit", "Paste", "Ctrl+V", Target::Text, key('v', CTRL)),
("Edit", "Comment or uncomment lines", "Alt+C or Ctrl+/", Target::Text, key('c', ALT)),
("Edit", "Duplicate the line", "Alt+D", Target::Text, key('d', ALT)),
("Edit", "Move the line up", "Alt+Up", Target::Text, Do::Key(KeyCode::Up, ALT)),
("Edit", "Move the line down", "Alt+Down", Target::Text, Do::Key(KeyCode::Down, ALT)),
("Edit", "Indent the selected lines", "Tab", Target::Text, Do::Key(KeyCode::Tab, NONE)),
("Edit", "Unindent the line or selected lines", "Shift+Tab", Target::Text, Do::Key(KeyCode::BackTab, NONE)),
("Find", "Find in this file", "Ctrl+F or Alt+F", Target::Text, key('f', CTRL)),
("Find", "Find the next match", "F3 or Alt+N", Target::Text, Do::Key(KeyCode::F(3), NONE)),
("Find", "Replace in this file", "Ctrl+R or Alt+R", Target::Text, key('r', CTRL)),
("Find", "Go to a line by number", "Ctrl+L or Alt+L", Target::Text, key('l', CTRL)),
("Find", "Go to the start of the file", "Ctrl+Home", Target::Text, Do::Key(KeyCode::Home, CTRL)),
("Find", "Go to the end of the file", "Ctrl+End", Target::Text, Do::Key(KeyCode::End, CTRL)),
("Code", "Fold or unfold the block here", "Alt+K or Ctrl+K", Target::Text, key('k', ALT)),
("Code", "Fold or unfold every block", "Alt+A", Target::Text, key('a', ALT)),
("Code", "Suggestions from the language server", "Ctrl+Space or Alt+/", Target::Text, key(' ', CTRL)),
("Code", "Explain what is under the cursor", "Alt+H or F2", Target::Text, key('h', ALT)),
("Code", "Go to the definition", "Alt+G or F12", Target::Text, key('g', ALT)),
("Run", "Run a command (build, test, start)", "Ctrl+T", Target::Window, key('t', CTRL)),
("Run", "Run the last command again", "F5", Target::Window, Do::Key(KeyCode::F(5), NONE)),
("Run", "Show or hide what it printed", "Alt+T", Target::Window, key('t', ALT)),
("Run", "Go to the next error it printed", "F8", Target::Window, Do::Key(KeyCode::F(8), NONE)),
("Run", "Go to the error before", "Shift+F8", Target::Window, Do::Key(KeyCode::F(8), KeyModifiers::SHIFT)),
("Run", "Stop the running command", "Ctrl+C in its output", Target::Output, key('c', CTRL)),
("Git", "Open the git menu", "Ctrl+G or Alt+V", Target::Window, key('g', CTRL)),
("Git", "Stage this file", "in the git menu", Target::Window, Do::Git(0)),
("Git", "Unstage this file", "in the git menu", Target::Window, Do::Git(1)),
("Git", "Stage all changes", "in the git menu", Target::Window, Do::Git(2)),
("Git", "Unstage everything", "in the git menu", Target::Window, Do::Git(3)),
("Git", "Commit what is staged", "in the git menu", Target::Window, Do::Git(4)),
("Git", "Switch to another branch", "in the git menu", Target::Window, Do::Git(5)),
("Git", "Make a new branch", "in the git menu", Target::Window, Do::Git(6)),
("Git", "Pull", "in the git menu", Target::Window, Do::Git(7)),
("Git", "Push", "in the git menu", Target::Window, Do::Git(8)),
("Claude", "Ask Claude (show its panel)", "Alt+I", Target::Claude, Do::Key(KeyCode::Null, NONE)),
("Claude", "The panel's own commands", "/ there", Target::Claude, key('/', NONE)),
("Claude", "Attach a file to the question", "@ there", Target::Claude, key('@', NONE)),
("Claude", "New line in the question", "Alt+Enter there", Target::Claude, Do::Key(KeyCode::Enter, ALT)),
("Claude", "What it may do", "Alt+M there", Target::Claude, key('m', ALT)),
("Claude", "Earlier conversations", "Ctrl+R there", Target::Claude, key('r', CTRL)),
("Claude", "New conversation", "Ctrl+N there", Target::Claude, key('n', CTRL)),
("Claude", "Undo its changes to files", "Alt+U there", Target::Claude, key('u', ALT)),
("Claude", "Open the files it changed", "Alt+O there", Target::Claude, key('o', ALT)),
("Claude", "Copy the last answer", "Alt+C there", Target::Claude, key('c', ALT)),
("Claude", "Make the panel as big as it goes", "Alt+Z there", Target::Claude, key('z', ALT)),
("Claude", "Make the panel bigger", "Alt+Up there", Target::Claude, Do::Key(KeyCode::Up, ALT)),
("Claude", "Make the panel smaller", "Alt+Down there", Target::Claude, Do::Key(KeyCode::Down, ALT)),
("Claude", "Stop it, or go back to the text", "Esc there", Target::Claude, Do::Key(KeyCode::Esc, NONE)),
("Look", "Dark colours", "CURD_THEME=dark", Target::Window, Do::Look(Theme::DARK)),
("Look", "Light colours", "CURD_THEME=light", Target::Window, Do::Look(Theme::LIGHT)),
("Look", "The terminal's own colours", "CURD_THEME=classic", Target::Window, Do::Look(Theme::CLASSIC)),
];
const OTHER_KEYS: &[(&str, &str, &str)] = &[
("In any list", "Narrow it down", "type part of a name"),
("In any list", "Choose", "Up / Down, the wheel"),
("In any list", "Pick", "Enter, or a click"),
("In any list", "Close", "Esc, or click outside"),
("Mouse", "Put the cursor there", "click in the text"),
("Mouse", "Select the word", "double click"),
("Mouse", "Fold or unfold a block", "click its - or +"),
("Mouse", "Close a tab", "click x, or middle click"),
("Mouse", "Go through the tabs", "wheel over the tab bar"),
("Mouse", "Go to an error", "click it in the output"),
("Mouse", "Resize the Claude panel", "drag its edge"),
];
const HELP_COLUMN: usize = 68;
const HELP_KEYS: usize = 28;
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>,
help: Option<usize>,
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,
help: 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;
}
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();
}
}
pub fn set_theme(&mut self, theme: Theme) {
self.screen = Screen::with_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.show_branch();
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(|(group, name, keys, ..)| format!("{:<48}{keys}", format!("{group}: {name}")))
.collect();
self.pick(Picker::Commands, lines);
}
fn run_listed(&mut self, index: usize) {
let (_, _, _, target, action) = 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;
}
Target::Output if self.show_output => self.focus = Focus::Output,
Target::Output => return self.say("No command is running".into()),
}
match action {
Do::Key(KeyCode::Null, _) => {}
Do::Key(code, modifiers) => self.handle_key(KeyEvent::new(code, modifiers)),
Do::Help => self.help = Some(0),
Do::Git(_) if self.git.is_none() => self.say("This folder is not in git".into()),
Do::Git(line) => self.git_command(line),
Do::Look(theme) => self.set_theme(theme),
}
}
fn help_lines() -> Vec<(&'static str, &'static str)> {
let commands = COMMANDS.iter().map(|(group, name, keys, ..)| (*group, *name, *keys));
let mut lines = Vec::new();
let mut last = "";
for (group, name, keys) in commands.chain(OTHER_KEYS.iter().copied()) {
if group != last {
if !lines.is_empty() {
lines.push(("", ""));
}
lines.push((group, ""));
last = group;
}
lines.push((name, keys));
}
lines
}
fn help_shape(width: usize) -> (usize, usize) {
let columns = (width / HELP_COLUMN).max(1);
(columns, Self::help_lines().len().div_ceil(columns))
}
fn help_page(width: usize, height: usize, top: usize) -> Vec<Row> {
let lines = Self::help_lines();
let (columns, rows) = Self::help_shape(width);
let title = " Keyboard shortcuts · Up/Down scroll · Esc closes · F1 lists them to pick from";
let mut page = vec![vec![Span::new(Style::Title, fit(title, width))]];
for row in top..top + height.saturating_sub(1) {
let mut spans = Row::new();
for column in 0..columns {
let cells = if column + 1 == columns { width - column * HELP_COLUMN.min(width) } else { HELP_COLUMN };
match lines.get(column * rows + row).filter(|_| row < rows) {
Some((group, "")) => spans.push(Span::new(Style::Accent, fit(&format!(" {group}"), cells))),
Some((name, keys)) => {
let keys_width = HELP_KEYS.min(cells);
spans.push(Span::new(Style::Bold, fit(&format!(" {keys}"), keys_width)));
spans.push(Span::new(Style::Plain, fit(name, cells - keys_width)));
}
None => spans.push(Span::new(Style::Plain, fit("", cells))),
}
}
page.push(spans);
}
page.truncate(height);
place(&mut page[1.min(height)..], Zone::Panel);
page
}
fn help_key(&mut self, key: KeyEvent) {
let Some(top) = self.help else {
return;
};
let page = self.size.1.saturating_sub(2).max(1);
let (_, rows) = Self::help_shape(self.size.0);
let last = rows.saturating_sub(self.size.1.saturating_sub(1));
self.help = match key.code {
KeyCode::Up => Some(top.saturating_sub(1)),
KeyCode::Down => Some((top + 1).min(last)),
KeyCode::PageUp => Some(top.saturating_sub(page)),
KeyCode::PageDown => Some((top + page).min(last)),
KeyCode::Home => Some(0),
KeyCode::End => Some(last),
KeyCode::F(1) => {
self.help = None;
return self.list_commands();
}
_ => None,
};
}
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;
self.show_branch();
}
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.help.is_some() {
return self.help_key(key);
}
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('?') if alt => self.help = Some(0),
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::F(1) if self.picker == Picker::Commands => {
self.finder = None;
self.help = Some(0);
}
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) {
if self.help.is_some() {
let key = match mouse.kind {
MouseEventKind::ScrollUp => KeyCode::Up,
MouseEventKind::ScrollDown => KeyCode::Down,
MouseEventKind::Down(_) => KeyCode::Esc,
_ => return,
};
return self.help_key(KeyEvent::new(key, NONE));
}
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)>) {
if let Some(top) = self.help {
return (Self::help_page(width, height, top), None);
}
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)
}
}