reedline/hinter/
default.rs1use crate::{hinter::get_first_token, history::SearchQuery, Hinter, History};
2use nu_ansi_term::{Color, Style};
3
4pub struct DefaultHinter {
6 style: Style,
7 current_hint: String,
8 min_chars: usize,
9}
10
11impl Hinter for DefaultHinter {
12 fn handle(
13 &mut self,
14 line: &str,
15 #[allow(unused_variables)] pos: usize,
16 history: &dyn History,
17 use_ansi_coloring: bool,
18 ) -> String {
19 self.current_hint = if line.chars().count() >= self.min_chars {
20 history
21 .search(SearchQuery::last_with_prefix(
22 line.to_string(),
23 history.session(),
24 ))
25 .expect("todo: error handling")
26 .first()
27 .map_or_else(String::new, |entry| {
28 entry
29 .command_line
30 .get(line.len()..)
31 .unwrap_or_default()
32 .to_string()
33 })
34 } else {
35 String::new()
36 };
37
38 if use_ansi_coloring && !self.current_hint.is_empty() {
39 self.style.paint(&self.current_hint).to_string()
40 } else {
41 self.current_hint.clone()
42 }
43 }
44
45 fn complete_hint(&self) -> String {
46 self.current_hint.clone()
47 }
48
49 fn next_hint_token(&self) -> String {
50 get_first_token(&self.current_hint)
51 }
52}
53
54impl Default for DefaultHinter {
55 fn default() -> Self {
56 DefaultHinter {
57 style: Style::new().fg(Color::LightGray),
58 current_hint: String::new(),
59 min_chars: 1,
60 }
61 }
62}
63
64impl DefaultHinter {
65 #[must_use]
67 pub fn with_style(mut self, style: Style) -> Self {
68 self.style = style;
69 self
70 }
71
72 #[must_use]
74 pub fn with_min_chars(mut self, min_chars: usize) -> Self {
75 self.min_chars = min_chars;
76 self
77 }
78}