Skip to content

Commit

Permalink
Merge pull request #492 from gwenn/conditional_binding2
Browse files Browse the repository at this point in the history
Conditional binding
  • Loading branch information
gwenn authored Mar 7, 2021
2 parents 4eeb2e4 + bf55c10 commit 9c419ba
Show file tree
Hide file tree
Showing 11 changed files with 534 additions and 67 deletions.
6 changes: 6 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,20 @@ members = ["rustyline-derive"]
[dependencies]
bitflags = "1.2"
cfg-if = "1.0"
# For file completion
# https://rustsec.org/advisories/RUSTSEC-2020-0053.html
dirs-next = { version = "2.0", optional = true }
# For History
fs2 = "0.4"
libc = "0.2"
log = "0.4"
unicode-width = "0.1"
unicode-segmentation = "1.0"
memchr = "2.0"
# For custom bindings
# https://rustsec.org/advisories/RUSTSEC-2021-0003.html
smallvec = "1.6.1"
radix_trie = "0.2"

[target.'cfg(unix)'.dependencies]
nix = "0.20"
Expand Down
110 changes: 110 additions & 0 deletions examples/custom_key_bindings.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
use smallvec::smallvec;
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))
}
}

#[derive(Clone)]
struct CompleteHintHandler;
impl ConditionalEventHandler for CompleteHintHandler {
fn handle(&self, evt: &Event, _: RepeatCount, _: bool, ctx: &EventContext) -> Option<Cmd> {
if !ctx.has_hint() {
return None; // default
}
if let Some(k) = evt.get(0) {
#[allow(clippy::if_same_then_else)]
if *k == KeyEvent::ctrl('E') {
Some(Cmd::CompleteHint)
} else if *k == KeyEvent::alt('f') && ctx.line().len() == ctx.pos() {
Some(Cmd::CompleteHint) // TODO give access to hint
} else {
None
}
} else {
unreachable!()
}
}
}

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 {})));

let ceh = Box::new(CompleteHintHandler);
rl.bind_sequence(KeyEvent::ctrl('E'), EventHandler::Conditional(ceh.clone()));
rl.bind_sequence(KeyEvent::alt('f'), EventHandler::Conditional(ceh));
rl.bind_sequence(
KeyEvent::from('\t'),
EventHandler::Conditional(Box::new(TabEventHandler)),
);
rl.bind_sequence(
Event::KeySeq(smallvec![KeyEvent::ctrl('X'), KeyEvent::ctrl('E')]),
EventHandler::Simple(Cmd::Suspend), // TODO external editor
);

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
41 changes: 41 additions & 0 deletions examples/numeric_input.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
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> {
if let Some(KeyEvent(KeyCode::Char(c), m)) = evt.get(0) {
if m.contains(Modifiers::CTRL) || m.contains(Modifiers::ALT) || c.is_ascii_digit() {
None
} else {
Some(Cmd::Noop) // filter out invalid input
}
} else {
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;
}
}
}
}
Loading

0 comments on commit 9c419ba

Please sign in to comment.