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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
use crate::mjimap::MjiMap;
use crate::CFG;
use rustyline::error::ReadlineError;
use rustyline::hint::{Hint, Hinter};
use rustyline::Context;
use rustyline::Editor;
use rustyline_derive::{Completer, Helper, Highlighter, Validator};
use std::collections::HashSet;
use std::io::Write;

#[macro_export]
macro_rules! print_error {
    ($expression:expr) => {
        if let Err(error) = $expression {
            println!("{}", error);
        }
    };
}

#[derive(Completer, Helper, Validator, Highlighter)]
struct MjiHinter {
    hints: HashSet<CommandHint>,
}

#[derive(Hash, Debug, PartialEq, Eq)]
struct CommandHint {
    display: String,
    complete_up_to: usize,
}

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

    fn completion(&self) -> Option<&str> {
        if self.complete_up_to > 0 {
            Some(&self.display[..self.complete_up_to])
        } else {
            None
        }
    }
}

impl CommandHint {
    fn new(text: &str, complete_up_to: &str) -> CommandHint {
        assert!(text.starts_with(complete_up_to));
        CommandHint {
            display: text.into(),
            complete_up_to: complete_up_to.len(),
        }
    }

    fn suffix(&self, strip_chars: usize) -> CommandHint {
        CommandHint {
            display: self.display[strip_chars..].to_owned(),
            complete_up_to: self.complete_up_to.saturating_sub(strip_chars),
        }
    }
}

impl Hinter for MjiHinter {
    type Hint = CommandHint;

    fn hint(&self, line: &str, pos: usize, _ctx: &Context<'_>) -> Option<CommandHint> {
        if line.is_empty() || pos < line.len() {
            return None;
        }

        self.hints.iter().find_map(|hint| {
            if hint.display.starts_with(line) {
                Some(hint.suffix(pos))
            } else {
                None
            }
        })
    }
}

fn mji_hints(map: &MjiMap) -> HashSet<CommandHint> {
    let mut set = HashSet::new();
    map.iter().for_each(|v| {
        set.insert(CommandHint::new(&v.1.hint_name(), &v.1.hint_name()));
    });
    set
}

pub fn prompt(_f: &mut dyn Write, map: &MjiMap) {
    println!("Enter your commit message. Terminate input with CTRL-D.");

    let h = MjiHinter {
        hints: mji_hints(map),
    };
    let mut rl = Editor::<MjiHinter>::new().unwrap();
    rl.set_helper(Some(h));

    loop {
        let readline = rl.readline(">> ");
        match readline {
            Ok(line) => {
                rl.add_history_entry(line.as_str());

                let mut list = line
                    .split_whitespace()
                    .map(|x| x.trim().to_owned())
                    .collect::<Vec<String>>();

                if !list.is_empty() {
                    CFG.write().unwrap().inputs.append(&mut list);
                    CFG.write().unwrap().inputs.push("-".into());
                }
            }
            Err(ReadlineError::Interrupted) => {
                std::process::exit(0);
            }
            Err(ReadlineError::Eof) => {
                break;
            }
            Err(err) => {
                println!("Error: {err:?}");
                break;
            }
        }
    }
}