lumesh 0.18.2

a lighting shell ⚡ bash alternative
Documentation
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
use crate::ai::init_ai;
use crate::cmdhelper::{
    LumeCompletionType, collect_command_with_prefix, detect_completion_type, find_command_pos,
};
use crate::completion::{ParamCompleter, list_path_entries};
use crate::editor::{
    Cmd, Completer, CompletionItem, Editor, EditorTheme, Highlighter, Hinter, KeyEvent,
    ReadlineError, ValidationResult, Validator,
};
use crate::expression::alias::get_alias_completion;
use crate::libs::{LIBS_INFO, is_lib};
use crate::syntax::{get_ayu_dark_theme, get_dark_theme, get_light_theme, get_merged_theme};
use crate::utils::{get_current_path, get_current_path_string};
use crate::{CFM_CONFIG, Expression, STRICT_ENABLED, childman};
use crate::{Environment, check, highlight, parse_and_eval, prompt::get_prompt_engine};
use std::collections::HashMap;
use std::path::{PathBuf, is_separator};
use std::rc::Rc;
use std::str::FromStr;
use std::sync::{Arc, Mutex};

use crossterm::style::Color;

const GREEN_BOLD: &str = "\x1b[1;32m";
const RESET: &str = "\x1b[0m";

struct LumeCompleter {
    param_completer: Arc<ParamCompleter>,
}

impl Completer for LumeCompleter {
    fn complete(&self, line: &str, pos: usize) -> Vec<CompletionItem> {
        match detect_completion_type(line, pos) {
            (LumeCompletionType::Path, _) => complete_path(line, pos),
            (LumeCompletionType::Command, section_pos) => {
                self.cmd_completion(line, pos, section_pos)
            }
            (LumeCompletionType::Param, section_pos) => {
                self.param_completion(line, pos, section_pos)
            }
            // (LumeCompletionType::AI, section_pos) => self.ai_completion(line, section_pos),
            (LumeCompletionType::None, _) => Vec::new(),
        }
    }
}

// only needed on head of line, without cmd
fn complete_path(line: &str, pos: usize) -> Vec<CompletionItem> {
    let prefix = &line[..pos];
    let path_start = prefix
        .rfind(|c: char| {
            c.is_ascii_whitespace()
                || c == '>'
                || c == ':'
                || c == '|'
                || c == '&'
                || c == '('
                || c == ';'
        })
        .map(|i| i + 1)
        .unwrap_or(0);
    let path = &prefix[path_start..];

    let entries = list_path_entries(path, false);
    let mut items: Vec<CompletionItem> = entries
        .into_iter()
        .map(|(name, full_path)| CompletionItem {
            display: Some(name),
            replacement: full_path,
            suffix: None,
        })
        .collect();
    items.sort_by(|a, b| a.replacement.cmp(&b.replacement));
    items
}

impl LumeCompleter {
    fn cmd_completion(&self, line: &str, pos: usize, section_start: usize) -> Vec<CompletionItem> {
        let prefix = &line[section_start..pos];

        let mut items: Vec<CompletionItem> = collect_command_with_prefix(prefix)
            .iter()
            .map(|cmd| CompletionItem::with(cmd.to_string(), if is_lib(cmd) { '.' } else { ' ' }))
            .collect();

        if items.is_empty() {
            match prefix.split_once(".") {
                Some((name, func)) => {
                    if !name.is_empty() {
                        LIBS_INFO.with(|h| {
                            if let Some(lib) = h.get(&name) {
                                items = lib
                                    .iter()
                                    .filter(|(f, _)| f.starts_with(func))
                                    .map(|(cmd, _)| CompletionItem::with(cmd.to_string(), '('))
                                    .collect();
                            }
                        });
                        items.sort_by_key(|a| a.display_text().len());
                        return items;
                    }
                }
                _ => {
                    items = get_alias_completion(prefix)
                        .into_iter()
                        .map(|cmd| CompletionItem::with(cmd, ' '))
                        .collect();
                }
            }
        }

        items.sort_by_key(|a| a.display_text().len());
        items
    }

