use crate::history::SearchDirection;
use crate::Context;
pub trait Hint {
fn display(&self) -> &str;
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())
}
}
pub trait Hinter {
type Hint: Hint + 'static;
fn hint(&self, line: &str, pos: usize, ctx: &Context<'_>) -> Option<Self::Hint> {
let _ = (line, pos, ctx);
None
}
}
impl Hinter for () {
type Hint = String;
}
#[derive(Default)]
pub struct HistoryHinter {}
impl 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);
}
}