Skip to content

Commit

Permalink
Add examples for custom key bindings
Browse files Browse the repository at this point in the history
- Use Ctrl-E for hint completion
- Insert tab when the cursor is ontop a whitespace character
- Prompt for numeric entry only
  • Loading branch information
gwenn committed Mar 6, 2021
1 parent 15d9f43 commit bf5bbfd
Show file tree
Hide file tree
Showing 5 changed files with 156 additions and 6 deletions.
96 changes: 96 additions & 0 deletions examples/custom_key_bindings.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
use std::borrow::Cow::{self, Borrowed, Owned};

use rustyline::highlight::Highlighter;
use rustyline::hint::{Hinter, HistoryHinter};
use rustyline::{
Cmd, ConditionalEventHandler, Context, Editor, Event, EventContext, EventHandler, KeyEvent,
RepeatCount,
};
use rustyline_derive::{Completer, Helper, Validator};

#[derive(Completer, Helper, Validator)]
struct MyHelper(HistoryHinter);

impl Hinter for MyHelper {
type Hint = String;

fn hint(&self, line: &str, pos: usize, ctx: &Context<'_>) -> Option<String> {
self.0.hint(line, pos, ctx)
}
}

impl Highlighter for MyHelper {
fn highlight_prompt<'b, 's: 'b, 'p: 'b>(
&'s self,
prompt: &'p str,
default: bool,
) -> Cow<'b, str> {
if default {
Owned(format!("\x1b[1;32m{}\x1b[m", prompt))
} else {
Borrowed(prompt)
}
}

fn highlight_hint<'h>(&self, hint: &'h str) -> Cow<'h, str> {
Owned(format!("\x1b[1m{}\x1b[m", hint))
}
}

struct CompleteHintHandler;
impl ConditionalEventHandler for CompleteHintHandler {
fn handle(&self, evt: &Event, _: RepeatCount, _: bool, ctx: &EventContext) -> Option<Cmd> {
debug_assert_eq!(*evt, Event::from(KeyEvent::ctrl('E')));
if ctx.has_hint() {
Some(Cmd::CompleteHint)
} else {
None // default
}
}
}

struct TabEventHandler;
impl ConditionalEventHandler for TabEventHandler {
fn handle(&self, evt: &Event, n: RepeatCount, _: bool, ctx: &EventContext) -> Option<Cmd> {
debug_assert_eq!(*evt, Event::from(KeyEvent::from('\t')));
if ctx.line()[..ctx.pos()]
.chars()
.rev()
.next()
.filter(|c| c.is_whitespace())
.is_some()
{
Some(Cmd::SelfInsert(n, '\t'))
} else {
None // default complete
}
}
}

fn main() {
let mut rl = Editor::<MyHelper>::new();
rl.set_helper(Some(MyHelper(HistoryHinter {})));

rl.bind_sequence(
KeyEvent::ctrl('E'),
EventHandler::Conditional(Box::new(CompleteHintHandler)),
);
rl.bind_sequence(
KeyEvent::from('\t'),
EventHandler::Conditional(Box::new(TabEventHandler)),
);

loop {
let readline = rl.readline("> ");
match readline {
Ok(line) => {
rl.add_history_entry(line.as_str());
println!("Line: {}", line);
}
Err(err) => {
println!("Error: {:?}", err);
break;
}
}
}
}
4 changes: 2 additions & 2 deletions examples/example.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,8 @@ fn main() -> rustyline::Result<()> {
};
let mut rl = Editor::with_config(config);
rl.set_helper(Some(h));
rl.bind_sequence(KeyEvent::alt('N'), Cmd::HistorySearchForward);
rl.bind_sequence(KeyEvent::alt('P'), Cmd::HistorySearchBackward);
rl.bind_sequence(KeyEvent::alt('n'), Cmd::HistorySearchForward);
rl.bind_sequence(KeyEvent::alt('p'), Cmd::HistorySearchBackward);
if rl.load_history("history.txt").is_err() {
println!("No previous history.");
}
Expand Down
49 changes: 49 additions & 0 deletions examples/numeric_input.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
use rustyline::{
Cmd, ConditionalEventHandler, Editor, Event, EventContext, EventHandler, KeyCode, KeyEvent,
Modifiers, RepeatCount,
};

struct FilteringEventHandler;
impl ConditionalEventHandler for FilteringEventHandler {
fn handle(&self, evt: &Event, _: RepeatCount, _: bool, _: &EventContext) -> Option<Cmd> {
match evt {
Event::KeySeq(ks) => {
if let Some(KeyEvent(KeyCode::Char(c), m)) = ks.first() {
if m.contains(Modifiers::CTRL)
|| m.contains(Modifiers::ALT)
|| c.is_ascii_digit()
{
None
} else {
Some(Cmd::Noop) // filter out invalid input
}
} else {
None
}
}
_ => None,
}
}
}

fn main() {
let mut rl = Editor::<()>::new();

rl.bind_sequence(
Event::Any,
EventHandler::Conditional(Box::new(FilteringEventHandler)),
);

loop {
let readline = rl.readline("> ");
match readline {
Ok(line) => {
println!("Num: {}", line);
}
Err(err) => {
println!("Error: {:?}", err);
break;
}
}
}
}
5 changes: 5 additions & 0 deletions src/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,11 @@ mod tests {
assert_eq!(E::ESC, E::new('\x1b', M::NONE));
}

#[test]
fn from() {
assert_eq!(E(K::Tab, M::NONE), E::from('\t'));
}

#[test]
fn normalize() {
assert_eq!(E::ctrl('A'), E::normalize(E(K::Char('\x01'), M::NONE)));
Expand Down
8 changes: 4 additions & 4 deletions src/tty/windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,7 @@ impl RawReader for ConsoleRawReader {
let mut surrogate = 0;
loop {
// TODO GetNumberOfConsoleInputEvents
check(unsafe {
consoleapi::ReadConsoleInputW(self.handle, &mut rec, 1, &mut count)
})?;
check(unsafe { consoleapi::ReadConsoleInputW(self.handle, &mut rec, 1, &mut count) })?;

if rec.EventType == wincon::WINDOW_BUFFER_SIZE_EVENT {
SIGWINCH.store(true, Ordering::SeqCst);
Expand Down Expand Up @@ -449,7 +447,9 @@ impl Renderer for ConsoleRenderer {
}

fn sigwinch(&self) -> bool {
SIGWINCH.compare_exchange(true, false, Ordering::SeqCst, Ordering::SeqCst).unwrap_or(false)
SIGWINCH
.compare_exchange(true, false, Ordering::SeqCst, Ordering::SeqCst)
.unwrap_or(false)
}

/// Try to get the number of columns in the current terminal,
Expand Down

0 comments on commit bf5bbfd

Please sign in to comment.