    fn param_completion(
        &self,
        line: &str,
        pos: usize,
        section_start: usize,
    ) -> Vec<CompletionItem> {
        let cmd_section = &line[section_start..pos];
        let tokens: Vec<&str> = cmd_section.split_whitespace().collect();

        if let Some((command, tokens)) = tokens.split_first() {
            let param_start = cmd_section.rfind(' ').map(|x| x + 1);
            let current_token = param_start.map_or("", |x| &cmd_section[x..]);

            let params = if current_token.is_empty() {
                tokens
            } else {
                &tokens[..tokens.len().saturating_sub(1)]
            };

            let pairs =
                self.param_completer
                    .get_completions_for_context(command, params, current_token);

            let mut items: Vec<CompletionItem> = pairs
                .into_iter()
                .map(|p| {
                    if p.replacement.ends_with("/") {
                        CompletionItem::with_display(p.display, p.replacement)
                    } else {
                        CompletionItem {
                            display: Some(p.display),
                            replacement: p.replacement,
                            suffix: Some(' '),
                        }
                    }
                })
                .collect();

            // empty param completion, try path
            if items.is_empty() && current_token.contains(is_separator) {
                let entries = list_path_entries(current_token, false);
                items = entries
                    .into_iter()
                    .map(|(name, full_path)| CompletionItem {
                        display: Some(name),
                        replacement: full_path,
                        suffix: None,
                    })
                    .collect();
            }

            items.sort_by_key(|a| a.replacement.len());
            return items;
        }
        Vec::new()
    }
}

struct LumeHighlighter {
    theme: HashMap<String, String>,
}

impl Highlighter for LumeHighlighter {
    fn highlight(&self, line: &str) -> String {
        if line.is_empty() {
            return String::new();
        }
        highlight(line, &self.theme)
    }

    fn highlight_char(&self, _line: &str, _pos: usize) -> bool {
        false
    }
}

struct LumeHinter {
    #[allow(clippy::type_complexity)]
    hinter: Option<Box<dyn Fn(&str, usize) -> Option<String>>>,
}

impl Hinter for LumeHinter {
    fn hint(&self, line: &str, pos: usize) -> Option<String> {
        if let Some(ref f) = self.hinter {
            f(line, pos)
        } else {
            None
        }
    }
}

