summaryrefslogtreecommitdiffstats
path: root/src/repl/highlighter.rs
blob: cca62977df725d1dc40854de19d2dd9e09695b84 (plain) (blame)
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
use crate::config::SharedConfig;

use nu_ansi_term::{Color, Style};
use reedline::{Highlighter, StyledText};

pub struct ReplHighlighter {
    external_commands: Vec<String>,
    config: SharedConfig,
}

impl ReplHighlighter {
    pub fn new(external_commands: Vec<String>, config: SharedConfig) -> Self {
        Self {
            external_commands,
            config,
        }
    }
}

impl Highlighter for ReplHighlighter {
    fn highlight(&self, line: &str, _cursor: usize) -> StyledText {
        let color = Color::Default;
        let match_color = if self.config.read().highlight {
            Color::Green
        } else {
            color
        };

        let mut styled_text = StyledText::new();

        if self
            .external_commands
            .clone()
            .iter()
            .any(|x| line.contains(x))
        {
            let matches: Vec<&str> = self
                .external_commands
                .iter()
                .filter(|c| line.contains(*c))
                .map(std::ops::Deref::deref)
                .collect();
            let longest_match = matches.iter().fold(String::new(), |acc, &item| {
                if item.len() > acc.len() {
                    item.to_string()
                } else {
                    acc
                }
            });
            let buffer_split: Vec<&str> = line.splitn(2, &longest_match).collect();

            styled_text.push((Style::new().fg(color), buffer_split[0].to_string()));
            styled_text.push((Style::new().fg(match_color), longest_match));
            styled_text.push((Style::new().fg(color), buffer_split[1].to_string()));
        } else {
            styled_text.push((Style::new().fg(color), line.to_string()));
        }

        styled_text
    }
}