use std::fs;
use std::io;
#[cfg(test)]
mod tests;
#[derive(Default)]
pub struct Document {
pub lines: Vec<String>,
pub path: Option<String>,
pub dirty: bool,
pub crlf: bool,
}
impl Document {
pub fn open(path: &str) -> io::Result<Self> {
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"),
})
}
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,
}
}
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;
}
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;
}
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;
}
fn ensure_line(&mut self, y: usize) {
while self.lines.len() <= y {
self.lines.push(String::new());
}
}
}
fn byte_index(line: &str, x: usize) -> usize {
line.char_indices().nth(x).map_or(line.len(), |(i, _)| i)
}