pub fn run_repl(env: &mut Environment) {
    // 安装全局 SIGINT 处理器:仅设置标志,不杀死 lume
    childman::install_sigint_handler();

    match env.get("LUME_WELCOME") {
        Some(wel) => {
            println!("{wel}");
            env.undefine("LUME_WELCOME");
        }
        _ => println!("Welcome to Lumesh {}", env!("CARGO_PKG_VERSION")),
    }

    if STRICT_ENABLED.with_borrow(|s| s == &true) {
        println!("\x1b[38;5;170m[Strict Mode]\x1b[0m")
    }
    if CFM_CONFIG.with_borrow(|c| c == &Some(true)) {
        println!("\x1b[38;5;141m[Cmd First Mode]\x1b[0m");
    }

    // history
    let no_history = match env.get("LUME_NO_HISTORY") {
        Some(Expression::Boolean(t)) => {
            env.undefine("LUME_NO_HISTORY");
            t
        }
        _ => false,
    };
    let history_file = match env.get("LUME_HISTORY_FILE") {
        Some(hf) => hf.to_string(),
        _ => {
            let c_dir = match dirs::cache_dir() {
                Some(c) => c.join("lumesh"),
                _ => PathBuf::new().join("lumesh"),
            };

            let path = c_dir.join("history");
            if !c_dir.exists()
                && let Err(e) = std::fs::create_dir_all(&c_dir)
            {
                eprintln!("Failed to create cache directory: {e}");
            }
            if !path.exists()
                && let Err(e) = std::fs::File::create(&path)
            {
                eprintln!("Failed to create cache file: {e}");
            }
            path.into_os_string().into_string().unwrap()
        }
    };

    // theme
    let theme_base = env.get("LUME_THEME");
    env.undefine("LUME_THEME");
    let theme = match theme_base {
        Some(Expression::String(t)) => match t.as_ref() {
            "light" => get_light_theme(),
            "ayu_dark" => get_ayu_dark_theme(),
            _ => get_dark_theme(),
        },
        _ => get_dark_theme(),
    };
    let theme_config = env.get("LUME_THEME_CONFIG");
    env.undefine("LUME_THEME_CONFIG");
    let theme_merged = match theme_config {
        Some(Expression::Map(m)) => get_merged_theme(theme, m.as_ref()),
        _ => theme,
    };

    // completion
    let completion_dir = match env.get("LUME_COMPLETION_DIR") {
        Some(Expression::String(c)) => c,
        _ => {
            if cfg!(target_os = "macos") {
                dirs::data_local_dir()
                    .unwrap_or_else(|| PathBuf::from("~/.local/share"))
                    .join("lumesh/completions")
                    .into_os_string()
                    .into_string()
                    .unwrap_or_else(|_| "~/.local/share/lumesh/completions".to_string())
            } else if cfg!(unix) {
                String::from("/usr/share/lumesh/completions")
            } else {
                String::from("C:\\Program Files\\lumesh\\completions")
            }
        }
    };
    env.undefine("LUME_COMPLETION_DIR");

    // key bindings
    let hotkey_sudo = match env.get("LUME_SUDO_CMD") {
        Some(s) => {
            env.undefine("LUME_SUDO_CMD");
            s.to_string()
        }
        _ => "sudo".to_string(),
    };

    let _abbr = env.get("LUME_ABBREVIATIONS");
    env.undefine("LUME_ABBREVIATIONS");

    // =======create editor=======
    let mut editor = Editor::new();

    // ai config
    let ai_config = env.get("LUME_AI_CONFIG");
    env.undefine("LUME_AI_CONFIG");

    // ai hinter
    let ai_client = ai_config.map(|ai_cfg| Arc::new(init_ai(ai_cfg)));
    if let Some(ref ai) = ai_client {
        editor.set_ai_client(Arc::clone(ai));
    }

    // Set up completer
    let completer = LumeCompleter {
        param_completer: Arc::new(ParamCompleter::new(completion_dir)),
    };
    editor.set_completer(Box::new(completer));

    // Set up highlighter
    // let hl_theme = theme_merged.clone();
    editor.set_highlighter(Box::new(LumeHighlighter {
        theme: theme_merged,
    }));

    // Set up hinter (hint from command history)
    // let hint_theme = theme_merged.clone();
    editor.set_hinter(Box::new(LumeHinter {
        hinter: Some(Box::new(move |line: &str, pos: usize| {
            hint_for_line(line, pos)
        })),
    }));

    // Editor theme from LUME_EDITOR_THEME config
    if let Some(Expression::Map(theme_map)) = env.get("LUME_EDITOR_THEME") {
        let mut theme = EditorTheme::default();
        for (k, v) in theme_map.iter() {
            let val = v.to_string();
            match k.as_str() {
                "hint" => theme.hint_color = parse_color(&val),
                "completion_bg" => theme.completion_bg = parse_color(&val),
                "completion_fg" => theme.completion_fg = parse_color(&val),
                "completion_selected_bg" => theme.completion_selected_bg = parse_color(&val),
                "completion_selected_fg" => theme.completion_selected_fg = parse_color(&val),
                _ => {}
            }
        }
        editor.set_theme(theme);
    }
    env.undefine("LUME_EDITOR_THEME");

    // Set up key bindings
    // Ctrl+J: accept full hint
    // editor.bind_sequence(KeyEvent::Ctrl('j'), Cmd::AcceptHint);
    // Alt+J: accept one word from hint
    // editor.bind_sequence(KeyEvent::Alt('j'), Cmd::AcceptHintWord(0));
    // Ctrl+O: clear buffer
    editor.bind_sequence(KeyEvent::Ctrl('o'), Cmd::ClearBuffer);
    // Alt+S: toggle sudo/pkexec prefix
    // editor.set_sudo_cmd(&hotkey_sudo);
    editor.bind_sequence(KeyEvent::Alt('s'), Cmd::ToggleSudo(hotkey_sudo));

    // Set up validator for multiline input
    struct LumeValidator;
    impl Validator for LumeValidator {
        fn validate(&self, input: &str) -> ValidationResult {
            if input.starts_with("/") {
                // slash command
                ValidationResult::Valid
            } else if check(input) {
                ValidationResult::Valid
            } else {
                ValidationResult::Incomplete
            }
        }
    }
    editor.set_validator(Box::new(LumeValidator));

    // Share env with the editor callback via Rc<Mutex<>> so the callback
    // can fork a live snapshot of the current environment at hotkey time.
    let shared_env = Rc::new(Mutex::new(env.clone()));

    // Custom hotkeys LUME_HOT_BINDINGS
    let hotkey_bindings = env.get("LUME_HOT_BINDINGS");
    env.undefine("LUME_HOT_BINDINGS");

    if let Some(Expression::Map(bindings)) = hotkey_bindings {
        for (k, v) in bindings.iter() {
            let key_str = k.to_string();
            if let Some((mod_str, key_char)) = key_str.rsplit_once('_')
                && let Some(ch) = key_char.chars().next()
            {
                let key = parse_hot_key(mod_str.trim_matches(['\'', '"']), ch.to_ascii_lowercase());
                match v {
                    Expression::String(s) => {
                        // String value: insert directly into buffer
                        editor.bind_sequence(key, Cmd::InsertStr(s.clone()));
                    }
                    Expression::Function(..) | Expression::Lambda(..) => {
                        // Function/Lambda: execute with buffer as argument,
                        // insert result if it returns a string
                        let expr = v.clone();
                        let shared_env = shared_env.clone();
                        editor.bind_hotkey_fn(key, move |buffer: &str| -> Option<String> {
                            let env_guard = shared_env.lock().ok()?;
                            let mut fork_env = env_guard.fork();
                            drop(env_guard);
                            let call = Expression::Apply(
                                Rc::new(expr.clone()),
                                Rc::new(vec![Expression::String(buffer.to_string())]),
                            );
                            match call.eval_cmd(&mut fork_env) {
                                Ok(Expression::String(s)) => Some(s),
                                // Ok(other) if other != Expression::None => {
                                //     println!("{other}");
                                //     let _ = std::io::stdout().flush();
                                //     None
                                // }
                                _ => None,
                            }
                        });
                    }
                    other => {
                        // Other types
                        eprintln!("invalid bindings: {} -> {}", key_str, other);
                    }
                }
            }
        }
    }
    let _abbr_map: HashMap<String, String> = match _abbr {
        Some(Expression::Map(ab)) => ab
            .iter()
            .map(|m| (m.0.to_string(), m.1.to_string()))
            .collect(),
        _ => HashMap::new(),
    };
    editor.set_abbreviations(_abbr_map);

    // =======load history=======
    let _ = editor.history_mut().load_from_file(&history_file);
    editor
        .history_mut()
        .set_current_dir(get_current_path_string(&mut shared_env.lock().unwrap()));

    // =======prompt=======
    let pe = get_prompt_engine(env.get("LUME_PROMPT_SETTINGS"));
    env.undefine("LUME_PROMPT_SETTINGS");
    editor.set_cont_prompt(&pe.get_prompt_continuation());

    // --------slash bindings-------
    let slash_bindings = if let Some(Expression::Map(m)) = env.get("LUME_SLASH_BINDINGS") {
        Some(m)
    } else {
        None
    };
    let slash_menu = env.get("LUME_SLASH_MENU");
    env.undefine("LUME_SLASH_BINDINGS");
    env.undefine("LUME_SLASH_MENU");
    // =======main loop=======
    let mut status: u8 = 0;
    let mut duration = 0;
    loop {
        let prompt = pe.get_prompt(status, duration);

        let line = match editor.readline(&prompt) {
            Ok(line) => line,
            Err(ReadlineError::Interrupted) => {
                println!("^C");
                if childman::kill_child() {
                    childman::clear_child();
                }
                continue;
            }
            Err(ReadlineError::Eof) => {
                println!("CTRL-D");
                continue;
            }
            Err(ReadlineError::Io(e)) => {
                eprintln!("Read error: {e}");
                continue;
            }
        };

        let trimmed = line.trim();

        if trimmed.is_empty() {
            continue;
        }

        if trimmed == "exit" {
            break;
        }

        // Strip backslash-newline continuation markers
        let full_input = trimmed.replace("\\\n", "");

        if full_input.is_empty() {
            continue;
        }

        // slash command:
        if let Some(rest) = full_input.strip_prefix('/')
            && !rest.contains('/')
        {
            if rest.is_empty() {
                // menu
                match &slash_menu {
                    Some(Expression::Lambda(..)) | Some(Expression::Function(..)) => {
                        let _x = slash_menu
                            .clone()
                            .unwrap()
                            .apply(vec![])
                            .eval(&mut shared_env.lock().unwrap());
                    }
                    None => {
                        eprintln!("LUME_SLASH_MENU is not defined")
                    }
                    _ => {
                        eprintln!("LUME_SLASH_MENU is not appliable")
                    }
                };
            } else if let Some(query) = rest.strip_prefix(' ') {
                // quick jump
                if let Some(cd_cmd) = editor.history().search_fuzzy_one_cd(query) {
                    if parse_and_eval(&cd_cmd, &mut shared_env.lock().unwrap()) == 0 {
                        // update current dir in history
                        let cwd = get_current_path(&mut shared_env.lock().unwrap());
                        editor
                            .history_mut()
                            .set_current_dir(cwd.to_string_lossy().to_string());
                        pe.set_dir_cache(cwd);
                        // must after
                        editor.history_mut().add(cd_cmd);
                    }
                }
            } else if rest == "q" {
                break;
            } else if rest == "cds" {
                let cmd = "ui.pick $PATH_SESSION 'cd to:' ?! | cd _";
                parse_and_eval(&cmd, &mut shared_env.lock().unwrap());
            } else {
                // slash bindings
                let (key, arg) = rest.split_once(' ').unwrap_or((rest, ""));
                match key {
                    "h" => {
                        let history = editor
                            .history()
                            .search_startswith(arg)
                            .into_iter()
                            .map(Expression::from)
                            .collect::<Vec<_>>();
                        if !history.is_empty() {
                            let mut forked_env = shared_env.lock().unwrap().fork();
                            forked_env.define("HISTORY", Expression::from(history));
                            let cmd =
                                format!("$HISTORY | ui.pick('select history') ?! | eval_str()");
                            parse_and_eval(&cmd, &mut forked_env);
                        }
                    }
                    "hh" => {
                        let history_here = editor
                            .history()
                            .search_local_startswith(arg)
                            .into_iter()
                            .map(Expression::from)
                            .collect::<Vec<_>>();
                        if !history_here.is_empty() {
                            let mut forked_env = shared_env.lock().unwrap().fork();
                            forked_env.define("HISTORY", Expression::from(history_here));
                            let cmd =
                                format!("$HISTORY | ui.pick('select history') ?! | eval_str()");
                            parse_and_eval(&cmd, &mut forked_env);
                        }
                    }
                    "hm" => {
                        let history_multi_dir = editor
                            .history()
                            .search_multidir_startswith(arg)
                            .into_iter()
                            .map(Expression::from)
                            .collect::<Vec<_>>();
                        if !history_multi_dir.is_empty() {
                            let mut forked_env = shared_env.lock().unwrap().fork();
                            forked_env.define("HISTORY", Expression::from(history_multi_dir));
                            let cmd =
                                format!("$HISTORY | ui.pick('select history') ?! | eval_str()");
                            parse_and_eval(&cmd, &mut forked_env);
                        }
                    }
                    "history" => {
                        if arg.is_empty() {
                            for (i, entry) in editor.history().iter().enumerate() {
                                println!("{}{}:{} {}", GREEN_BOLD, i + 1, RESET, entry);
                            }
                        } else {
                            for (i, entry) in editor
                                .history()
                                .iter()
                                .filter(|e| e.starts_with(arg))
                                .enumerate()
                            {
                                println!("{}{}:{} {}", GREEN_BOLD, i + 1, RESET, entry);
                            }
                        }
                    }
                    // custom slash bindings
                    _ => {
                        if let Some(r) = slash_bindings.clone().and_then(|m| {
                            m.as_ref().get(key).and_then(|exp| {
                                Some(exp.apply(vec![Expression::String(arg.to_string())]))
                            })
                        }) {
                            let _ = r.eval(&mut shared_env.lock().unwrap());
                        } else {
                            eprintln!("\x1b[31mundefined slash cmd\x1b[0m");
                        }
                    }
                }
            }
        } else {
            // normal
            let start = std::time::Instant::now();
            status = parse_and_eval(&full_input, &mut shared_env.lock().unwrap());
            duration = start.elapsed().as_millis();

            if status == 0 {
                let changing = full_input.starts_with("cd ");
                // update current dir in history
                if changing {
                    let cwd = get_current_path(&mut shared_env.lock().unwrap());
                    editor
                        .history_mut()
                        .set_current_dir(cwd.to_string_lossy().to_string());
                    // update prompt  cache dir
                    pe.set_dir_cache(cwd);
                }
                // must bellow set_current_dir
                editor.history_mut().add(full_input);
            } else {
                editor.history_mut().add_tmp(full_input);
            }
        }

        // 检查命令执行期间是否收到 SIGINT(Ctrl+C)
        if childman::check_and_clear_sigint() {
            println!("^C");
        }
    }

    // Save history
    if !no_history && let Err(e) = editor.history_mut().save_to_file(&history_file) {
        eprintln!("Failed to save history: {e}");
    }
}

