curd-editor 0.18.0

A terminal code editor: file tree, tabs, git, language servers, run and jump to errors, and a Claude panel that uses your own claude command
//! Running a command in the project (a build, the tests, the program
//! itself) and showing what it prints in a panel under the text.
//!
//! The panel is a list of lines. A line that names a place in a file, as
//! compilers and test runners print them (`src/main.rs:12:5`), can be
//! jumped to.

use std::io::{BufRead, BufReader};
use std::path::Path;
use std::process::{Child, Command, Stdio};

use crate::screen::{fit, Row, Span, Style};

#[cfg(test)]
mod tests;

/// The panel keeps this many lines; older ones are dropped.
const MAX_LINES: usize = 5000;

/// Something the running command did.
pub enum Event {
    /// A line it printed.
    Line(String),
    /// It has printed everything and ended.
    Exit,
}

/// Starts `command` with the system's shell in `dir`. Every line it
/// prints (errors too) is passed to `forward`, and its end.
pub fn start(
    command: &str,
    dir: &Path,
    forward: impl Fn(Event) + Send + Clone + 'static,
) -> std::io::Result<Child> {
    let (shell, flag) = if cfg!(windows) { ("cmd", "/C") } else { ("sh", "-c") };
    let mut child = Command::new(shell)
        .arg(flag)
        .arg(command)
        .current_dir(dir)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()?;
    let errors = child.stderr.take();
    let output = child.stdout.take();
    let pass_on = |stream: Box<dyn std::io::Read + Send>, forward: &(dyn Fn(Event) + Send)| {
        // Not every program prints proper text: keep what can be read.
        let mut reader = BufReader::new(stream);
        let mut bytes = Vec::new();
        while reader.read_until(b'\n', &mut bytes).is_ok_and(|read| read > 0) {
            forward(Event::Line(String::from_utf8_lossy(&bytes).into_owned()));
            bytes.clear();
        }
    };
    let error_forward = forward.clone();
    let error_thread = errors.map(|errors| {
        std::thread::spawn(move || pass_on(Box::new(errors), &error_forward))
    });
    if let Some(output) = output {
        std::thread::spawn(move || {
            pass_on(Box::new(output), &forward);
            if let Some(thread) = error_thread {
                let _ = thread.join();
            }
            // The exit code itself is asked for by whoever holds the child.
            forward(Event::Exit);
        });
    }
    Ok(child)
}

/// A printed line as the panel shows it: without the line ending, the
/// colour codes some programs print, or the part a progress bar wrote
/// over.
pub fn clean(line: &str) -> String {
    let line = line.trim_end_matches(['\n', '\r']);
    let line = line.rsplit('\r').next().unwrap_or(line);
    let mut text = String::new();
    let mut chars = line.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '\x1b' {
            // An escape sequence: `ESC [ ... letter`.
            if chars.next_if_eq(&'[').is_some() {
                while chars.next_if(|c| !c.is_ascii_alphabetic()).is_some() {}
                chars.next();
            }
        } else if c == '\t' {
            text.push_str("    ");
        } else if !c.is_control() {
            text.push(c);
        }
    }
    text
}

/// The place in a file that `line` names, if it names one: the file, and
/// the line and column counted from 1 (column 1 if none is given).
/// `src/main.rs:12:5`, `  --> src/lib.rs:3:1`, `File "x.py", line 4`.
pub fn location(line: &str) -> Option<(String, usize, usize)> {
    // Python's own way of saying it.
    if let Some((_, rest)) = line.split_once("File \"")
        && let Some((file, rest)) = rest.split_once("\", line ")
    {
        let digits: String = rest.chars().take_while(char::is_ascii_digit).collect();
        let row = digits.parse::<usize>().ok().filter(|row| *row > 0)?;
        return Some((file.to_string(), row, 1));
    }
    let is_path = |c: char| c.is_alphanumeric() || "/\\._-+@~".contains(c);
    // The digits `text` starts with, as a number, and what follows them.
    fn number(text: &str) -> Option<(usize, &str)> {
        let digits = text.chars().take_while(char::is_ascii_digit).count();
        Some((text[..digits].parse::<usize>().ok().filter(|n| *n > 0)?, &text[digits..]))
    }
    for (at, _) in line.match_indices(':') {
        let file: String = line[..at].chars().rev().take_while(|c| is_path(*c)).collect();
        let file: String = file.chars().rev().collect();
        // A name with a letter and a dot or a slash in it, then a line
        // number, and perhaps a column after another colon.
        if file.contains(['.', '/'])
            && file.chars().any(char::is_alphabetic)
            && let Some((row, rest)) = number(&line[at + 1..])
        {
            let column = rest.strip_prefix(':').and_then(number).map_or(1, |(column, _)| column);
            return Some((file, row, column));
        }
    }
    None
}

