From 3ad57e8a3af6c3ddc77bf249d56725c60df47019 Mon Sep 17 00:00:00 2001 From: Felipe Coury Date: Sat, 14 Nov 2026 01:20:23 -0300 Subject: [PATCH] feat: add single-line command and field editing --- .github/workflows/ci.yml | 1 + scripts/command_line_reference.lua | 58 +++++++ src/command_line.rs | 239 +++++++++++++++++++++++++++++ src/lib.rs | 4 + tests/command_line.json | 16 ++ tests/command_line.rs | 70 +++++++++ 6 files changed, 388 insertions(+) create mode 100644 scripts/command_line_reference.lua create mode 100644 src/command_line.rs create mode 100644 tests/command_line.json create mode 100644 tests/command_line.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 686952c..b562707 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -37,4 +37,5 @@ jobs: curl --fail --location --output "$RUNNER_TEMP/nvim.tar.gz" https://github.com/neovim/neovim/releases/download/v0.12.1/nvim-linux-x86_64.tar.gz tar -xzf "$RUNNER_TEMP/nvim.tar.gz" -C "$RUNNER_TEMP" python3 scripts/conformance.py --nvim "$RUNNER_TEMP/nvim-linux-x86_64/bin/nvim" + NVIM_LOG_FILE="$RUNNER_TEMP/nvim.log" "$RUNNER_TEMP/nvim-linux-x86_64/bin/nvim" --headless -u NONE -i NONE -n -l scripts/command_line_reference.lua - run: python3 scripts/check_package.py diff --git a/scripts/command_line_reference.lua b/scripts/command_line_reference.lua new file mode 100644 index 0000000..8282f84 --- /dev/null +++ b/scripts/command_line_reference.lua @@ -0,0 +1,58 @@ +-- Run with Neovim 0.12.1 from the repository root or pass the fixture path. +assert(vim.version().major == 0 and vim.version().minor == 12 and vim.version().patch == 1) +local path = arg[1] or 'tests/command_line.json' +local cases = vim.json.decode(table.concat(vim.fn.readfile(path), '\n')) +local observed +local function observe() + observed = { text = vim.fn.getcmdline(), caret = vim.fn.getcmdpos() - 1, kind = vim.fn.getcmdtype() } + return '' +end +vim.keymap.set('c', '', observe, { expr = true }) + +local prefixes = { Ex = ':', SearchForward = '/', SearchBackward = '?', Field = '@' } +local keys = { + Left = '', Backspace = '', Delete = '', Enter = '', + Escape = '', ['Ctrl-u'] = '', ['Ctrl-w'] = '', +} +local function feed(s, flags) + vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes(s, true, false, true), flags, false) +end +for _, case in ipairs(cases) do + observed = nil + local input, paste = '', nil + for _, k in ipairs(case.keys) do + if k:sub(1, 6) == 'Paste:' then + paste = k:sub(7) + else + input = input .. (keys[k] or k) + end + end + if case.kind == 'Field' then + feed(input .. (case.text and '' or ''), 't') + local accepted = vim.fn.input({ prompt = 'Field: ', default = case.initial or '', cancelreturn = 'cancelled' }) + if not case.text then + assert(accepted == case.outcome, vim.inspect(case)) + end + elseif paste then + vim.keymap.set('c', '', function() + vim.schedule(function() + vim.api.nvim_paste(paste, true, -1) + feed('', 't') + end) + return '' + end, { expr = true }) + -- input() blocks on command-line input, so scheduled paste runs in that mode. + feed(input .. '', 't') + vim.fn.input('Paste: ') + elseif case.text then + feed(prefixes[case.kind] .. input .. '', 'xt') + else + feed(prefixes[case.kind] .. input, 'xt') + assert(vim.fn.getcmdtype() == '', vim.inspect(case)) + end + if case.text then + assert(vim.deep_equal(observed, { text = case.text, caret = case.caret, kind = paste and '@' or prefixes[case.kind] }), + vim.inspect({ case = case, observed = observed })) + end +end +print(('%d command-line cases match Neovim'):format(#cases)) diff --git a/src/command_line.rs b/src/command_line.rs new file mode 100644 index 0000000..0763f7b --- /dev/null +++ b/src/command_line.rs @@ -0,0 +1,239 @@ +//! Edit a one-line prompt with Neovim's Command-line bindings. + +use crate::{ByteOffset, Key, TextSource}; +use unicode_segmentation::UnicodeSegmentation; + +/// The purpose of a command-line draft. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum PromptKind { + /// An Ex command opened with `:`. + #[default] + Ex, + /// A forward search opened with `/`. + SearchForward, + /// A backward search opened with `?`. + SearchBackward, + /// A general input field. Backspace on an empty draft keeps it open. + Field, +} + +/// Direction of a history or completion request. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PromptDirection { + /// Older history or the previous completion. + Previous, + /// Newer history or the next completion. + Next, +} + +/// The result of dispatching a key to a prompt. +#[derive(Debug, PartialEq, Eq)] +pub enum PromptOutcome { + /// The text changed. Hosts can refresh dependent previews. + Edited, + /// Only the insertion point changed. + Moved, + /// The key was handled without changing the draft. + Consumed, + /// The host should navigate its history using the current draft and caret. + History(PromptDirection), + /// The host should navigate its completion candidates. + Complete(PromptDirection), + /// The user accepted this exact draft, which may be empty. + Accepted(String), + /// The user cancelled the prompt. + Cancelled, + /// The host may handle the key. + Unhandled, +} + +/// A draft or insertion point violates the single-line editor's invariants. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct InvalidPromptDraft; + +impl std::fmt::Display for InvalidPromptDraft { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("expected one line and a caret on a UTF-8 grapheme boundary") + } +} + +impl std::error::Error for InvalidPromptDraft {} + +/// An owned, single-line draft with a UTF-8 byte caret. +/// +/// The host renders the prompt prefix separately and handles history, completion, +/// acceptance and cancellation. Use a new instance when opening another prompt. +#[derive(Clone, Default)] +pub struct CommandLine { + kind: PromptKind, + text: String, + caret: usize, + closed: bool, + skip_operand: bool, +} + +impl std::fmt::Debug for CommandLine { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CommandLine") + .field("kind", &self.kind) + .finish_non_exhaustive() + } +} + +impl CommandLine { + /// Create an empty draft for the given prompt. + pub fn empty(kind: PromptKind) -> Self { + Self { + kind, + ..Self::default() + } + } + + /// Open a draft with the caret at the end. + /// + /// # Errors + /// + /// Returns an error if the text contains a line break. + pub fn new(kind: PromptKind, text: impl Into) -> Result { + let mut line = Self::empty(kind); + let text = text.into(); + let end = ByteOffset(text.len()); + line.replace(text, end)?; + Ok(line) + } + + /// Return the editable text, excluding any prefix or label. + pub fn text(&self) -> &str { + &self.text + } + + /// Return the zero-based UTF-8 byte offset of the insertion point. + pub fn caret(&self) -> ByteOffset { + ByteOffset(self.caret) + } + + /// Replace the active draft, for example after recalling history. + /// + /// For asynchronous replies the caller should check that the same prompt, + /// draft and caret are still active before calling this method. + /// + /// # Errors + /// + /// Rejects closed prompts, line breaks and caret positions inside graphemes. + pub fn replace(&mut self, text: String, caret: ByteOffset) -> Result<(), InvalidPromptDraft> { + if self.closed + || text.contains(['\r', '\n']) + || !(caret.0 == text.len() + || text.grapheme_indices(true).any(|(byte, _)| byte == caret.0)) + { + return Err(InvalidPromptDraft); + } + self.text = text; + self.caret = caret.0; + self.skip_operand = false; + Ok(()) + } + + /// Dispatch one normalized key. A text batch inserts at most its first line. + /// + /// Accept and cancel close the prompt. Further keys are unhandled. + pub fn handle(&mut self, key: Key) -> PromptOutcome { + use PromptOutcome::{Accepted, Cancelled, Complete, Consumed, History, Unhandled}; + + if self.closed { + return Unhandled; + } + if std::mem::take(&mut self.skip_operand) { + return Consumed; + } + let previous = self.text.as_str().prev_grapheme(self.caret); + let next = self.text.as_str().next_grapheme(self.caret); + match key { + Key::Char(ch) if !ch.is_control() => { + self.edit(self.caret, self.caret, ch.encode_utf8(&mut [0; 4])) + } + Key::Text(text) => { + let first = text.split(['\r', '\n']).next().unwrap_or_default(); + self.edit(self.caret, self.caret, first) + } + Key::Left => self.move_to(previous), + Key::Right => self.move_to(next), + Key::Home | Key::Ctrl('b') => self.move_to(0), + Key::End | Key::Ctrl('e') => self.move_to(self.text.len()), + Key::Backspace | Key::Ctrl('h') + if self.text.is_empty() && self.kind != PromptKind::Field => + { + self.closed = true; + Cancelled + } + Key::Backspace | Key::Ctrl('h') => self.edit(previous, self.caret, ""), + Key::Delete if self.caret == self.text.len() => self.edit(previous, self.caret, ""), + Key::Delete => self.edit(self.caret, next, ""), + Key::Ctrl('u') => self.edit(0, self.caret, ""), + Key::Ctrl('w') => self.edit(self.previous_word(), self.caret, ""), + Key::Ctrl('v' | 'q' | 'r') => { + self.skip_operand = true; + Consumed + } + Key::Enter | Key::Ctrl('j' | 'm') => { + self.closed = true; + Accepted(self.text.clone()) + } + Key::Escape | Key::Ctrl('c' | '[') => { + self.closed = true; + self.caret = 0; + self.text.clear(); + Cancelled + } + Key::Up => History(PromptDirection::Previous), + Key::Down => History(PromptDirection::Next), + Key::Tab => Complete(PromptDirection::Next), + Key::Named(name) if name == "BackTab" => Complete(PromptDirection::Previous), + _ => Unhandled, + } + } + + fn move_to(&mut self, caret: usize) -> PromptOutcome { + if self.caret == caret { + return PromptOutcome::Consumed; + } + self.caret = caret; + PromptOutcome::Moved + } + + fn edit(&mut self, start: usize, end: usize, replacement: &str) -> PromptOutcome { + if start == end && replacement.is_empty() { + return PromptOutcome::Consumed; + } + self.text.replace_range(start..end, replacement); + let end = start + replacement.len(); + // Inserting or removing text can join clusters on either side of the edit. + self.caret = self + .text + .grapheme_indices(true) + .find_map(|(byte, _)| (byte >= end).then_some(byte)) + .unwrap_or(self.text.len()); + PromptOutcome::Edited + } + + fn previous_word(&self) -> usize { + let mut graphemes = self.text[..self.caret].grapheme_indices(true).rev(); + let class = |grapheme: &str| { + let first = grapheme.chars().next().expect("nonempty grapheme"); + if first.is_whitespace() { + 0 + } else if first.is_alphanumeric() || first == '_' { + 1 + } else { + 2 + } + }; + let Some((start, first)) = graphemes.find(|(_, g)| class(g) != 0) else { + return 0; + }; + graphemes + .take_while(|(_, g)| class(g) == class(first)) + .last() + .map_or(start, |(byte, _)| byte) + } +} diff --git a/src/lib.rs b/src/lib.rs index c29f18b..fbad9e5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -68,6 +68,7 @@ #![warn(missing_docs)] +pub mod command_line; pub mod engine; #[cfg(doc)] pub mod guide; @@ -76,6 +77,9 @@ pub mod registers; pub mod text; pub mod types; +pub use command_line::{ + CommandLine, InvalidPromptDraft, PromptDirection, PromptKind, PromptOutcome, +}; pub use engine::{ Action, AppliedEdit, Binding, BindingContext, Capabilities, Command, EditTarget, EditingState, EngineError, HistoryCommand, HostCommand, HostOperation, HostOutcome, HostResult, Input, diff --git a/tests/command_line.json b/tests/command_line.json new file mode 100644 index 0000000..a987db8 --- /dev/null +++ b/tests/command_line.json @@ -0,0 +1,16 @@ +[ + {"kind":"Ex","keys":["i","w","d","d","u"],"text":"iwddu","caret":5}, + {"kind":"Ex","keys":["a","b","界","Left","X"],"text":"abX界","caret":3}, + {"kind":"Ex","keys":["a","👩","‍","👩","‍","👦","Backspace"],"text":"a","caret":1}, + {"kind":"Ex","keys":["o","n","e"," ","t","w","o","!","Left","Ctrl-w"],"text":"one !","caret":4}, + {"kind":"Ex","keys":["o","n","e"," ","t","w","o","!","Left","Ctrl-u"],"text":"!","caret":0}, + {"kind":"Ex","keys":["a","b","c","Delete"],"text":"ab","caret":2}, + {"kind":"Ex","keys":["Backspace"],"outcome":"cancelled"}, + {"kind":"SearchForward","keys":["Backspace"],"outcome":"cancelled"}, + {"kind":"SearchBackward","keys":["d","w","a"],"text":"dwa","caret":3}, + {"kind":"Field","keys":["Backspace","Z"],"text":"Z","caret":1}, + {"kind":"Field","initial":"XY","keys":["z","Enter"],"outcome":"XYz"}, + {"kind":"Field","keys":["Enter"],"outcome":""}, + {"kind":"Field","initial":"XY","keys":["Escape"],"outcome":"cancelled"}, + {"kind":"Ex","keys":["f","o","o","Paste:A\r\nB"],"text":"fooA","caret":4} +] diff --git a/tests/command_line.rs b/tests/command_line.rs new file mode 100644 index 0000000..8b2d10a --- /dev/null +++ b/tests/command_line.rs @@ -0,0 +1,70 @@ +use serde::Deserialize; +use vimlet::{ByteOffset, CommandLine, Key, PromptKind, PromptOutcome}; + +#[derive(Deserialize)] +struct Case { + kind: String, + keys: Vec, + #[serde(default)] + initial: String, + text: Option, + caret: Option, + outcome: Option, +} + +#[test] +fn command_line_matches_neovim_fixtures() { + let cases: Vec = serde_json::from_str(include_str!("command_line.json")).unwrap(); + for case in cases { + let kind = match case.kind.as_str() { + "Ex" => PromptKind::Ex, + "SearchForward" => PromptKind::SearchForward, + "SearchBackward" => PromptKind::SearchBackward, + "Field" => PromptKind::Field, + _ => unreachable!(), + }; + let mut line = CommandLine::new(kind, case.initial).unwrap(); + let mut outcome = None; + for key in &case.keys { + let key = match key.as_str() { + "Left" => Key::Left, + "Backspace" => Key::Backspace, + "Delete" => Key::Delete, + "Enter" => Key::Enter, + "Escape" => Key::Escape, + "Ctrl-u" => Key::Ctrl('u'), + "Ctrl-w" => Key::Ctrl('w'), + key if key.starts_with("Paste:") => Key::Text(key[6..].into()), + ch => Key::Char(ch.parse().unwrap()), + }; + outcome = match line.handle(key) { + PromptOutcome::Accepted(text) => Some(text), + PromptOutcome::Cancelled => Some("cancelled".into()), + _ => None, + }; + } + assert_eq!(outcome, case.outcome, "{:?}", case.keys); + if let Some(text) = case.text { + assert_eq!(line.text(), text, "{:?}", case.keys); + assert_eq!(Some(line.caret().0), case.caret, "{:?}", case.keys); + } + } +} + +#[test] +fn rejected_replacements_and_quoted_keys_cannot_submit() { + let mut line = CommandLine::new(PromptKind::Ex, "e\u{301}").unwrap(); + assert!(line.replace(line.text().into(), ByteOffset(1)).is_err()); + assert!(line.replace("one\ntwo".into(), ByteOffset(0)).is_err()); + assert_eq!(line.handle(Key::Ctrl('v')), PromptOutcome::Consumed); + assert_eq!(line.handle(Key::Enter), PromptOutcome::Consumed); + assert_eq!( + line.handle(Key::Text("x\u{3}\ny".into())), + PromptOutcome::Edited + ); + assert_eq!( + line.handle(Key::Enter), + PromptOutcome::Accepted("e\u{301}x\u{3}".into()) + ); + assert_eq!(line.handle(Key::Enter), PromptOutcome::Unhandled); +}