//! Multi-line input editor with history. #[derive(Default)] pub struct Editor { pub buf: String, /// byte offset, always on a char boundary pub cur: usize, history: Vec, /// index into history while browsing; None = editing a fresh line hist_pos: Option, stash: String, } pub enum Action { None, Submit(String), } impl Editor { pub fn insert(&mut self, s: &str) { // normalize pasted CRLF let s = s.replace("\r\n", "\n").replace('\r', "\n"); self.buf.insert_str(self.cur, &s); self.cur += s.len(); } fn prev_boundary(&self) -> usize { self.buf[..self.cur] .char_indices() .next_back() .map_or(0, |(i, _)| i) } fn next_boundary(&self) -> usize { self.buf[self.cur..] .chars() .next() .map_or(self.cur, |c| self.cur + c.len_utf8()) } fn line_start(&self) -> usize { self.buf[..self.cur].rfind('\n').map_or(0, |i| i + 1) } fn line_end(&self) -> usize { self.buf[self.cur..] .find('\n') .map_or(self.buf.len(), |i| self.cur + i) } pub fn backspace(&mut self) { if self.cur > 0 { let p = self.prev_boundary(); self.buf.replace_range(p..self.cur, ""); self.cur = p; } } pub fn delete(&mut self) { let n = self.next_boundary(); self.buf.replace_range(self.cur..n, ""); } pub fn left(&mut self) { self.cur = self.prev_boundary(); } pub fn right(&mut self) { self.cur = self.next_boundary(); } pub fn home(&mut self) { self.cur = self.line_start(); } pub fn end(&mut self) { self.cur = self.line_end(); } /// Delete from line start to cursor. pub fn kill_line(&mut self) { let s = self.line_start(); self.buf.replace_range(s..self.cur, ""); self.cur = s; } pub fn kill_word(&mut self) { let before = &self.buf[..self.cur]; let trimmed = before.trim_end(); let s = trimmed.rfind(char::is_whitespace).map_or(0, |i| i + 1); self.buf.replace_range(s..self.cur, ""); self.cur = s; } /// Up: previous line in a multi-line buffer, else history. pub fn up(&mut self) { let ls = self.line_start(); if ls > 0 { let col = self.buf[ls..self.cur].chars().count(); let pls = self.buf[..ls - 1].rfind('\n').map_or(0, |i| i + 1); self.cur = advance(&self.buf, pls, ls - 1, col); return; } if self.history.is_empty() { return; } let i = match self.hist_pos { None => { self.stash = std::mem::take(&mut self.buf); self.history.len() - 1 } Some(0) => 0, Some(i) => i - 1, }; self.hist_pos = Some(i); self.buf = self.history[i].clone(); self.cur = self.buf.len(); } pub fn down(&mut self) { let le = self.line_end(); if le < self.buf.len() { let col = self.buf[self.line_start()..self.cur].chars().count(); let nle = self.buf[le + 1..] .find('\n') .map_or(self.buf.len(), |i| le + 1 + i); self.cur = advance(&self.buf, le + 1, nle, col); return; } match self.hist_pos { None => {} Some(i) if i + 1 < self.history.len() => { self.hist_pos = Some(i + 1); self.buf = self.history[i + 1].clone(); } Some(_) => { self.hist_pos = None; self.buf = std::mem::take(&mut self.stash); } } self.cur = self.buf.len(); } pub fn submit(&mut self) -> Action { let s = std::mem::take(&mut self.buf); self.cur = 0; self.hist_pos = None; if s.trim().is_empty() { return Action::None; } if self.history.last() != Some(&s) { self.history.push(s.clone()); } Action::Submit(s) } /// Replace `buf[start..cur]` with `text`; cursor lands after it. pub fn replace(&mut self, start: usize, text: &str) { self.buf.replace_range(start..self.cur, text); self.cur = start + text.len(); } /// Buffer as screen rows hard-wrapped at `w` chars, plus the cursor's (row, col). /// The cursor at the end of a full row sits on a fresh row below it. // ponytail: counts chars, not cell width; CJK/emoji can overflow a row by a cell. Use unicode-width if it matters. pub fn wrapped(&self, w: usize) -> (Vec, (usize, usize)) { let w = w.max(1); let (cur_line, cur_col) = self.cursor_rc(); let mut rows = vec![]; let mut cur = (0, 0); for (i, line) in self.buf.split('\n').enumerate() { let chars: Vec = line.chars().collect(); let mut n = chars.len().div_ceil(w).max(1); if i == cur_line { cur = (rows.len() + cur_col / w, cur_col % w); n = n.max(cur_col / w + 1); } rows.extend((0..n).map(|k| chars.iter().skip(k * w).take(w).collect::())); } (rows, cur) } /// Enter after a typed `\`: the backslash becomes a newline (for terminals that cannot /// tell shift-enter from enter). True when it did. pub fn continue_line(&mut self) -> bool { if self.buf[..self.cur].ends_with('\\') { self.backspace(); self.insert("\n"); return true; } false } /// (row, col) of the cursor in chars. pub fn cursor_rc(&self) -> (usize, usize) { let before = &self.buf[..self.cur]; ( before.matches('\n').count(), before[self.line_start()..].chars().count(), ) } } /// Byte offset `col` chars into `buf[from..to]`, clamped to `to`. fn advance(buf: &str, from: usize, to: usize, col: usize) -> usize { buf[from..to] .char_indices() .nth(col) .map_or(to, |(i, _)| from + i) } #[cfg(test)] mod tests { use super::*; #[test] fn wraps_and_places_cursor() { let mut e = Editor::default(); e.insert("abcdef\nxy"); let (rows, cur) = e.wrapped(4); assert_eq!(rows, ["abcd", "ef", "xy"]); assert_eq!(cur, (2, 2)); // cursor right after a full row goes to the next row let mut e = Editor::default(); e.insert("abcd"); let (rows, cur) = e.wrapped(4); assert_eq!((rows.len(), cur), (2, (1, 0))); // trailing newline is an empty row e.insert("\n"); assert_eq!(e.wrapped(4).0, ["abcd", ""]); } #[test] fn backslash_enter_continues() { let mut e = Editor::default(); e.insert("a\\"); assert!(e.continue_line()); assert_eq!(e.buf, "a\n"); assert!(!e.continue_line()); } #[test] fn edit_and_multiline_nav() { let mut e = Editor::default(); e.insert("héllo"); e.left(); e.backspace(); assert_eq!(e.buf, "hélo"); e.insert("\r\nworld"); assert_eq!(e.buf, "hél\r\nworldo".replace("\r\n", "\n")); assert_eq!(e.cursor_rc(), (1, 5)); e.up(); assert_eq!(e.cursor_rc(), (0, 3)); e.down(); assert_eq!(e.cursor_rc(), (1, 3)); e.end(); e.kill_line(); assert_eq!(e.buf, "hél\n"); e.insert("a b"); e.kill_word(); assert_eq!(e.buf, "hél\na "); } #[test] fn history_and_submit() { let mut e = Editor::default(); assert!(matches!(e.submit(), Action::None)); for s in ["a", "b"] { e.insert(s); assert!(matches!(e.submit(), Action::Submit(x) if x == s)); } e.insert("draft"); e.up(); assert_eq!(e.buf, "b"); e.up(); e.up(); assert_eq!(e.buf, "a"); e.down(); e.down(); assert_eq!(e.buf, "draft"); } #[test] fn replace_token() { let mut e = Editor::default(); e.insert("look at @mai"); e.replace(8, "@src/main.rs "); assert_eq!((e.buf.as_str(), e.cur), ("look at @src/main.rs ", 21)); } }