/// The panel under the text: the command and what it printed.
#[derive(Default)]
pub struct Output {
    /// The command last run.
    pub command: String,
    pub lines: Vec<String>,
    pub running: bool,
    /// How it ended, once it has.
    pub status: String,
    /// The line the keys are on.
    pub selected: usize,
    /// The first line shown.
    top: usize,
    /// The line F8 last went to. Walking through the places starts at the
    /// top, wherever the keys are.
    walked: Option<usize>,
}

impl Output {
    /// Clears the panel for a new run of `command`.
    pub fn begin(&mut self, command: &str) {
        *self = Self {
            command: command.to_string(),
            running: true,
            ..Self::default()
        };
    }

    /// Adds a printed line. The view follows the output while the keys
    /// are on its last line.
    pub fn push(&mut self, line: &str) {
        let following = self.selected + 1 >= self.lines.len();
        self.lines.push(clean(line));
        if self.lines.len() > MAX_LINES {
            self.lines.remove(0);
            self.selected = self.selected.saturating_sub(1);
        }
        if following {
            self.selected = self.lines.len() - 1;
        }
    }

    /// Notes that the command ended with `code` (`None`: it was stopped).
    pub fn finish(&mut self, code: Option<i32>) {
        self.running = false;
        self.status = match code {
            Some(0) => "finished".into(),
            Some(code) => format!("failed (exit code {code})"),
            None => "stopped".into(),
        };
    }

    /// Moves the keys `rows` lines down (up, when negative).
    pub fn move_by(&mut self, rows: isize) {
        let last = self.lines.len().saturating_sub(1) as isize;
        self.selected = (self.selected as isize).saturating_add(rows).clamp(0, last) as usize;
    }

    /// Puts the keys on the line shown on row `row` of the panel's lines.
    pub fn click(&mut self, row: usize) {
        if self.top + row < self.lines.len() {
            self.selected = self.top + row;
        }
    }

    /// The next line that names a place in a file, after the one this
    /// last found (or before it): the first one, the first time.
    pub fn next_location(&mut self, forward: bool) -> Option<(String, usize, usize)> {
        let lines: Vec<usize> = match (forward, self.walked) {
            (true, None) => (0..self.lines.len()).collect(),
            (true, Some(at)) => (at + 1..self.lines.len()).collect(),
            (false, None) => (0..self.lines.len()).rev().collect(),
            (false, Some(at)) => (0..at).rev().collect(),
        };
        let found = lines.into_iter().find(|line| location(&self.lines[*line]).is_some())?;
        self.walked = Some(found);
        self.selected = found;
        location(&self.lines[found])
    }

    /// The place the selected line names, if it names one.
    pub fn selected_location(&self) -> Option<(String, usize, usize)> {
        location(self.lines.get(self.selected)?)
    }

    /// The panel as `height` rows: a title and the lines.
    pub fn render(&mut self, width: usize, height: usize, focused: bool) -> Vec<Row> {
        let state = if self.running { "running (Ctrl+C stops it)" } else { self.status.as_str() };
        let title = format!(" Run · {} · {state}", self.command);
        let title_style = if focused { Style::Title } else { Style::Menu };
        let mut rows = vec![vec![Span::new(title_style, fit(&title, width))]];

        let body = height.saturating_sub(1);
        // Keep the selected line in view.
        if self.selected < self.top {
            self.top = self.selected;
        }
        if body > 0 && self.selected >= self.top + body {
            self.top = self.selected + 1 - body;
        }
        for row in 0..body {
            let index = self.top + row;
            let text = self.lines.get(index).map_or("", String::as_str);
            let lower = text.trim_start().to_lowercase();
            let style = if focused && index == self.selected && index < self.lines.len() {
                Style::Selected
            } else if lower.starts_with("error")
                || lower.contains(": error")
                || lower.contains("panicked at")
                || lower.contains("failed")
            {
                Style::Error
            } else if lower.starts_with("warning") || lower.contains(": warning") {
                Style::Warning
            } else {
                Style::Plain
            };
            rows.push(vec![Span::new(style, fit(text, width))]);
        }
        rows.truncate(height);
        rows
    }
}