From f16e2aba0c624e0287440cb9a2a5f9ceae67b953 Mon Sep 17 00:00:00 2001 From: Ansho Rei Date: Thu, 27 Aug 2026 20:31:54 +0200 Subject: [PATCH] (3686dd6) Open a command prompt on the board with : and parse what is typed, and bump to 0.32.15 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The board reads. Changing anything meant quitting it and retyping an id that was already selected. So `:` opens a one line editor in the footer and the line is a worklane command, spelled exactly as the shell spells it. This is the mode and the grammar check, not the doing. Enter tokenises the line with split_line, prepends the binary's own name and hands the arguments to the same Cli definition the shell reaches, so a flag added to a command is typeable here the day it is added and no list of verbs lives on the board to go stale. A line that resolves is named and the prompt closes; a line that does not keeps the prompt open with the line intact and clap's own message, cut back to what fits a row. Running it is 53ffb94, and the notice and the `↵ check` key both say so rather than reading like a move that happened. The prompt owns the keyboard while it is open, the contract search_key and picker_key already keep, and declines ctrl-c for the same reason they do. A line that ends inside a quote never reaches clap, which is what the splitter's Unclosed state is for. --help is caught, or clap's page lands on the alternate screen the way an unsunk println! would. Co-Authored-By: Claude Opus 5 (1M context) --- AGENTS.md | 12 + Cargo.lock | 2 +- Cargo.toml | 2 +- src/main.rs | 19 +- src/tui.rs | 823 +++++++++++++++++++++++++++++++++++++++++++++++++++- 5 files changed, 853 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 3fe0bd8..17f4a17 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -351,6 +351,18 @@ and this file is for what someone changing worklane's own code needs. - Both closed footers name `/`, since the jump works with a ticket open as well: it moves the selection and the overlay follows - Out of scope on purpose, each its own ticket once the input mode exists: `n` and `N` for the next and previous match, searching the description, tags or owner, regex, and filtering the board down to matches rather than selecting one +### The Command Prompt +- **`prompt: Option` is the whole mode**, the shape `search` and `detail` use: open and content cannot disagree, and closing it leaves nothing to reset. `Prompt` carries the line, the cursor as a byte offset into it, and `refused`, which is `Search::missed` with something to say +- **`Board::prompt_key` is third in the pre-dispatch**, beside `search_key` and `picker_key` and on the same contract: while a command is being typed `q` is a letter, `d` leaves the columns alone and `tab` stays out of the project tabs, and `ctrl-c` is the one key declined. It takes no `Size`, because nothing it does measures the board — the keypress that will is 53ffb94, which redraws on what the command wrote. Only one of the two prompts can be open at once: `:` is reachable from the action arms alone, and while either has the keyboard the other's key is a character in a line +- **`esc` and `enter` are the mode's own keys and are answered in `prompt_key`; everything else belongs to the line and goes to `Prompt::key`.** That is also what keeps the borrow straight, since closing the prompt takes the whole board and editing takes only the prompt. Left, right, home, end, backspace and `ctrl-w` behave as they do in a shell, and `ctrl-w` eats the separators behind the cursor before the word behind those, so one press at the end of `mv 1b78a24 ` takes the id. There is deliberately no `tab`: suggesting the selected ticket is 00a14e7, and until then it is a key that must not reach the tabs +- **The grammar is clap's, with nothing restated.** The line is tokenised by `split_line`, the binary's own name goes in front, and the arguments go to the same `Cli` definition the shell reaches, so a flag added to a command is typeable here the day it is added. Through `Cli::command().try_get_matches_from_mut` rather than `try_parse_from`, for what the matches give back: `command_name` walks the subcommands to name what resolved (`campaign show`, not `campaign`) instead of a `match` over every variant, which would be a second list of every verb the CLI has and one that goes stale silently +- **`refused` is cleared by an edit and not by a movement.** The message is about the line, and moving the cursor does not change the line. `Prompt::key` clears it in the three arms that write to the line +- **A line that ends inside a quote never reaches clap.** That is what `Unclosed` is for: a grammar complaint about a sentence nobody finished describes the wrong thing. Enter on an empty line, or one of nothing but separators, closes the prompt with nothing said, the way `esc` does — the bare form of the CLI opens a board and there is one on the screen +- **Enter resolves the line and does not run it**, so the notice says `parsed, not run yet` rather than reading like a move that happened, and the prompt's own key is drawn as `↵ check`. Both are replaced by 53ffb94, which is the ticket that runs it; naming the key `run` here would be the fault 1b78a24 was, in the other direction +- **What a refused line shows is clap's own message with the usage block cut off**, which is also what drops the `--help` line after it. `--help` is the exception: it parses as an error of the kind that means *print this* and what it would print is a page, so it is caught and answered in a row's worth of words, or clap's help lands on the alternate screen the way an unsunk `println!` would. `--version` goes through the ordinary path, because what it prints is one line by construction. `ColorChoice::Never` on the command, so nothing that reaches the row carries an escape +- **The keys' width comes off the row before the line is windowed**, so a long command does not push them off the end; a message takes the row from the keys instead, since the reader has just been told something and `esc` and `enter` still do what they did. `prompt_window` anchors the window on the cursor's right edge, which costs the text *after* the cursor on a long line: keeping both ends needs a scroll offset in state, and the draw is where the width is known and the state is not writable +- `: command` is named in every footer state, because the key works in every one of them + ### Splitting a Typed Line - **`split_line` is the whole module, and it knows nothing about `Board`.** The command prompt reads one string and clap reads an argv, so `comment 1b78a24 the offset was never passed` has to be tokenised before anything can parse it: split on whitespace it is five arguments and `comment` takes two. A pure function over the line and the cursor is what makes every rule reachable from a unit test, and it is in a file of its own rather than in `tui.rs`, which is eleven thousand lines already - **The rules are the shell's, because that is what the prompt promises**: the line is spelled there exactly as it is spelled in the shell. Runs of whitespace separate arguments, single and double quotes group one, a backslash escapes the next character *except* inside single quotes where it is a backslash, and an explicitly empty `''` is an argument that exists and is empty — which is what `--title ""` being a usage error rather than a silent clear depends on. A leading hyphen is not special here: whether `--foo` is a flag or the text of a criterion is clap's question, and `PROSE` already answers it diff --git a/Cargo.lock b/Cargo.lock index bc40259..0d48613 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1503,7 +1503,7 @@ dependencies = [ [[package]] name = "worklane" -version = "0.32.14" +version = "0.32.15" dependencies = [ "anyhow", "assert_cmd", diff --git a/Cargo.toml b/Cargo.toml index 3be576d..148ef16 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "worklane" -version = "0.32.14" +version = "0.32.15" edition = "2024" [dependencies] diff --git a/src/main.rs b/src/main.rs index 0192767..e37882d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,8 +8,9 @@ mod completions; mod handlers; mod history; mod install; -/// Nothing in the binary splits a line yet: the prompt that will is 3686dd6, and the -/// allow goes when it lands. The tests are what drive it in the meantime. +/// The command prompt reads `split_line` and `unclosed`; `cursor_arg` and `at_new_arg` are +/// what completing an argument needs and nothing reads them yet, so the allow stays until +/// 00a14e7 and 952a9f8 land. The tests are what drive them in the meantime. #[cfg_attr(not(test), allow(dead_code))] mod split; mod tag; @@ -219,6 +220,14 @@ fn run_tui(paths: &[std::path::PathBuf], start: &std::path::Path) -> Result<()> continue; } + // And the command prompt, third, on the same contract: while a command is being + // typed `q` is a letter, `d` leaves the columns alone and `tab` stays out of the + // project tabs. No screen, because nothing it does measures the board yet. The + // rule is `Board::prompt_key`, where a test can reach it. + if board.prompt_key(key) { + continue; + } + match key.code { // One arm, because the two keys mean one thing: close what is open, and // quit when there is nothing left to close. Two arms carrying one rule @@ -262,6 +271,12 @@ fn run_tui(paths: &[std::path::PathBuf], start: &std::path::Path) -> Result<()> // at an open picker is taken by `picker_key` to open the picker's own // query, so this arm is only ever the way in to the board's prompt. KeyCode::Char('/') => board.open_search(), + // The way in to the command prompt, and the same single-shot arm `/` is: + // from the next keypress on, `prompt_key` above has the keyboard. A `:` + // typed into either open prompt is a character there and one pressed at an + // open picker is swallowed by it, so this arm is only ever the way in from + // the board itself. Free of every existing binding. + KeyCode::Char(':') => board.open_prompt(), // `y` as in yank, for the readers this board is for, and the only letter // left that a vim hand would reach for. The clipboard is handed in rather // than reached for inside `Board`, so the suite can drive both answers. diff --git a/src/tui.rs b/src/tui.rs index cd16d42..599974c 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -23,7 +23,9 @@ use ratatui::text::{Line, Span, Text}; use ratatui::widgets::{Block, Borders, Clear, Paragraph, Tabs, Wrap}; use crate::campaign::{CAMPAIGNS_DIR, CampaignIndex, Standing}; +use crate::command::Cli; use crate::history::{HistoryPart, history_parts, history_root, read_history}; +use crate::split::{Unclosed, split_line}; use crate::tag::{NO_ANNOTATION, TAGS_FILE, TagIndex}; use crate::util::*; @@ -696,6 +698,177 @@ pub struct Search { pub missed: bool, } +/// The open command prompt: the line, where the cursor is in it, and what the last enter +/// had to say about it. +/// +/// One field on `Board` rather than a buffer beside a bool, for the reason [`Search`] is +/// one: "the prompt is open" and "what is in it" cannot disagree, and closing it leaves +/// nothing to reset. +/// +/// The cursor is a byte offset into `line`, which is what `String` inserts and removes at +/// and what [`crate::split::split_line`] reads. Every key that moves it moves it by whole +/// characters, so it is never inside one. +#[derive(Debug, Default)] +pub struct Prompt { + pub line: String, + pub cursor: usize, + /// What the last enter could not do, cleared by the next edit of the line. The message + /// is about the line that was refused, so it goes the moment the line changes; moving + /// the cursor leaves it up, since the line it is about has not changed. `Search::missed` + /// is the same rule with nothing to say but "no match". + pub refused: Option, +} + +impl Prompt { + /// Every key that only edits the line or moves the cursor, which is all of them but + /// `esc` and `enter`: those two are the mode's rather than the line's, and they are + /// answered by [`Board::prompt_key`] before it gets here. + /// + /// Left, right, home, end, backspace and `ctrl-w` behave as they do in a shell. There + /// is no `tab`: suggesting the selected ticket is 00a14e7, and until then it is a key + /// that must not reach the project tabs. Every other control combination lands on the + /// last arm and does nothing, which is what stops `ctrl-d` reaching the action bound + /// to `d`. + fn key(&mut self, key: KeyEvent, control: bool) { + match key.code { + KeyCode::Left if !control => self.cursor = self.left_of(), + KeyCode::Right if !control => self.cursor = self.right_of(), + KeyCode::Home if !control => self.cursor = 0, + KeyCode::End if !control => self.cursor = self.line.len(), + // The three that change the line, so the message about what it used to say goes + // with it. Movement above deliberately does not clear it. + KeyCode::Backspace if !control => self.cut(self.left_of()), + KeyCode::Char('w') if control => self.cut(self.word_start()), + KeyCode::Char(typed) if !control => { + self.line.insert(self.cursor, typed); + self.cursor += typed.len_utf8(); + self.refused = None; + } + _ => {} + } + } + + /// The offset one character to the left of the cursor, or the cursor itself at the + /// start of the line. By characters, so a cursor never lands inside one. + fn left_of(&self) -> usize { + match self.line[..self.cursor].chars().next_back() { + Some(c) => self.cursor - c.len_utf8(), + None => self.cursor, + } + } + + /// The same one character to the right, or the cursor itself at the end. + fn right_of(&self) -> usize { + match self.line[self.cursor..].chars().next() { + Some(c) => self.cursor + c.len_utf8(), + None => self.cursor, + } + } + + /// Where the word before the cursor starts, which is what `ctrl-w` takes off: the + /// separators immediately behind the cursor, and then the run of everything that is + /// not one behind those. + /// + /// The separators first, so `ctrl-w` at the end of `mv 1b78a24 ` takes the id rather + /// than the space alone, which is what a shell does with it. + fn word_start(&self) -> usize { + let back = |at: usize| { + self.line[..at] + .chars() + .next_back() + .map(|c| (at - c.len_utf8(), c)) + }; + + let mut at = self.cursor; + while let Some((before, c)) = back(at) { + if !c.is_whitespace() { + break; + } + at = before; + } + while let Some((before, c)) = back(at) { + if c.is_whitespace() { + break; + } + at = before; + } + + at + } + + /// Take everything between `from` and the cursor off the line, and put the cursor + /// where it was taken from. Nothing to remove writes nothing. + fn cut(&mut self, from: usize) { + if from >= self.cursor { + return; + } + + self.line.replace_range(from..self.cursor, ""); + self.cursor = from; + self.refused = None; + } +} + +/// What a line that ends half typed is waiting for, or nothing when it is whole. +/// +/// The splitter reports the state rather than raising an error, and this is the sentence +/// the row carries for it. Said here rather than at the call site so the three states are +/// spelled in one place. +fn unclosed_message(unclosed: Unclosed) -> Option<&'static str> { + match unclosed { + Unclosed::Closed => None, + Unclosed::Single => Some("the line ends inside a ' quote"), + Unclosed::Double => Some("the line ends inside a \" quote"), + Unclosed::Escape => Some("the line ends on a backslash"), + } +} + +/// What clap resolved the line to, as the words a reader typed: `mv`, or `campaign show` +/// for a command inside a group. +/// +/// Off the matches rather than off a `match` on `Command`, which would be a second list of +/// every verb the CLI has — one that goes stale the day a command is added, and silently, +/// since a missing arm would only ever be seen by whoever typed that verb. `None` is the +/// bare form, which names no command at all. +fn command_name(matches: &clap::ArgMatches) -> Option { + let (name, inner) = matches.subcommand()?; + + Some(match command_name(inner) { + Some(rest) => format!("{name} {rest}"), + None => name.to_string(), + }) +} + +/// The one line the row carries for a line clap would not take. +/// +/// Clap's own message, because the grammar is clap's: a complaint written here would +/// describe a rule this file does not own. What is dropped is the usage block and the +/// `--help` line after it, which are a paragraph — the synopsis is d7e493e's, and until +/// then the row says what is wrong rather than what would have been right. +/// +/// `--help` is the exception. It parses as an error of the kind that means *print this*, +/// and what it would print is a page: caught here, or clap's help lands on the alternate +/// screen the way an unsunk `println!` would. `--version` goes through the ordinary path +/// because what it prints is one line by construction, which is exactly what fits. +fn refusal(err: &clap::Error) -> String { + if matches!( + err.kind(), + clap::error::ErrorKind::DisplayHelp + | clap::error::ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand + ) { + return "help is a page and this is a row: try it in a shell".to_string(); + } + + let rendered = err.render().to_string(); + rendered + .lines() + .take_while(|line| !line.starts_with("Usage:")) + .map(str::trim) + .filter(|line| !line.is_empty()) + .collect::>() + .join(" ") +} + /// A line the footer carries in place of the key list until the next keypress. /// /// The board otherwise says everything by drawing it, and a copy leaves nothing on the @@ -1073,6 +1246,10 @@ pub struct Board { pub offset: u16, /// The search prompt while it is open. `None` is the board reading keys as actions. pub search: Option, + /// The command prompt while it is open, on the same terms as `search`. Only one of the + /// two can be open at once: `:` is reachable from the action arms alone, and while + /// either prompt has the keyboard the other's key is a character in a line. + pub prompt: Option, /// The campaign picker while it is open, on the same terms as `search`. pub picker: Option, /// What the last action said, until the next keypress takes it away. @@ -1109,6 +1286,7 @@ impl Board { detail: None, offset: 0, search: None, + prompt: None, picker: None, notice: None, visibility: Visibility::default(), @@ -1920,6 +2098,113 @@ impl Board { } } + /// Open the command prompt on an empty line. + /// + /// Empty rather than the last line kept, for the reason `open_search` opens empty: the + /// command that was typed has been dealt with, and reopening on it would make `:` and + /// enter repeat something nobody asked for. Recalling a line is `a9bd6f0`. + pub fn open_prompt(&mut self) { + self.prompt = Some(Prompt::default()); + } + + /// Feed a keypress to the open command prompt, and say whether it was taken. + /// + /// The same contract as `search_key` and `picker_key`, and it runs beside them for the + /// same reason: the prompt owns the keyboard while it is open, so `q` typed into a + /// command has to be a letter, `d` must not rotate the columns and `tab` must not + /// change project. `ctrl-c` is the one key it declines, because a terminal application + /// always honours it and a prompt that ate it would leave no way off the board. + /// + /// `esc` and `enter` are the mode's own two keys and are answered here; everything else + /// belongs to the line and goes to `Prompt::key`. That split is also what keeps the + /// borrow straight: closing the prompt takes the whole board, editing takes the prompt. + /// + /// No screen: nothing here measures the board. The keypress that will is 53ffb94, which + /// redraws on what the command wrote. + pub fn prompt_key(&mut self, key: KeyEvent) -> bool { + if self.prompt.is_none() { + return false; + } + + let control = key.modifiers.contains(KeyModifiers::CONTROL); + if control && key.code == KeyCode::Char('c') { + return false; + } + + match key.code { + KeyCode::Esc if !control => self.prompt = None, + KeyCode::Enter if !control => self.submit(), + _ => { + if let Some(prompt) = &mut self.prompt { + prompt.key(key, control); + } + } + } + + true + } + + /// What enter does with the line: name the command it resolved to, or say why it did + /// not resolve to one. + /// + /// The grammar is clap's, with nothing restated. The line is tokenised the way a shell + /// tokenises one, the binary's own name is put in front of the arguments, and the + /// result goes to the same `Cli` definition the shell reaches: a flag added to a + /// command is typeable here the day it is added, and no list of verbs lives on the + /// board to go stale. + /// + /// A line that resolves closes the prompt and says what it resolved to, in the footer's + /// one channel for saying something in words. **It does not run it** — running is + /// 53ffb94 — so the notice says so rather than reading like a move that happened. + /// + /// A line that does not resolve keeps the prompt open with the line and the cursor + /// exactly as they were, and puts the message on the row, so a typo is corrected in + /// place instead of retyped from `:`. That is `Search`'s hit-closes-miss-stays rule, + /// and the reason both are true of one field. + fn submit(&mut self) { + let Some(prompt) = &self.prompt else { return }; + + // Before clap sees anything, because a line ending inside a quote is not a line + // that failed to parse: it is one the reader has not finished typing, and handing + // its half-open argument to clap would report a grammar fault about a sentence + // nobody finished. + let split = split_line(&prompt.line, prompt.cursor); + if let Some(open) = unclosed_message(split.unclosed) { + self.refuse(open.to_string()); + return; + } + + // Enter on an empty line closes the prompt and leaves the board as it was, the way + // esc does. A line of nothing but separators is the same line: it names no command, + // and the bare form of the CLI opens a board, which is already on the screen. + if split.args.is_empty() { + self.prompt = None; + return; + } + + let mut command = ::command().color(clap::ColorChoice::Never); + let argv = std::iter::once(command.get_name().to_string()).chain(split.args); + + match command.try_get_matches_from_mut(argv) { + // No subcommand is the bare form, which opens a board: there is one on the + // screen, so there is nothing to name and nothing to do but close. + Ok(matches) => { + self.prompt = None; + if let Some(named) = command_name(&matches) { + self.notice = Some(Notice::done(format!("{named}: parsed, not run yet"))); + } + } + Err(err) => self.refuse(refusal(&err)), + } + } + + /// Keep the prompt open, with the line untouched, carrying what enter had to say. + fn refuse(&mut self, message: String) { + if let Some(prompt) = &mut self.prompt { + prompt.refused = Some(message); + } + } + /// The string the copy key puts on the clipboard: the selected card's short id. /// /// A method here rather than a line inside the arm that copies, so what gets copied @@ -3734,6 +4019,14 @@ fn key_hints(hints: &[(&str, &str)]) -> Vec> { } fn draw_footer(frame: &mut Frame, board: &Board, area: Rect) { + // The command prompt takes the whole row on the same terms as the search prompt below, + // and is asked first: an input cannot be covered, and it is the newest of the three + // things that can hold the row. Only one of the two prompts can be open at a time. + if let Some(prompt) = &board.prompt { + draw_prompt(frame, prompt, area); + return; + } + // The prompt takes the whole row while it is open. The footer is one line and // already says what the state allows, and with every key going into the buffer the // key list it replaces describes nothing that currently works. @@ -3831,6 +4124,7 @@ fn draw_footer(frame: &mut Frame, board: &Board, area: Rect) { ("←→↑↓", "select"), ("pgup/pgdn", "scroll"), ("/", "search"), + (":", "command"), ("y", "copy id"), ("↵/q", "close"), ]), @@ -3840,13 +4134,19 @@ fn draw_footer(frame: &mut Frame, board: &Board, area: Rect) { ("↵", height), ("pgup/pgdn", "scroll"), ("/", "search"), + (":", "command"), ]); if let Some(copied) = copied { hints.push(("y", copied)); } } (false, Focus::Cards) => { - hints.extend([("←→", "column"), ("↑↓", "card"), ("/", "search")]); + hints.extend([ + ("←→", "column"), + ("↑↓", "card"), + ("/", "search"), + (":", "command"), + ]); hints.extend_from_slice(filter); hints.extend([("y", "copy id"), ("↵", "detail")]); } @@ -3907,6 +4207,85 @@ fn draw_search(frame: &mut Frame, search: &Search, area: Rect) { frame.set_cursor_position((area.x + at, area.y)); } +/// What the row spends on the command prompt before the line starts: its own opening space +/// and the key that opened it, drawn where a search draws its `/`. +const PROMPT_OPENING: &str = " :"; + +/// The command prompt, in place of the key list, and the line windowed to what is left of +/// the row. +/// +/// The keys are drawn the way `draw_search` draws its two, and their width is taken off the +/// row *before* the line is windowed, so they keep their place rather than being pushed off +/// the end by a long command. A message takes the row from them instead: the reader has +/// just been told something and that is the thing to read, while `esc` and `enter` still do +/// what they did. It is brightred beside the line it is about, the one thing on the row +/// that is neither a key nor what was typed, which is where `no match` sits. +/// +/// `check` and not `run`: enter resolves the line and names it, and running it is 53ffb94. +/// A row naming a key by what it does not do yet is the fault 1b78a24 was, in the other +/// direction. +fn draw_prompt(frame: &mut Frame, prompt: &Prompt, area: Rect) { + let keys = key_hints(&[("↵", "check"), ("esc", "cancel")]); + let spent: usize = PROMPT_OPENING.chars().count() + + KEY_GAP.chars().count() + + keys + .iter() + .map(|span| span.content.chars().count()) + .sum::(); + + // At least one cell, so a terminal too narrow for the keys still draws a cursor to type + // at rather than nothing at all. + let room = (area.width as usize).saturating_sub(spent).max(1); + let (visible, at) = prompt_window(&prompt.line, prompt.cursor, room); + + let mut spans = vec![Span::raw(format!("{PROMPT_OPENING}{visible}"))]; + match &prompt.refused { + Some(message) => spans.push(Span::styled( + format!("{KEY_GAP}{message}"), + Style::default().fg(Color::BrightRed.into()), + )), + None => { + spans.push(Span::raw(KEY_GAP)); + spans.extend(keys); + } + } + + frame.render_widget(Paragraph::new(Line::from(spans)), area); + + // Held on the row, the way the search prompt holds its own: a line longer than the + // terminal leaves the cursor on the last cell rather than off the frame. + let column = (PROMPT_OPENING.chars().count() + at) as u16; + frame.set_cursor_position((area.x + column.min(area.width.saturating_sub(1)), area.y)); +} + +/// The part of `line` a field `room` cells wide shows with the cursor at `cursor`, and the +/// column the cursor lands on inside it. +/// +/// The window is anchored on the cursor's right edge, so a line longer than the row scrolls +/// as it is typed instead of being cut off at the end of the field, and scrolls back as the +/// cursor moves left. What it costs is the text *after* the cursor on a long line, which is +/// off the window until the cursor reaches it. A window that kept both ends needs a scroll +/// offset held in state, and the draw is where the width is known and the state is not +/// writable, so that offset would have to be maintained by every key that moves the cursor +/// against a width the keypress cannot see. +/// +/// Counted in characters, which is what the rest of this row is measured in. The cursor is +/// counted rather than sliced, so an offset that is somehow not on a character boundary +/// gives a window rather than a panic on the board. +fn prompt_window(line: &str, cursor: usize, room: usize) -> (String, usize) { + let before = line + .char_indices() + .take_while(|(offset, _)| *offset < cursor) + .count(); + + // One cell of the field is the cursor's own, so a line whose head fills the row keeps + // the cursor on it rather than one cell past its end. + let start = before.saturating_sub(room.saturating_sub(1)); + let visible = line.chars().skip(start).take(room).collect(); + + (visible, before - start) +} + /// The picker's footer: its query while one is open, and the keys it answers to otherwise. /// /// The same division `draw_search` makes, and the same reason for it: while every printable @@ -6940,6 +7319,448 @@ approach"; ); } + // ------------------------------------------------------------ the command prompt -- + + /// A keypress with control held, which is how `ctrl-w` and `ctrl-c` arrive. + fn ctrl(c: char) -> KeyEvent { + KeyEvent::new(KeyCode::Char(c), KeyModifiers::CONTROL) + } + + /// Type a whole line into an open command prompt, one key at a time, the way it arrives. + fn type_line(board: &mut Board, line: &str) { + for c in line.chars() { + assert!(board.prompt_key(letter(c)), "'{c}' was not taken"); + } + } + + fn prompt_line(board: &Board) -> Option<&str> { + board.prompt.as_ref().map(|prompt| prompt.line.as_str()) + } + + /// What the last enter had to say, or nothing. + fn refused(board: &Board) -> Option<&str> { + board + .prompt + .as_ref() + .and_then(|prompt| prompt.refused.as_deref()) + } + + /// Press enter on the open prompt, which is the whole of what this ticket does. + fn submit(board: &mut Board) { + assert!(board.prompt_key(typed(KeyCode::Enter)), "enter was not taken"); + } + + /// The prompt takes the row, names its own two keys, and the board is still behind it. + #[test] + fn the_command_prompt_replaces_the_footer_and_draws_the_line_and_its_cursor() { + let dir = searchable(); + let mut board = one_board(&dir); + board.open_prompt(); + + let screen = render(&board, SCREEN.width, SCREEN.height); + let row = screen.last().expect("no rows rendered"); + + assert!(row.contains("↵ check"), "{row}"); + assert!(row.contains("esc cancel"), "{row}"); + assert!(!row.contains("quit"), "the key list survived the prompt:\n{row}"); + assert!( + screen.join("\n").contains("Alpha first"), + "the board went away behind the prompt" + ); + + type_line(&mut board, "mv 1111111"); + let row = footer(&board, SCREEN.width, SCREEN.height); + assert!(row.contains(" :mv 1111111"), "the line is not drawn: {row}"); + + let mut terminal = Terminal::new(TestBackend::new(SCREEN.width, SCREEN.height)).unwrap(); + terminal.draw(|frame| draw(frame, &board)).unwrap(); + let at = terminal.get_cursor_position().unwrap(); + + // The leading space, the `:`, and the ten characters typed. + assert_eq!(at.x, 12, "the cursor is not after the line"); + assert_eq!(at.y, SCREEN.height - 1, "the cursor left the prompt row"); + } + + /// The line is edited where the cursor is, not at its end, which is the difference + /// between a command line and the search prompt's append-only query. + #[test] + fn the_line_is_edited_at_a_cursor_the_way_a_shell_edits_one() { + let dir = searchable(); + let mut board = one_board(&dir); + board.open_prompt(); + type_line(&mut board, "mv 1111111"); + + board.prompt_key(typed(KeyCode::Home)); + type_line(&mut board, "x"); + assert_eq!(prompt_line(&board), Some("xmv 1111111"), "home did not reach the front"); + + // Backspace takes the character before the cursor, not the last one on the line. + board.prompt_key(typed(KeyCode::Backspace)); + assert_eq!(prompt_line(&board), Some("mv 1111111")); + + board.prompt_key(typed(KeyCode::Right)); + board.prompt_key(typed(KeyCode::Right)); + type_line(&mut board, "!"); + assert_eq!(prompt_line(&board), Some("mv! 1111111")); + + board.prompt_key(typed(KeyCode::Left)); + board.prompt_key(typed(KeyCode::Backspace)); + assert_eq!(prompt_line(&board), Some("m! 1111111")); + + // `ctrl-w` takes the word before the cursor, and the separators behind the cursor + // with it, so a second press takes the word before those rather than the space. + board.prompt_key(typed(KeyCode::End)); + board.prompt_key(ctrl('w')); + assert_eq!(prompt_line(&board), Some("m! ")); + board.prompt_key(ctrl('w')); + assert_eq!(prompt_line(&board), Some("")); + + // Nothing to take is nothing done, at either end. + board.prompt_key(typed(KeyCode::Backspace)); + board.prompt_key(ctrl('w')); + board.prompt_key(typed(KeyCode::Left)); + assert_eq!(prompt_line(&board), Some("")); + + // A cursor counted in bytes still moves by whole characters, so a backspace over a + // multi-byte one takes the character rather than splitting it. + type_line(&mut board, "comment é"); + board.prompt_key(typed(KeyCode::Backspace)); + assert_eq!(prompt_line(&board), Some("comment ")); + } + + /// The whole point of an input mode. Every one of these keys does something on the + /// board, and none of it may happen while a command is being typed. + #[test] + fn the_command_prompt_swallows_the_keys_that_are_bound_to_actions() { + let first = searchable(); + let second = board_dir(); + let mut board = boards(&[("alpha", &first), ("beta", &second)]); + + let before = selected_title(&board); + board.open_prompt(); + + for key in [ + letter('d'), + letter('q'), + letter('j'), + letter('h'), + typed(KeyCode::Up), + typed(KeyCode::Down), + typed(KeyCode::Left), + typed(KeyCode::Right), + typed(KeyCode::Tab), + typed(KeyCode::BackTab), + typed(KeyCode::PageDown), + ] { + assert!(board.prompt_key(key), "{key:?} was not taken"); + } + + assert!(!board.should_quit, "typing 'q' quit the board"); + assert_eq!(board.visibility, Visibility::Neither, "typing 'd' rotated the columns"); + assert_eq!(selected_title(&board), before, "an arrow moved the selection"); + assert_eq!(board.tab, 0, "tab changed project from under the prompt"); + // The letters landed in the line; the keys that are not characters did not. + assert_eq!(prompt_line(&board), Some("dqjh")); + } + + /// `ctrl-c` is the exception, since a terminal application always honours it. Every + /// other control combination is swallowed and does nothing but the one that is bound. + #[test] + fn the_command_prompt_declines_ctrl_c_and_eats_every_other_control_key() { + let dir = searchable(); + let mut board = one_board(&dir); + board.open_prompt(); + + assert!( + !board.prompt_key(ctrl('c')), + "the prompt ate ctrl-c and left no way off the board" + ); + + assert!(board.prompt_key(ctrl('d')), "ctrl-d fell through to the 'd' arm"); + assert_eq!(prompt_line(&board), Some(""), "a control key typed its letter"); + } + + /// Both ways of leaving with nothing done, and neither touches anything behind the row. + #[test] + fn esc_and_enter_on_an_empty_line_leave_the_board_as_it_was() { + let dir = searchable(); + let mut board = one_board(&dir); + board.toggle_detail(); + + let before = selected_title(&board); + board.open_prompt(); + type_line(&mut board, "mv 1111111"); + + assert!(board.prompt_key(typed(KeyCode::Esc)), "esc was not taken"); + assert!(board.prompt.is_none(), "the prompt stayed open"); + assert!(board.detail.is_some(), "esc reached the overlay arm"); + assert!(!board.should_quit, "esc reached the quit arm"); + assert_eq!(selected_title(&board), before, "the selection moved on a cancel"); + assert!(board.notice.is_none(), "a cancel said something in the footer"); + + // And the next esc is the overlay's again. + assert!(!board.prompt_key(typed(KeyCode::Esc))); + + board.open_prompt(); + submit(&mut board); + assert!(board.prompt.is_none(), "enter on an empty line left the prompt open"); + assert!(board.notice.is_none(), "an empty line named a command"); + + // A line of nothing but separators names no command either. + board.open_prompt(); + type_line(&mut board, " "); + submit(&mut board); + assert!(board.prompt.is_none(), "a line of spaces left the prompt open"); + assert!(board.notice.is_none(), "a line of spaces named a command"); + } + + /// A line clap takes closes the prompt and is named, in the footer's one channel for + /// saying something in words. It is *not* run here, and the notice has to say so. + #[test] + fn enter_names_the_command_the_line_resolved_to_and_closes_the_prompt() { + let dir = searchable(); + let mut board = one_board(&dir); + + board.open_prompt(); + type_line(&mut board, "mv 1111111 --status committed"); + submit(&mut board); + + assert!(board.prompt.is_none(), "the prompt stayed open on a line clap took"); + let row = footer(&board, SCREEN.width, SCREEN.height); + assert!(row.contains("mv"), "the command was not named: {row}"); + assert!(row.contains("not run"), "the notice reads like the move happened: {row}"); + + // A command inside a group is named by the words that reach it, off the matches + // rather than a list of verbs kept here. + board.open_prompt(); + type_line(&mut board, "campaign show v1"); + submit(&mut board); + let row = footer(&board, SCREEN.width, SCREEN.height); + assert!(row.contains("campaign show"), "the group was not named: {row}"); + + // And the reason the line is tokenised at all: `comment` takes two arguments, so a + // body split on whitespace would be five and clap would refuse it. + board.open_prompt(); + type_line(&mut board, "comment 1111111 \"the offset was never passed\""); + submit(&mut board); + assert!(board.prompt.is_none(), "a quoted body was refused: {:?}", refused(&board)); + } + + /// A line clap will not take keeps the prompt open with the line intact, so a typo is + /// corrected in place instead of retyped from `:`. The message is clap's own, cut back + /// to the part that fits a row. + #[test] + fn a_refused_line_keeps_the_prompt_open_and_shows_clap_without_the_usage_block() { + let dir = searchable(); + let mut board = one_board(&dir); + + board.open_prompt(); + type_line(&mut board, "mv"); + submit(&mut board); + + assert_eq!(prompt_line(&board), Some("mv"), "the line was not kept"); + let message = refused(&board).expect("nothing was said about a line clap refused"); + assert!(message.contains("required"), "not clap's own message: {message}"); + assert!(!message.contains("Usage:"), "the usage block reached the row: {message}"); + assert!(!message.contains('\n'), "the message is a paragraph, not a row: {message}"); + assert!(!message.contains('\x1b'), "clap coloured the message: {message:?}"); + + let row = footer(&board, SCREEN.width, SCREEN.height); + assert!(row.contains(" :mv"), "the line left the row: {row}"); + assert!(row.contains("required"), "the message is not on the row: {row}"); + assert!( + !row.contains("esc cancel"), + "the keys and the message shared the row: {row}" + ); + + // The message is about the line, so moving the cursor keeps it and an edit takes it. + board.prompt_key(typed(KeyCode::Left)); + assert!( + refused(&board).is_some(), + "moving the cursor cleared a message about a line that had not changed" + ); + type_line(&mut board, "x"); + assert!(refused(&board).is_none(), "the message outlived the line it was about"); + } + + /// `--help` parses as an error of the kind that means *print this*, and what it would + /// print is a page: uncaught, clap's help lands on the alternate screen the way an + /// unsunk `println!` would. `--version` is one line by construction, so it says itself. + #[test] + fn help_and_version_put_nothing_over_the_board() { + let dir = searchable(); + let mut board = one_board(&dir); + + for line in ["--help", "-h", "mv --help"] { + board.open_prompt(); + type_line(&mut board, line); + submit(&mut board); + + let message = refused(&board).unwrap_or_else(|| panic!("`{line}` said nothing")); + assert!(!message.contains('\n'), "`{line}` put a page on the row: {message}"); + assert!(message.contains("help"), "`{line}` said something else: {message}"); + + let screen = render(&board, SCREEN.width, SCREEN.height); + assert!( + screen.join("\n").contains("Alpha first"), + "`{line}` printed over the board" + ); + board.prompt_key(typed(KeyCode::Esc)); + } + + board.open_prompt(); + type_line(&mut board, "--version"); + submit(&mut board); + let message = refused(&board).expect("`--version` said nothing"); + assert!( + message.contains(env!("CARGO_PKG_VERSION")), + "`--version` did not say the version: {message}" + ); + assert!(!message.contains('\n'), "the version is not one line: {message}"); + } + + /// The splitter reports a half-typed line as a state rather than an error, and this is + /// what the prompt does with it: nothing goes to clap, because a grammar complaint about + /// a sentence nobody finished is a complaint about the wrong thing. + #[test] + fn a_line_that_ends_inside_a_quote_is_never_handed_to_clap() { + let dir = searchable(); + let mut board = one_board(&dir); + + board.open_prompt(); + type_line(&mut board, "comment 1111111 \"the offset"); + submit(&mut board); + + assert_eq!( + prompt_line(&board), + Some("comment 1111111 \"the offset"), + "the line was not kept" + ); + let message = refused(&board).expect("nothing was said about an open quote"); + assert!(message.contains("quote"), "{message}"); + + // Closing it makes the same line a command. + type_line(&mut board, "\""); + submit(&mut board); + assert!( + board.prompt.is_none(), + "a closed quote was still refused: {:?}", + refused(&board) + ); + } + + /// A line longer than the row scrolls under the cursor instead of being cut off at the + /// end of the field, and scrolls back as the cursor moves left. + #[test] + fn a_line_longer_than_the_row_scrolls_with_the_cursor() { + // The window itself, which is where the rule lives. + assert_eq!(prompt_window("mv", 2, 10), ("mv".to_string(), 2)); + assert_eq!(prompt_window("", 0, 10), (String::new(), 0)); + assert_eq!(prompt_window("abcdefghij", 10, 5), ("ghij".to_string(), 4)); + assert_eq!(prompt_window("abcdefghij", 0, 5), ("abcde".to_string(), 0)); + assert_eq!(prompt_window("abcdefghij", 7, 5), ("defgh".to_string(), 4)); + // One cell wide is still a cursor to type at rather than a panic. + assert_eq!(prompt_window("abc", 3, 1), (String::new(), 0)); + + let dir = searchable(); + let mut board = one_board(&dir); + board.open_prompt(); + type_line(&mut board, &format!("mv {}", "a".repeat(200))); + + let row = footer(&board, SCREEN.width, SCREEN.height); + assert!(!row.contains(":mv"), "the head of the line held the row: {row}"); + assert!(row.contains("esc cancel"), "a long line pushed the keys off: {row}"); + + let mut terminal = Terminal::new(TestBackend::new(SCREEN.width, SCREEN.height)).unwrap(); + terminal.draw(|frame| draw(frame, &board)).unwrap(); + assert!( + terminal.get_cursor_position().unwrap().x < SCREEN.width, + "the cursor left the frame" + ); + + // Home takes the window back to the front of the line. + board.prompt_key(typed(KeyCode::Home)); + let row = footer(&board, SCREEN.width, SCREEN.height); + assert!( + row.contains(" :mv aaa"), + "the window did not follow the cursor back: {row}" + ); + } + + /// `:` is the way in, and only from the action arms: typed into either open prompt it is + /// an ordinary character, and pressed at an open picker it belongs to the picker. + #[test] + fn a_colon_typed_into_the_search_or_the_picker_opens_nothing() { + let dir = searchable(); + // A campaign to pick, since an empty picker says so rather than opening. Its own + // uuid, not one of the tickets': nothing here resolves either, and a shared prefix + // in a fixture reads as a claim that it matters. + write_campaign( + &dir, + "55555555-0000-4000-8000-000000000000", + "First public release", + "v1", + "For a public tag.", + ); + let mut board = one_board(&dir); + + board.open_search(); + assert!(board.search_key(letter(':'), SCREEN), "':' was not taken by the search"); + assert!(board.prompt.is_none(), "the search prompt opened a command prompt"); + assert_eq!(board.search.as_ref().map(|search| search.query.as_str()), Some(":")); + board.search_key(typed(KeyCode::Esc), SCREEN); + + board.open_picker(PickerKind::Campaign, SCREEN); + assert!(board.picker_key(letter(':'), SCREEN), "':' was not taken by the picker"); + assert!(board.prompt.is_none(), "the picker opened a command prompt"); + assert!(board.picker.is_some(), "':' closed the picker"); + + // And inside the picker's own query it is a character like any other. + board.picker_key(letter('/'), SCREEN); + board.picker_key(letter(':'), SCREEN); + assert_eq!( + board + .picker + .as_ref() + .and_then(|picker| picker.query.clone()) + .as_deref(), + Some(":"), + ); + assert!(board.prompt.is_none(), "the picker's query opened a command prompt"); + } + + /// The row names the keys that work, and `:` works in every state the board is in. + #[test] + fn every_footer_names_the_command_key() { + let dir = searchable(); + let mut board = one_board(&dir); + + assert!(footer(&board, 120, 20).contains(": command"), "the board's own footer"); + board.toggle_detail(); + assert!(footer(&board, 120, 20).contains(": command"), "the modal footer"); + } + + /// The prompt has to be offered every key before the action arms, and `:` has to be the + /// way in from the board itself. Neither is reachable from a test, so the dispatch is + /// read as text, the way the search prompt's own contract is. + #[test] + fn the_dispatch_opens_the_command_prompt_and_gives_it_the_keyboard_first() { + let source = include_str!("main.rs") + .split_whitespace() + .collect::>() + .join(" "); + + assert!( + source.contains("if board.prompt_key(key) { continue; }"), + "the prompt has to be offered every key before the action arms, or typing \ + 'd' into a command toggles the done column" + ); + assert!( + source.contains("KeyCode::Char(':') => board.open_prompt(),"), + "`:` has to open the prompt from the action arms" + ); + } + // ------------------------------------------------------------------ the copy key -- /// A sink that records what it was handed, standing in for the clipboard.