use rustyline::{Changeset, Context, Editor, Helper};
use rustyline::completion::Completer;
use rustyline::highlight::Highlighter;
use rustyline::hint::Hinter;
use rustyline::history::DefaultHistory;
use rustyline::line_buffer::LineBuffer;
use rustyline::validate::Validator;
pub type CommandEditor = Editor<CommandHelper, DefaultHistory>;
pub struct CommandHelper {
commands: Vec<String>,
}
impl CommandHelper {
pub fn new(commands: Vec<String>) -> CommandHelper {
Self { commands }
}
fn find_candidates(&self, initial: &str) -> Vec<String> {
self.commands.iter()
.filter(|x| x.starts_with(initial))
.map(|x| x.to_string())
.collect()
}
}
impl Helper for CommandHelper {
}
impl Completer for CommandHelper {
type Candidate = String;
fn complete(
&self,
line: &str,
pos: usize,
_context: &Context<'_>,
) -> rustyline::Result<(usize, Vec<Self::Candidate>)> {
let line = &line[..pos];
if let Some((start, initial)) = line.rsplit_once(' ') {
let start = start.len() + 1;
let candidates = self.find_candidates(initial);
return Ok((start, candidates));
} else {
let candidates = self.find_candidates(line);
return Ok((0, candidates));
}
}
fn update(
&self,
line: &mut LineBuffer,
start: usize,
elected: &str,
changes: &mut Changeset,
) {
let end = line.pos();
let elected = format!("{} ", elected);
line.replace(start..end, &elected, changes);
}
}
impl Highlighter for CommandHelper {
}
impl Hinter for CommandHelper {
type Hint = String;
}
impl Validator for CommandHelper {
}