curd-editor 0.8.0

A small terminal code editor: file tree, git status and change markers, tabs, undo, selection, search and replace, a git menu, and language-server colours, errors and completion
use std::fs;
use std::io;

#[cfg(test)]
mod tests;

#[derive(Default)]
pub struct Document {
    pub lines: Vec<String>,
    /// Where the document is saved. `None` when started without a file.
    pub path: Option<String>,
    /// True when there are changes that have not been saved.
    pub dirty: bool,
    /// True when the file on disk used Windows line endings (\r\n),
    /// so saving writes them back the same way.
    pub crlf: bool,
}

impl Document {
    /// Opens `path`. A path that does not exist yet gives an empty document
    /// that will be created on the first save.
    pub fn open(path: &str) -> io::Result<Self> {
        // Said outright, because reading a folder fails in a different way
        // on each system (on Windows it can look like a missing file).
        if std::path::Path::new(path).is_dir() {
            return Err(io::Error::new(io::ErrorKind::InvalidInput, "is a folder"));
        }
        let text = match fs::read_to_string(path) {
            Ok(text) => text,
            Err(error) if error.kind() == io::ErrorKind::NotFound => String::new(),
            Err(error) => return Err(error),
        };
        Ok(Self {
            lines: text.lines().map(String::from).collect(),
            path: Some(path.to_string()),
            dirty: false,
            crlf: text.contains("\r\n"),
        })
    }

    /// Writes the document to its path. Every line ends with a line ending.
    pub fn save(&mut self) -> io::Result<()> {
        let Some(path) = &self.path else {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "no file name",
            ));
        };
        let ending = if self.crlf { "\r\n" } else { "\n" };
        let mut text = String::new();
        for line in &self.lines {
            text.push_str(line);
            text.push_str(ending);
        }
        fs::write(path, text)?;
        self.dirty = false;
        Ok(())
    }

    pub fn is_empty(&self) -> bool {
        self.lines.is_empty()
    }

    pub fn len(&self) -> usize {
        self.lines.len()
    }

    pub fn line_len(&self, y: usize) -> usize {
        match self.lines.get(y) {
            Some(line) => line.chars().count(),
            None => 0,
        }
    }

    /// Inserts `c` before character `x` of line `y`.
    pub fn insert_char(&mut self, x: usize, y: usize, c: char) {
        self.ensure_line(y);
        let line = &mut self.lines[y];
        line.insert(byte_index(line, x), c);
        self.dirty = true;
    }

    /// Splits line `y` in two at character `x`.
    pub fn insert_newline(&mut self, x: usize, y: usize) {
        self.ensure_line(y);
        let line = &mut self.lines[y];
        let rest = line.split_off(byte_index(line, x));
        self.lines.insert(y + 1, rest);
        self.dirty = true;
    }

    /// Deletes character `x` of line `y`. At the end of a line it joins the
    /// next line onto this one instead.
    pub fn delete_char(&mut self, x: usize, y: usize) {
        if y >= self.lines.len() {
            return;
        }
        if x < self.line_len(y) {
            let line = &mut self.lines[y];
            line.remove(byte_index(line, x));
        } else if y + 1 < self.lines.len() {
            let next = self.lines.remove(y + 1);
            self.lines[y].push_str(&next);
        } else {
            return;
        }
        self.dirty = true;
    }

    /// Makes sure line `y` exists, so an empty document can be typed into.
    fn ensure_line(&mut self, y: usize) {
        while self.lines.len() <= y {
            self.lines.push(String::new());
        }
    }
}

/// Converts a character position in `line` to a byte position.
/// Positions past the end give the end of the line.
fn byte_index(line: &str, x: usize) -> usize {
    line.char_indices().nth(x).map_or(line.len(), |(i, _)| i)
}