fn hint_for_line(line: &str, pos: usize) -> Option<String> {
    let prefix = &line[..pos];
    let p = find_command_pos(prefix);
    let segment = &prefix[p..];

    if segment.is_empty() {
        return None;
    }

    let mut matches = collect_command_with_prefix(segment);

    if matches.is_empty() {
        let ends: &[_] = &['(', ' '];
        let (matches, hint_pos) = match segment.split_once(".") {
            Some((name, func)) => LIBS_INFO.with(|h| {
                if let Some(lib) = h.get(&name) {
                    (
                        lib.iter()
                            .filter(|(f, _)| f.starts_with(func.trim_matches(ends)))
                            .map(|(f, info)| {
                                let tip = if func.trim_end().ends_with('(') {
                                    format!("{f}(\0{})", info.hint.replace(' ', ","))
                                } else {
                                    format!("{f} \0{}", info.hint)
                                };
                                (tip, f.len())
                            })
                            .collect::<Vec<_>>(),
                        func.len(),
                    )
                } else {
                    (Vec::new(), 0)
                }
            }),
            _ => LIBS_INFO.with(|h| {
                if let Some(lib) = h.get("") {
                    (
                        lib.iter()
                            .filter(|(f, _)| f.starts_with(segment.trim_matches(ends)))
                            .map(|(f, info)| {
                                let tip = if segment.trim_end().ends_with('(') {
                                    format!("{f}(\0{})", info.hint.replace(' ', ","))
                                } else {
                                    format!("{f} \0{}", info.hint)
                                };
                                (tip, f.len())
                            })
                            .collect::<Vec<_>>(),
                        segment.len(),
                    )
                } else {
                    (Vec::new(), 0)
                }
            }),
        };
        if !matches.is_empty() {
            // let hint_color = theme.get("hint").map_or(DEFAULT, |c| c.as_str());
            let matches: Vec<_> = matches.iter().filter(|(_, l)| *l > 0).collect();
            if let Some((matched, _)) = matches.first() {
                let suffix = &matched[hint_pos..];
                if !suffix.is_empty() {
                    // return Some(format!("{hint_color}{suffix}{RESET}"));
                    return Some(suffix.to_string());
                }
            }
        }
        return None;
    }

    matches.sort_by_key(|a| a.len());
    if let Some(matched) = matches.first() {
        let suffix = &matched[segment.len()..];
        if !suffix.is_empty() {
            return Some(suffix.to_string());
            //     let hint_color = theme.get("hint").map_or(DEFAULT, |c| c.as_str());
            //     return Some(format!("{hint_color}{suffix}{RESET}"));
        }
    }

    None
}

