From d31247992286bef8e808a8777c2c8b9bdb23a783 Mon Sep 17 00:00:00 2001 From: NerdyPepper Date: Tue, 18 Jun 2019 16:25:01 +0530 Subject: add hinter, completer, matching bracket highlighter --- src/main.rs | 84 ++++++++++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 75 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/main.rs b/src/main.rs index 63e886e..1a05904 100644 --- a/src/main.rs +++ b/src/main.rs @@ -29,7 +29,67 @@ use rustyline::highlight::{ Highlighter, MatchingBracketHighlighter }; use clap::{Arg, App}; use lazy_static::lazy_static; -struct LineHelper (MatchingBracketHighlighter, HistoryHinter); + +struct RLHelper { + completer: FilenameCompleter, + highlighter: MatchingBracketHighlighter, + hinter: AnswerHinter, +} + +struct AnswerHinter { } + +impl Hinter for AnswerHinter { + fn hint(&self, line: &str, _: usize, _: &Context) -> Option { + let input = line.trim(); + let input = input.replace(" ", ""); + if input.len() == 0 { + return Some("".into()) + } + let dry_run = eval_math_expression(&input); + match dry_run { + Ok(ans) => return Some(format!("\x1b[90m = {}\x1b[0m", ans)), + Err(_) => return Some(format!("")) + }; + } +} + +impl Highlighter for RLHelper { + fn highlight_prompt<'p>(&self, prompt: &'p str) -> Cow<'p, str> { + Owned(String::from(prompt)) + } + + fn highlight_hint<'h>(&self, hint: &'h str) -> Cow<'h, str> { + Owned("\x1b[1m".to_owned() + hint + "\x1b[m") + } + + fn highlight<'l>(&self, line: &'l str, pos: usize) -> Cow<'l, str> { + self.highlighter.highlight(line, pos) + } + + fn highlight_char(&self, line: &str, pos: usize) -> bool { + self.highlighter.highlight_char(line, pos) + } +} + +impl Completer for RLHelper { + type Candidate = Pair; + fn complete( + &self, + line: &str, + pos: usize, + ctx: &Context<'_>, + ) -> Result<(usize, Vec), ReadlineError> { + self.completer.complete(line, pos, ctx) + } +} + +impl Hinter for RLHelper { + fn hint(&self, line: &str, a: usize, b: &Context) -> Option { + self.hinter.hint(line, a, b) + } +} + +impl Helper for RLHelper {} struct Configuration { radian_mode: bool, @@ -60,10 +120,16 @@ fn main() { .completion_type(CompletionType::Circular) .max_history_size(1000) .build(); - let mut rl = Editor::<()>::with_config(config); + let mut rl = Editor::with_config(config); + let h = RLHelper { + completer: FilenameCompleter::new(), + highlighter: MatchingBracketHighlighter::new(), + hinter: AnswerHinter {} + }; + rl.set_helper(Some(h)); if rl.load_history("history.txt").is_err() { - println!("No previous history."); - } + println!("No previous history.") + }; loop { let readline = rl.readline("> "); @@ -130,11 +196,11 @@ fn parse_arguments() -> Configuration { .unwrap_or("10") .parse() .unwrap(), - base: config.value_of("base") - .unwrap_or("10") - .parse() - .unwrap(), - input, + base: config.value_of("base") + .unwrap_or("10") + .parse() + .unwrap(), + input, } } -- cgit v1.2.3