summaryrefslogtreecommitdiffstats
path: root/src/completion.rs
blob: 4e766aacbb99c679215092dbf359311e2bbe5d29 (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
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
use std::fs::{self, ReadDir};

use anyhow::Result;
use strum::IntoEnumIterator;

use crate::{fileinfo::PathContent, tree::Filenames};

/// Different kind of completions
#[derive(Clone, Default, Copy)]
pub enum InputCompleted {
    /// No completion needed
    #[default]
    Nothing,
    /// Complete a directory path in filesystem
    Goto,
    /// Complete a filename from current directory
    Search,
    /// Complete an executable name from $PATH
    Exec,
    /// Command
    Command,
}

/// Holds a `Vec<String>` of possible completions and an `usize` index
/// showing where the user is in the vec.
#[derive(Clone, Default)]
pub struct Completion {
    /// Possible completions
    pub proposals: Vec<String>,
    /// Which completion is selected by the user
    pub index: usize,
}

impl Completion {
    /// Is there any completion option ?
    pub fn is_empty(&self) -> bool {
        self.proposals.is_empty()
    }

    /// Move the index to next element, cycling to 0.
    /// Does nothing if the list is empty.
    pub fn next(&mut self) {
        if self.proposals.is_empty() {
            return;
        }
        self.index = (self.index + 1) % self.proposals.len()
    }

    /// Move the index to previous element, cycling to the last one.
    /// Does nothing if the list is empty.
    pub fn prev(&mut self) {
        if self.proposals.is_empty() {
            return;
        }
        if self.index > 0 {
            self.index -= 1
        } else {
            self.index = self.proposals.len() - 1
        }
    }

    /// Returns the currently selected proposition.
    /// Returns an empty string if `proposals` is empty.
    pub fn current_proposition(&self) -> &str {
        if self.proposals.is_empty() {
            return "";
        }
        &self.proposals[self.index]
    }

    /// Updates the proposition with a new `Vec`.
    /// Reset the index to 0.
    fn update(&mut self, proposals: Vec<String>) {
        self.index = 0;
        self.proposals = proposals;
        self.proposals.dedup()
    }

    fn extend(&mut self, proposals: &[String]) {
        self.index = 0;
        self.proposals.extend_from_slice(proposals);
        self.proposals.dedup()
    }

    /// Empty the proposals `Vec`.
    /// Reset the index.
    pub fn reset(&mut self) {
        self.index = 0;
        self.proposals.clear();
    }

    /// Goto completion.
    /// Looks for the valid path completing what the user typed.
    pub fn goto(&mut self, input_string: &str, current_path: &str) -> Result<()> {
        self.goto_update_from_input(input_string, current_path);
        let (parent, last_name) = split_input_string(input_string);
        if last_name.is_empty() {
            return Ok(());
        }
        self.extend_absolute_paths(&parent, &last_name);
        self.extend_relative_paths(current_path, &last_name);
        Ok(())
    }

    fn goto_update_from_input(&mut self, input_string: &str, current_path: &str) {
        self.proposals = vec![];
        if let Some(expanded_input) = self.expand_input(input_string) {
            self.proposals.push(expanded_input);
        }
        if let Some(cannonicalized_input) = self.canonicalize_input(input_string, current_path) {
            self.proposals.push(cannonicalized_input);
        }
    }

    fn expand_input(&mut self, input_string: &str) -> Option<String> {
        let expanded_input = shellexpand::tilde(input_string).into_owned();
        if std::path::PathBuf::from(&expanded_input).exists() {
            Some(expanded_input)
        } else {
            None
        }
    }

    fn canonicalize_input(&mut self, input_string: &str, current_path: &str) -> Option<String> {
        let mut path = fs::canonicalize(current_path).unwrap();
        path.push(input_string);
        let path = fs::canonicalize(path).unwrap_or_default();
        if path.exists() {
            Some(path.to_str().unwrap_or_default().to_owned())
        } else {
            None
        }
    }

    fn extend_absolute_paths(&mut self, parent: &str, last_name: &str) {
        let Ok(path) = std::fs::canonicalize(parent) else {
            return;
        };
        let Ok(entries) = fs::read_dir(path) else {
            return;
        };
        self.extend(&Self::entries_matching_filename(entries, last_name))
    }

    fn extend_relative_paths(&mut self, current_path: &str, last_name: &str) {
        if let Ok(entries) = fs::read_dir(current_path) {
            self.extend(&Self::entries_matching_filename(entries, last_name))
        }
    }

    fn entries_matching_filename(entries: ReadDir, last_name: &str) -> Vec<String> {
        entries
            .filter_map(|e| e.ok())
            .filter(|e| e.file_type().unwrap().is_dir() && filename_startswith(e, last_name))
            .map(|e| e.path().to_string_lossy().into_owned())
            .collect()
    }

    /// Looks for programs in $PATH completing the one typed by the user.
    pub fn exec(&mut self, input_string: &str) -> Result<()> {
        let mut proposals: Vec<String> = vec![];
        if let Some(paths) = std::env::var_os("PATH") {
            for path in std::env::split_paths(&paths).filter(|path| path.exists()) {
                proposals.extend(Self::find_completion_in_path(path, input_string)?);
            }
        }
        self.update(proposals);
        Ok(())
    }

    /// Looks for fm actions completing the one typed by the user.
    pub fn command(&mut self, input_string: &str) -> Result<()> {
        let proposals = crate::action_map::ActionMap::iter()
            .filter(|command| {
                command
                    .to_string()
                    .to_lowercase()
                    .contains(&input_string.to_lowercase())
            })
            .map(|command| command.to_string())
            .collect();
        self.update(proposals);
        Ok(())
    }

    fn find_completion_in_path(
        path: std::path::PathBuf,
        input_string: &str,
    ) -> Result<Vec<String>> {
        Ok(fs::read_dir(path)?
            .filter_map(|e| e.ok())
            .filter(|e| file_match_input(e, input_string))
            .map(|e| e.path().to_string_lossy().into_owned())
            .collect())
    }

    /// Looks for file within current folder completing what the user typed.
    pub fn search_from_normal(
        &mut self,
        input_string: &str,
        path_content: &PathContent,
    ) -> Result<()> {
        self.update(
            path_content
                .content
                .iter()
                .filter(|f| f.filename.contains(input_string))
                .map(|f| f.filename.clone())
                .collect(),
        );
        Ok(())
    }

    /// Looks for file within tree completing what the user typed.
    pub fn search_from_tree(&mut self, input_string: &str, content: Filenames) -> Result<()> {
        self.update(
            content
                .filter(|&p| p.contains(input_string))
                .map(|p| p.replace("▸ ", "").replace("▾ ", ""))
                .collect(),
        );

        Ok(())
    }

    /// Complete the input string with current_proposition if possible.
    /// Returns the optional last chars of the current_proposition.
    /// If the current_proposition doesn't start with input_string, it returns None.
    pub fn complete_input_string(&self, input_string: &str) -> Option<&str> {
        self.current_proposition().strip_prefix(input_string