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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
//! Hints (suggestions at the right of the prompt as you type).

use crate::history::SearchDirection;
use crate::Context;

/// A hint returned by Hinter
pub trait Hint {
    /// Text to display when hint is active
    fn display(&self) -> &str;
    /// Text to insert in line when right arrow is pressed
    fn completion(&self) -> Option<&str>;
}

impl Hint for String {
    fn display(&self) -> &str {
        self.as_str()
    }

    fn completion(&self) -> Option<&str> {
        Some(self.as_str())
    }
}

/// Hints provider
pub trait Hinter {
    /// Specific hint type
    type Hint: Hint + 'static;

    /// Takes the currently edited `line` with the cursor `pos`ition and
    /// returns the string that should be displayed or `None`
    /// if no hint is available for the text the user currently typed.
    // TODO Validate: called while editing line but not while moving cursor.
    fn hint(&self, line: &str, pos: usize, ctx: &Context<'_>) -> Option<Self::Hint> {
        let _ = (line, pos, ctx);
        None
    }
}

impl Hinter for () {
    type Hint = String;
}

/// Add suggestion based on previous history entries matching current user
/// input.
#[derive(Default)]
pub struct HistoryHinter {}

impl HistoryHinter {
    /// Create a new `HistoryHinter`
    pub fn new() -> Self {
        Self::default()
    }
}

impl Hinter for HistoryHinter {
    type Hint = String;

    fn hint(&self, line: &str, pos: usize, ctx: &Context<'_>) -> Option<String> {
        if line.is_empty() || pos < line.len() {
            return None;
        }
        let start = if ctx.history_index() == ctx.history().len() {
            ctx.history_index().saturating_sub(1)
        } else {
            ctx.history_index()
        };
        if let Some(sr) = ctx
            .history
            .starts_with(line, start, SearchDirection::Reverse)
            .unwrap_or(None)
        {
            if sr.entry == line {
                return None;
            }
            return Some(sr.entry[pos..].to_owned());
        }
        None
    }
}

#[cfg(test)]
mod test {
    use super::{Hinter, HistoryHinter};
    use crate::history::DefaultHistory;
    use crate::Context;

    #[test]
    pub fn empty_history() {
        let history = DefaultHistory::new();
        let ctx = Context::new(&history);
        let hinter = HistoryHinter {};
        let hint = hinter.hint("test", 4, &ctx);
        assert_eq!(None, hint);
    }
}