1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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 {
}

// noinspection RsLift
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 {
}