summaryrefslogtreecommitdiffstats
path: root/src/commands/search.rs
blob: 41c2a8dff58ab2cd19296f6e7287f6fdb24be087 (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
87
use crate::context::{AppContext, MatchContext};
use crate::error::JoshutoResult;
use crate::tab::JoshutoTab;

use super::cursor_move;

pub fn search_next(context: &mut AppContext) -> JoshutoResult {
    if let Some(search_context) = context.get_search_context() {
        if search_context.is_none() {
            return Ok(());
        }

        let curr_tab = &context.tab_context_ref().curr_tab_ref();
        let index = curr_tab.curr_list_ref().and_then(|c| c.get_index());

        let offset = match index {
            Some(index) => index + 1,
            None => return Ok(()),
        };

        if let Some(index) = search_next_impl(curr_tab, search_context, offset) {
            cursor_move::cursor_move(context, index);
        }
    }

    Ok(())
}

pub(super) fn search_next_impl(
    curr_tab: &JoshutoTab,
    match_context: &MatchContext,
    offset: usize,
) -> Option<usize> {
    let curr_list = curr_tab.curr_list_ref()?;
    let contents_len = curr_list.contents.len();

    for i in 0..contents_len {
        let file_name = curr_list.contents[(offset + i) % contents_len].file_name();

        if match_context.is_match(file_name) {
            return Some((offset + i) % contents_len);
        }
    }

    None
}

pub fn search_prev(context: &mut AppContext) -> JoshutoResult {
    if let Some(search_context) = context.get_search_context() {
        if search_context.is_none() {
            return Ok(());
        }

        let curr_tab = &context.tab_context_ref().curr_tab_ref();
        let index = curr_tab.curr_list_ref().and_then(|c| c.get_index());

        let offset = match index {
            Some(index) => index,
            None => return Ok(()),
        };

        if let Some(index) = search_prev_impl(curr_tab, search_context, offset) {
            cursor_move::cursor_move(context, index);
        }
    }

    Ok(())
}

fn search_prev_impl(
    curr_tab: &JoshutoTab,
    match_context: &MatchContext,
    offset: usize,
) -> Option<usize> {
    let curr_list = curr_tab.curr_list_ref()?;
    let contents_len = curr_list.contents.len();

    for i in (0..contents_len).rev() {
        let file_name = curr_list.contents[(offset + i) % contents_len].file_name();

        if match_context.is_match(file_name) {
            return Some((offset + i) % contents_len);
        }
    }

    None
}