summaryrefslogtreecommitdiffstats
path: root/src/commands/search_fzf.rs
blob: 9d86b7b5b8b4a2a2e1b7add8339ff965ea3d225e (plain)
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
use std::io;
use std::io::Write;
use std::process::{Command, Stdio};

use crate::commands::cursor_move;
use crate::config::option::CaseSensitivity;
use crate::context::AppContext;
use crate::error::{JoshutoError, JoshutoErrorKind, JoshutoResult};
use crate::ui::AppBackend;

pub fn search_fzf(context: &mut AppContext, backend: &mut AppBackend) -> JoshutoResult {
    let items = context
        .tab_context_ref()
        .curr_tab_ref()
        .curr_list_ref()
        .map(|list| {
            let v: Vec<String> = list
                .iter()
                .enumerate()
                .map(|(i, entry)| format!("{} {}\n", i, entry.file_name()))
                .collect();
            v
        })
        .unwrap_or_default();

    if items.is_empty() {
        return Err(JoshutoError::new(
            JoshutoErrorKind::Io(io::ErrorKind::InvalidData),
            "no files to select".to_string(),
        ));
    }

    backend.terminal_drop();

    let mut cmd = Command::new("fzf");
    cmd.stdin(Stdio::piped()).stdout(Stdio::piped());

    let case_sensitivity = context
        .config_ref()
        .search_options_ref()
        .fzf_case_sensitivity;

    match case_sensitivity {
        CaseSensitivity::Insensitive => {
            cmd.arg("-i");
        }
        CaseSensitivity::Sensitive => {
            cmd.arg("+i");
        }
        // fzf uses smart-case match by default
        CaseSensitivity::Smart => {}
    }

    let mut fzf = match cmd.spawn() {
        Ok(child) => child,
        Err(e) => {
            backend.terminal_restore()?;
            return Err(JoshutoError::from(e));
        }
    };

    if let Some(fzf_stdin) = fzf.stdin.as_mut() {
        let mut writer = io::BufWriter::new(fzf_stdin);
        for item in items {
            writer.write_all(item.as_bytes())?;
        }
    }
    let fzf_output = fzf.wait_with_output();

    backend.terminal_restore()?;

    if let Ok(output) = fzf_output {
        if output.status.success() {
            if let Ok(selected) = std::str::from_utf8(&output.stdout) {
                let selected_idx_str = selected.split_once(' ');
                if let Some((selected_idx_str, _)) = selected_idx_str {
                    if let Ok(index) = selected_idx_str.parse::<usize>() {
                        cursor_move::cursor_move(context, index);
                    }
                }
            }
        }
    }

    Ok(())
}