fn parse_hot_key(modifier_str: &str, key_char: char) -> KeyEvent {
    match modifier_str {
        "CTRL_ALT" => KeyEvent::CtrlAlt(key_char),
        "CTRL_SHIFT" => KeyEvent::CtrlShift(key_char),
        "ALT_SHIFT" => KeyEvent::AltShift(key_char),
        "CTRL_ALT_SHIFT" => KeyEvent::CtrlAltShift(key_char),
        "CTRL" => KeyEvent::Ctrl(key_char),
        "ALT" => KeyEvent::Alt(key_char),
        "SHIFT" => KeyEvent::Shift(key_char),
        _ => KeyEvent::Char(key_char),
    }
}

fn parse_color(s: &str) -> Color {
    Color::from_str(s).unwrap_or(Color::Grey)
    // match s.to_lowercase().as_str() {
    //     "black" => Color::Black,
    //     "dark_grey" => Color::DarkGrey,
    //     "red" => Color::Red,
    //     "dark_red" => Color::DarkRed,
    //     "green" => Color::Green,
    //     "dark_green" => Color::DarkGreen,
    //     "yellow" => Color::Yellow,
    //     "dark_yellow" => Color::DarkYellow,
    //     "blue" => Color::Blue,
    //     "dark_blue" => Color::DarkBlue,
    //     "magenta" => Color::Magenta,
    //     "dark_magenta" => Color::DarkMagenta,
    //     "cyan" => Color::Cyan,
    //     "dark_cyan" => Color::DarkCyan,
    //     "white" => Color::White,
    //     "grey" => Color::Grey,
    //     _ => Color::DarkGrey,
    // }
}