curd-editor 0.24.0

A terminal code editor: file tree, tabs, git, language servers, run and jump to errors, and a panel for Claude or any other assistant
mod agent;
mod diff;
mod document;
mod editor;
mod finder;
mod folds;
mod git;
mod highlight;
mod history;
mod lsp;
mod runner;
mod screen;
mod search;
mod snippets;
mod terminal;
mod theme;
mod tree;
mod workspace;

use std::path::{Path, PathBuf};
use std::sync::mpsc::channel;

use terminal::Terminal;
use workspace::{AppEvent, Workspace};

const USAGE: &str = "\
curd, a terminal code editor

  curd                 start with an empty file
  curd FILE...         open those files, in tabs
  curd FOLDER          open the folder as a project, with its file tree
  curd --version       say which version this is, and for which machine
  curd --help          show this

Inside it, F1 lists every command and F1 twice shows every key.
Colours: CURD_THEME=dark, light or classic.";

/// `curd`            an empty file
/// `curd file ...`   those files, in tabs
/// `curd folder`     the folder as a project, with its file tree
fn main() -> std::io::Result<()> {
    let args: Vec<String> = std::env::args().skip(1).collect();
    // Answered without a terminal, so a script (or a check that a freshly
    // built binary runs on this machine) can ask.
    match args.first().map(String::as_str) {
        Some("--version" | "-V") => {
            // The kind of machine it was built for is part of the answer.
            println!(
                "curd {} ({}-{})",
                env!("CARGO_PKG_VERSION"),
                std::env::consts::ARCH,
                std::env::consts::OS
            );
            return Ok(());
        }
        Some("--help" | "-h") => {
            println!("{USAGE}");
            return Ok(());
        }
        _ => {}
    }
    let here = std::env::current_dir()?;

    let folder = args.first().map(PathBuf::from).filter(|path| path.is_dir());
    let files = &args[folder.is_some() as usize..];
    // The project is the folder given, or the one the first file belongs
    // to: its git repository, or else the folder it sits in.
    let root = match (&folder, files.first()) {
        (Some(folder), _) => folder.clone(),
        (None, Some(file)) => {
            let file = std::path::absolute(file)?;
            lsp::find_root(file.parent().unwrap_or(&here), &[])
        }
        (None, None) => here,
    };
    let root = std::fs::canonicalize(&root).unwrap_or(root);

    let _terminal = Terminal::start()?;

    // Keys, language-server messages and git results arrive on one queue.
    let (sender, events) = channel();
    let lsp_setting = std::env::var("CURD_LSP").ok();
    let mut workspace = Workspace::new(root, Some(sender.clone()), lsp_setting);
    workspace.agent_setting = std::env::var("CURD_AGENT").ok();
    workspace.set_theme(theme::Theme::choose(
        std::env::var("CURD_THEME").ok().as_deref(),
        std::env::var("COLORTERM").ok().as_deref(),
    ));
    for file in files {
        workspace.open(Path::new(file));
    }
    if folder.is_some() {
        workspace.show_folder();
    } else if args.is_empty() {
        workspace.open_empty();
    } else if !workspace.has_files() {
        // Nothing could be opened: show the folder, and why.
        workspace.show_folder();
    }

    // The assistants the panel can talk to: Claude, and whatever is
    // described in agents.json.
    let home = PathBuf::from(std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).unwrap_or_default());
    let config = agent::config_path(std::env::var("XDG_CONFIG_HOME").ok().as_deref(), &home);
    workspace.set_agents(std::fs::read_to_string(config).ok().as_deref());

    // Keys and the mouse are read here and queued. While another program
    // has the terminal (to sign in, say) nothing is read, so that what is
    // typed goes to it.
    let paused = workspace.input_paused.clone();
    std::thread::spawn(move || loop {
        if paused.load(std::sync::atomic::Ordering::Relaxed) {
            std::thread::sleep(std::time::Duration::from_millis(50));
            continue;
        }
        match crossterm::event::poll(workspace::INPUT_WAIT) {
            Ok(true) => {
                let Ok(event) = crossterm::event::read() else {
                    break;
                };
                if sender.send(AppEvent::Input(event)).is_err() {
                    break;
                }
            }
            Ok(false) => {}
            Err(_) => break,
        }
    });

    workspace.run(&events)
}