//! Multi-line input field with history. use unicode_width::UnicodeWidthChar; #[derive(Default)] pub struct Editor { pub lines: Vec, /// Cursor: line index and char index. pub row: usize, pub col: usize, history: Vec, hist_pos: Option, } fn byte_idx(s: &str, ch: usize) -> usize { s.char_indices().nth(ch).map(|(i, _)| i).unwrap_or(s.len()) } impl Editor { pub fn new() -> Self { let history = std::fs::read_to_string(crate::conf::data_dir().join("history.txt")) .map(|t| t.lines().map(|l| l.replace("\\n", "\n")).collect()) .unwrap_or_default(); Self { lines: vec![String::new()], history, ..Default::default() } } pub fn text(&self) -> String { self.lines.join("\n") } pub fn is_empty(&self) -> bool { self.lines.iter().all(|l| l.is_empty()) } pub fn set(&mut self, text: &str) { self.lines = text.split('\n').map(String::from).collect(); if self.lines.is_empty() { self.lines.push(String::new()); } self.row = self.lines.len() - 1; self.col = self.lines[self.row].chars().count(); } pub fn clear(&mut self) { self.lines = vec![String::new()]; self.row = 0; self.col = 0; self.hist_pos = None; } /// Take the text (and remember it in the history). pub fn take(&mut self) -> String { let t = self.text(); if !t.trim().is_empty() && self.history.last() != Some(&t) { self.history.push(t.clone()); if self.history.len() > 500 { self.history.remove(0); } let _ = std::fs::create_dir_all(crate::conf::data_dir()); let _ = std::fs::write(crate::conf::data_dir().join("history.txt"), self.history.iter().map(|h| h.replace('\n', "\\n")).collect::>().join("\n")); } self.clear(); t } pub fn insert(&mut self, s: &str) { for (i, part) in s.split('\n').enumerate() { if i > 0 { self.newline(); } let part = part.replace('\r', "").replace('\t', " "); let line = &mut self.lines[self.row]; let at = byte_idx(line, self.col); line.insert_str(at, &part); self.col += part.chars().count(); } } pub fn newline(&mut self) { let line = &mut self.lines[self.row]; let at = byte_idx(line, self.col); let rest = line.split_off(at); self.lines.insert(self.row + 1, rest); self.row += 1; self.col = 0; } pub fn backspace(&mut self) { if self.col > 0 { let line = &mut self.lines[self.row]; let a = byte_idx(line, self.col - 1); let b = byte_idx(line, self.col); line.replace_range(a..b, ""); self.col -= 1; } else if self.row > 0 { let line = self.lines.remove(self.row); self.row -= 1; self.col = self.lines[self.row].chars().count(); self.lines[self.row].push_str(&line); } } pub fn delete(&mut self) { let len = self.lines[self.row].chars().count(); if self.col < len { let line = &mut self.lines[self.row]; let a = byte_idx(line, self.col); let b = byte_idx(line, self.col + 1); line.replace_range(a..b, ""); } else if self.row + 1 < self.lines.len() { let next = self.lines.remove(self.row + 1); self.lines[self.row].push_str(&next); } } pub fn delete_word(&mut self) { let chars: Vec = self.lines[self.row].chars().collect(); let mut i = self.col; while i > 0 && chars[i - 1].is_whitespace() { i -= 1; } while i > 0 && !chars[i - 1].is_whitespace() { i -= 1; } let line = &mut self.lines[self.row]; let a = byte_idx(line, i); let b = byte_idx(line, self.col); line.replace_range(a..b, ""); self.col = i; } pub fn left(&mut self) { if self.col > 0 { self.col -= 1; } else if self.row > 0 { self.row -= 1; self.col = self.lines[self.row].chars().count(); } } pub fn right(&mut self) { if self.col < self.lines[self.row].chars().count() { self.col += 1; } else if self.row + 1 < self.lines.len() { self.row += 1; self.col = 0; } } pub fn home(&mut self) { self.col = 0; } pub fn end(&mut self) { self.col = self.lines[self.row].chars().count(); } /// Up: previous line, or older history entry on the first line. pub fn up(&mut self) { if self.row > 0 { self.row -= 1; self.col = self.col.min(self.lines[self.row].chars().count()); return; } if self.history.is_empty() { return; } let pos = match self.hist_pos { None if !self.is_empty() => return, None => self.history.len() - 1, Some(0) => 0, Some(p) => p - 1, }; self.hist_pos = Some(pos); let h = self.history[pos].clone(); self.set(&h); } pub fn down(&mut self) { if self.row + 1 < self.lines.len() { self.row += 1; self.col = self.col.min(self.lines[self.row].chars().count()); return; } if let Some(p) = self.hist_pos { if p + 1 < self.history.len() { self.hist_pos = Some(p + 1); let h = self.history[p + 1].clone(); self.set(&h); } else { self.clear(); } } } /// The word the cursor is in (for @file and /command completion): (start char, word). pub fn current_word(&self) -> (usize, String) { let chars: Vec = self.lines[self.row].chars().collect(); let mut i = self.col.min(chars.len()); while i > 0 && !chars[i - 1].is_whitespace() { i -= 1; } (i, chars[i..self.col.min(chars.len())].iter().collect()) } pub fn replace_word(&mut self, start: usize, with: &str) { let line = &mut self.lines[self.row]; let a = byte_idx(line, start); let b = byte_idx(line, self.col); line.replace_range(a..b, with); self.col = start + with.chars().count(); } /// The text as it is shown at `width` columns: every logical line is broken into rows, preferably after a /// space, otherwise inside a long word. Each row is (line index, first char, end char). pub fn layout(&self, width: usize) -> Vec<(usize, usize, usize)> { let width = width.max(1); let mut rows = Vec::new(); for (i, line) in self.lines.iter().enumerate() { let chars: Vec = line.chars().collect(); if chars.is_empty() { rows.push((i, 0, 0)); continue; } let mut start = 0; while start < chars.len() { let mut w = 0; let mut end = start; let mut last_space = None; while end < chars.len() { let cw = UnicodeWidthChar::width(chars[end]).unwrap_or(0); if w + cw > width && end > start { break; } w += cw; end += 1; if chars[end - 1] == ' ' { last_space = Some(end); } } if end < chars.len() { if let Some(sp) = last_space.filter(|sp| *sp > start) { end = sp; } } rows.push((i, start, end)); start = end; } } rows } /// The text of one row of `layout`. pub fn row_text(&self, (line, a, b): (usize, usize, usize)) -> String { self.lines[line].chars().skip(a).take(b - a).collect() } /// Cursor in the wrapped view: (row index in `layout`, display column). pub fn cursor_in(&self, layout: &[(usize, usize, usize)]) -> (usize, usize) { for (n, &(line, a, b)) in layout.iter().enumerate() { let last = layout.get(n + 1).is_none_or(|next| next.0 != line); if line == self.row && self.col >= a && (self.col < b || (last && self.col <= b)) { let w: usize = self.lines[line].chars().skip(a).take(self.col - a).map(|c| UnicodeWidthChar::width(c).unwrap_or(0)).sum(); return (n, w); } } (layout.len().saturating_sub(1), 0) } } #[cfg(test)] mod tests { use super::*; fn editor(text: &str) -> Editor { let mut e = Editor { lines: vec![String::new()], ..Default::default() }; e.set(text); e } #[test] fn long_line_wraps_at_spaces() { let e = editor("aaa bbb ccc ddd"); let rows: Vec = e.layout(8).into_iter().map(|r| e.row_text(r)).collect(); assert_eq!(rows, vec!["aaa bbb ", "ccc ddd"]); } #[test] fn long_word_breaks_inside() { let e = editor("abcdefghij"); let rows: Vec = e.layout(4).into_iter().map(|r| e.row_text(r)).collect(); assert_eq!(rows, vec!["abcd", "efgh", "ij"]); } #[test] fn empty_lines_keep_a_row_and_nothing_is_lost() { let e = editor("one\n\ntwo words here"); let l = e.layout(6); let joined: String = l.iter().map(|r| e.row_text(*r)).collect::>().join("|"); assert_eq!(joined, "one||two |words |here"); } #[test] fn cursor_follows_the_wrap() { let mut e = editor("aaa bbb ccc ddd"); let l = e.layout(8); assert_eq!(e.cursor_in(&l), (1, 7)); // end of the text, second row e.col = 8; // before "ccc" assert_eq!(e.cursor_in(&l), (1, 0)); e.col = 3; assert_eq!(e.cursor_in(&l), (0, 3)); } }