Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,097 changes: 764 additions & 333 deletions Cargo.lock

Large diffs are not rendered by default.

5 changes: 3 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ edition = "2021"
license = "MIT"
name = "reedline"
repository = "https://github.com/nushell/reedline"
rust-version = "1.63.0"
rust-version = "1.74.0"
version = "0.46.0"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
Expand All @@ -21,9 +21,10 @@ chrono = { version = "0.4.19", default-features = false, features = [
"serde",
] }
crossbeam = { version = "0.8.2", optional = true }
crossterm = { version = "0.29.0", features = ["serde"] }
crossterm = { version = "0.28.1", features = ["serde"] }
Comment thread
schlich marked this conversation as resolved.
Outdated
fd-lock = "4.0.2"
itertools = "0.13.0"
modalkit = "0.0.24"
nu-ansi-term = "0.50.0"
rusqlite = { version = "0.37.0", optional = true }
serde = { version = "1.0", features = ["derive"] }
Expand Down
6 changes: 2 additions & 4 deletions examples/demo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ fn main() -> reedline::Result<()> {
history_session_id,
Some(chrono::Utc::now()),
)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?,
.map_err(std::io::Error::other)?,
);
#[cfg(not(any(feature = "sqlite", feature = "sqlite-dynlib")))]
let history = Box::new(FileBackedHistory::with_file(50, "history.txt".into())?);
Expand Down Expand Up @@ -195,9 +195,7 @@ fn main() -> reedline::Result<()> {
}
if buffer.trim() == "clear-history" {
let hstry = Box::new(line_editor.history_mut());
hstry
.clear()
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
hstry.clear().map_err(std::io::Error::other)?;
continue;
}
println!("Our buffer: {buffer}");
Expand Down
2 changes: 1 addition & 1 deletion examples/helix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ fn main() -> io::Result<()> {
println!("Helix edit mode demo:\nAbort with Ctrl-C");

let prompt = DefaultPrompt::default();
let mut line_editor = Reedline::create().with_edit_mode(Box::new(Helix));
let mut line_editor = Reedline::create().with_edit_mode(Box::new(Helix::default()));

loop {
let sig = line_editor.read_line(&prompt)?;
Expand Down
2 changes: 1 addition & 1 deletion src/core_editor/line_buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -323,7 +323,7 @@ impl LineBuffer {
fn at_end_of_line_with_preceding_whitespace(&self) -> bool {
!self.is_empty() // No point checking if empty
&& self.insertion_point == self.lines.len()
&& self.lines.chars().last().map_or(false, |c| c.is_whitespace())
&& self.lines.chars().last().is_some_and(|c| c.is_whitespace())
}

/// Cursor position at the end of the current whitespace block.
Expand Down
282 changes: 255 additions & 27 deletions src/edit_mode/helix.rs
Original file line number Diff line number Diff line change
@@ -1,64 +1,292 @@
use crate::{
enums::{EventStatus, ReedlineEvent, ReedlineRawEvent},
edit_mode::EditMode,
enums::{EditCommand, ReedlineEvent, ReedlineRawEvent},
PromptEditMode, PromptViMode,
};
use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use modalkit::{
key::TerminalKey,
keybindings::{
BindingMachine, EdgeEvent, EdgePath, EdgeRepeat, EmptyKeyClass, EmptyKeyState,
InputBindings, InputKey, ModalMachine, Mode, ModeKeys,
},
};

use super::EditMode;
#[derive(Clone, Copy, Debug, Default, Hash, Eq, PartialEq)]
enum HelixMode {
#[default]
Insert,
Normal,
}

impl Mode<HelixAction, EmptyKeyState> for HelixMode {}

impl ModeKeys<TerminalKey, HelixAction, EmptyKeyState> for HelixMode {
fn unmapped(
&self,
key: &TerminalKey,
_: &mut EmptyKeyState,
) -> (Vec<HelixAction>, Option<HelixMode>) {
match self {
HelixMode::Normal => (vec![], None),
HelixMode::Insert => {
if let Some(c) = key.get_char() {
return (vec![HelixAction::Type(c)], None);
}

(vec![], None)
}
}
}
}

#[derive(Clone, Debug, Default, Eq, Hash, PartialEq)]
enum HelixAction {
Type(char),
MoveCharRight,
MoveCharLeft,
#[default]
NoOp,
}

type HelixStep = (Option<HelixAction>, Option<HelixMode>);

type HelixEdgePath = EdgePath<TerminalKey, EmptyKeyClass>;

type HelixMachine = ModalMachine<TerminalKey, HelixStep>;

/// A minimal custom edit mode example for Helix-style integrations.
#[derive(Default)]
pub struct Helix;
struct HelixBindings;

impl HelixBindings {
fn add_single_keypress_mapping(
machine: &mut HelixMachine,
mode: HelixMode,
code: KeyCode,
step: HelixStep,
) {
let path: &HelixEdgePath = &[(EdgeRepeat::Once, EdgeEvent::Key(TerminalKey::from(code)))];
machine.add_mapping(mode, path, &step);
}
}

impl InputBindings<TerminalKey, HelixStep> for HelixBindings {
fn setup(&self, machine: &mut HelixMachine) {
Self::add_single_keypress_mapping(
machine,
HelixMode::Insert,
KeyCode::Esc,
(None, Some(HelixMode::Normal)),
);
Self::add_single_keypress_mapping(
machine,
HelixMode::Normal,
KeyCode::Char('i'),
(None, Some(HelixMode::Insert)),
);
for code in [KeyCode::Char('h'), KeyCode::Left] {
Self::add_single_keypress_mapping(
machine,
HelixMode::Normal,
code,
(Some(HelixAction::MoveCharLeft), None),
);
}
for code in [KeyCode::Char('l'), KeyCode::Right] {
Self::add_single_keypress_mapping(
machine,
HelixMode::Normal,
code,
(Some(HelixAction::MoveCharRight), None),
);
}
}
}

/// A minimal custom edit mode example for Helix-style integrations.
pub struct Helix {
machine: HelixMachine,
}

impl std::fmt::Debug for Helix {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Helix")
.field("mode", &self.machine.mode())
.finish_non_exhaustive()
}
}

impl Default for Helix {
fn default() -> Self {
Self::new(PromptViMode::Insert)
}
}

impl Helix {
/// Creates a Helix editor with the requested initial mode.
pub fn new(initial_mode: PromptViMode) -> Self {
let mut machine = HelixMachine::from_bindings::<HelixBindings>();

if matches!(initial_mode, PromptViMode::Normal) {
machine.input_key(TerminalKey::from(KeyCode::Esc));
let _ = machine.pop();
}
Self { machine }
}
}

impl EditMode for Helix {
fn parse_event(&mut self, event: ReedlineRawEvent) -> ReedlineEvent {
match Event::from(event) {
Event::Key(KeyEvent {
let Ok(key_event) = KeyEvent::try_from(event) else {
return ReedlineEvent::None;
};

if matches!(
&key_event,
KeyEvent {
code: KeyCode::Char('c'),
modifiers: KeyModifiers::CONTROL,
..
}) => ReedlineEvent::CtrlC,
_ => ReedlineEvent::None,
}
) {
return ReedlineEvent::CtrlC;
}
}

fn edit_mode(&self) -> PromptEditMode {
PromptEditMode::Vi(PromptViMode::Normal)
let previous_mode = self.machine.mode();
self.machine.input_key(key_event.into());
let mode_changed = self.machine.mode() != previous_mode;

let Some((action, _ctx)) = self.machine.pop() else {
return if mode_changed {
ReedlineEvent::Repaint
} else {
ReedlineEvent::None
};
};

match action {
HelixAction::Type(c) => ReedlineEvent::Edit(vec![EditCommand::InsertChar(c)]),
HelixAction::MoveCharLeft => {
ReedlineEvent::Edit(vec![EditCommand::MoveLeft { select: false }])
}
HelixAction::MoveCharRight => {
ReedlineEvent::Edit(vec![EditCommand::MoveRight { select: false }])
}
HelixAction::NoOp => {
if mode_changed {
ReedlineEvent::Repaint
} else {
ReedlineEvent::None
}
}
}
}

fn handle_mode_specific_event(&mut self, _event: ReedlineEvent) -> EventStatus {
EventStatus::Inapplicable
fn edit_mode(&self) -> PromptEditMode {
match self.machine.mode() {
HelixMode::Insert => PromptEditMode::Vi(PromptViMode::Insert),
HelixMode::Normal => PromptEditMode::Vi(PromptViMode::Normal),
}
}
}

#[cfg(test)]
mod tests {
use super::*;
use crate::PromptViMode;
use crossterm::event::{Event, KeyEventKind, KeyEventState};
use rstest::rstest;

fn key_press(code: KeyCode, modifiers: KeyModifiers) -> ReedlineRawEvent {
Event::Key(KeyEvent {
code,
modifiers,
kind: KeyEventKind::Press,
state: KeyEventState::NONE,
})
.try_into()
.expect("valid crossterm key event")
}

#[test]
fn helix_edit_mode_defaults_to_normal_mode() {
let helix_mode = Helix;
fn helix_editor_defaults_to_insert_mode() {
let helix_editor = Helix::default();

let edit_mode = helix_mode.edit_mode();
assert!(matches!(
helix_editor.edit_mode(),
PromptEditMode::Vi(PromptViMode::Insert)
));
}

#[test]
fn ctrl_c_maps_to_interrupt_event() {
let mut helix_mode = Helix::default();

assert_eq!(
helix_mode.parse_event(key_press(KeyCode::Char('c'), KeyModifiers::CONTROL)),
ReedlineEvent::CtrlC
);
}

#[test]
fn pressing_esc_in_insert_mode_switches_to_normal() {
let mut helix_mode = Helix::new(PromptViMode::Insert);

assert_eq!(
helix_mode.parse_event(key_press(KeyCode::Esc, KeyModifiers::NONE)),
ReedlineEvent::Repaint
);

assert!(matches!(
edit_mode,
helix_mode.edit_mode(),
PromptEditMode::Vi(PromptViMode::Normal)
));
}

#[test]
fn helix_edit_mode_parses_ctrl_c_event() {
let mut helix_mode = Helix;
let ctrl_c_raw_event = ReedlineRawEvent::try_from(Event::Key(KeyEvent::new(
KeyCode::Char('c'),
KeyModifiers::CONTROL,
)));
fn pressing_i_in_normal_mode_switches_to_insert() {
let mut helix_mode = Helix::new(PromptViMode::Normal);

assert_eq!(
helix_mode.parse_event(ctrl_c_raw_event.unwrap()),
ReedlineEvent::CtrlC
helix_mode.parse_event(key_press(KeyCode::Char('i'), KeyModifiers::NONE)),
ReedlineEvent::Repaint
);
assert!(matches!(
helix_mode.edit_mode(),
PromptEditMode::Vi(PromptViMode::Insert)
));
}

#[test]
fn typing_in_insert_mode_produces_insert_char_event() {
let mut helix_mode = Helix::new(PromptViMode::Insert);

assert_eq!(
helix_mode.parse_event(key_press(KeyCode::Char('a'), KeyModifiers::NONE)),
ReedlineEvent::Edit(vec![EditCommand::InsertChar('a')])
);
}

#[rstest]
#[case(KeyCode::Char('h'))]
#[case(KeyCode::Left)]
fn pressing_left_key_or_h_in_normal_mode_moves_cursor_left(#[case] key_code: KeyCode) {
let mut helix_mode = Helix::new(PromptViMode::Normal);

assert_eq!(
helix_mode.parse_event(key_press(key_code, KeyModifiers::NONE)),
ReedlineEvent::Edit(vec![EditCommand::MoveLeft { select: false }])
);
}

#[rstest]
#[case(KeyCode::Char('l'))]
#[case(KeyCode::Right)]
fn pressing_right_key_or_l_in_normal_mode_moves_cursor_right(#[case] key_code: KeyCode) {
let mut helix_mode = Helix::new(PromptViMode::Normal);

assert_eq!(
helix_mode.parse_event(key_press(key_code, KeyModifiers::NONE)),
ReedlineEvent::Edit(vec![EditCommand::MoveRight { select: false }])
);
}
}
4 changes: 2 additions & 2 deletions src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2320,11 +2320,11 @@ mod tests {
fn with_edit_mode_builder_accepts_custom_helix_mode() {
use crate::PromptViMode;

let reedline = Reedline::create().with_edit_mode(Box::new(crate::Helix));
let reedline = Reedline::create().with_edit_mode(Box::new(crate::Helix::default()));

assert!(matches!(
reedline.prompt_edit_mode(),
PromptEditMode::Vi(PromptViMode::Normal)
PromptEditMode::Vi(PromptViMode::Insert)
));
}

Expand Down
Loading
Loading