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
//! The path palette: `@` mentions in the normal composer, Tab completion in
//! shell mode.
//!
//! Both use the same list UI over different path sources. They differ in how
//! the token under the cursor is found ([`App::active_path_token`]) and how a
//! picked path is written back ([`App::apply_file_palette_selection`]); the
//! navigation, caching, and rendering are shared.
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use super::{
file_picker::{self, FileMention, FilePaletteEntry, FilePaletteMatches, PathTokenSource},
palette::ActivePalette,
shell_palette, App,
};
/// What follows a path written into the composer.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum TokenTerminator {
/// The path is a finished argument; separate it from what comes next.
Space,
/// The path is a directory the user will keep descending into.
Continue,
}
impl App {
pub(super) fn handle_file_palette_key(&mut self, key: KeyEvent) -> anyhow::Result<bool> {
let palette = self.active_palette();
let handled = match (palette, key.modifiers, key.code) {
(Some(ActivePalette::File(matches)), KeyModifiers::NONE, KeyCode::Up) => {
let selection = self.input_ui.file_selection();
self.input_ui.set_file_selection(if selection == 0 {
matches.len() - 1
} else {
selection - 1
});
true
}
(Some(ActivePalette::File(matches)), KeyModifiers::NONE, KeyCode::Down) => {
self.input_ui
.set_file_selection((self.input_ui.file_selection() + 1) % matches.len());
true
}
(
Some(ActivePalette::File(matches)),
KeyModifiers::NONE,
KeyCode::Tab | KeyCode::Enter,
) => {
if let Some(entry) =
selected_palette_entry(&matches, self.input_ui.file_selection())
{
self.apply_file_palette_selection(&entry)?;
}
true
}
(Some(ActivePalette::File(_)), KeyModifiers::NONE, KeyCode::Esc) => {
self.close_file_palette();
true
}
// Shell mode has no auto-open: Tab on a bare word opens completion.
(_, KeyModifiers::NONE, KeyCode::Tab) if self.input_ui.shell_mode().is_some() => {
self.open_shell_completion()?;
true
}
_ => false,
};
if handled {
self.input_ui.clear_paste_burst();
self.ctrl_c_streak = 0;
}
Ok(handled)
}
/// Close the palette until the next typed edit (`@`) or the next Tab
/// (shell mode).
pub(super) fn close_file_palette(&mut self) {
self.input_ui.set_file_palette_dismissed(true);
self.input_ui.set_shell_completion_anchor(None);
self.input_ui.set_file_selection(0);
}
/// Act on the row the user picked.
///
/// A workspace path and a URI template are both references the message
/// carries as text, so both are written into the composer. A concrete
/// resource is content, so it becomes an attachment instead. A shell word
/// is written as a path the shell can read.
pub(super) fn apply_file_palette_selection(
&mut self,
entry: &FilePaletteEntry,
) -> anyhow::Result<()> {
match entry {
FilePaletteEntry::WorkspaceFile(path) => self.insert_selected_file_path(path),
// A template URI carries RFC 6570 placeholders, so there is nothing
// to read until a person fills them in. It goes in as text.
FilePaletteEntry::McpResource(resource) if resource.templated => {
if self.insert_file_mention_text(&resource.uri) {
self.set_status("resource template inserted; fill in the placeholders");
}
}
FilePaletteEntry::McpResource(resource) => self.start_mcp_resource_attach(resource)?,
}
Ok(())
}
pub(super) fn insert_selected_file_path(&mut self, path: &str) {
let Some(token) = self.active_path_token() else {
return;
};
match token.source {
PathTokenSource::Mention => {
if self.insert_file_mention_text(path) {
self.set_status("file path inserted");
}
}
// A directory is one component of a longer path: no space after
// it, so the next Tab keeps descending from where this one left off.
PathTokenSource::ShellWord => self.replace_path_token(
&token,
shell_palette::shell_quote(path),
if path.ends_with('/') {
TokenTerminator::Continue
} else {
TokenTerminator::Space
},
),
}
}
/// Replace the active `@` token with `@{text}` and close the palette.
///
/// Returns false when the mention is already gone, so callers do not report
/// an insertion that did not happen.
fn insert_file_mention_text(&mut self, text: &str) -> bool {
let Some(mention) =
file_picker::active_file_mention(self.input_ui.text(), self.input_ui.cursor())
else {
return false;
};
self.replace_path_token(&mention, format!("@{text}"), TokenTerminator::Space);
true
}
/// Write `insertion` over the token and close the palette. A `Space`
/// terminator is added only when the token is not already followed by one.
fn replace_path_token(
&mut self,
token: &FileMention,
mut insertion: String,
terminator: TokenTerminator,
) {
let next_is_space = self
.input_ui
.text()
.chars()
.nth(token.end)
.is_some_and(char::is_whitespace);
if terminator == TokenTerminator::Space && !next_is_space {
insertion.push(' ');
}
self.replace_input_range(token.start, token.end, &insertion);
self.close_file_palette();
}
/// Remove the active `@` token entirely, for a selection whose content is
/// attached rather than referenced by name.
pub(super) fn clear_active_file_mention(&mut self) {
let Some(mention) =
file_picker::active_file_mention(self.input_ui.text(), self.input_ui.cursor())
else {
return;
};
self.replace_input_range(mention.start, mention.end, "");
self.close_file_palette();
}
/// The token the path palette is matching on right now, if any.
///
/// Outside shell mode that is an `@` mention. In shell mode it is the bare
/// word Tab opened completion on, for as long as the cursor stays in it.
pub(super) fn active_path_token(&self) -> Option<FileMention> {
let (text, cursor) = (self.input_ui.text(), self.input_ui.cursor());
if self.input_ui.shell_mode().is_some() {
let anchor = self.input_ui.shell_completion_anchor()?;
file_picker::anchored_shell_word(text, cursor, anchor)
} else {
file_picker::active_file_mention(text, cursor)
}
}
/// Matches for the path palette, served from the session cache when fresh.
///
/// Get-or-discover: whichever path asks first — a keystroke or a render
/// frame — runs discovery once and shares the result. An empty answer also
/// drops any cache left by a token that is no longer active.
pub(super) fn file_match_list(&mut self) -> FilePaletteMatches {
let Some(token) = self.active_path_token() else {
self.palette_caches.clear_file();
return FilePaletteMatches::empty();
};
if let Some(matches) = self.palette_caches.fresh_file(
token.source,
&token.query,
super::palette::PALETTE_CACHE_TTL,
) {
return matches;
}
let discovered = self.discover_file_palette_matches(&token);
self.palette_caches
.store_file(token.source, token.query, discovered.clone());
discovered
}
/// Candidates for one token. A mention fuzzy-searches the whole workspace
/// index plus the MCP catalog (an in-memory listing refreshed at connect,
/// so this stays a local lookup on every keystroke). A shell word lists one
/// directory, one component at a time, as a shell does.
fn discover_file_palette_matches(&mut self, token: &FileMention) -> FilePaletteMatches {
let cwd = self.info.runtime.cwd.clone();
match token.source {
PathTokenSource::Mention => {
let discovered = file_picker::matching_file_paths_cached(
&cwd,
&token.query,
self.palette_caches.workspace_mut(),
);
let resources = if self.mcp_catalog.is_empty() {
Vec::new()
} else {
self.mcp_catalog.resources()
};
file_picker::file_palette_matches(discovered, &resources, &token.query)
}
PathTokenSource::ShellWord => FilePaletteMatches::shell_words(
shell_palette::shell_word_candidates(&cwd, &token.query),
),
}
}
/// Reset the highlight when the token changes and keep it inside the list.
/// Keep a shell anchor through zero matches so correcting the word restores
/// the list, but drop it when the cursor leaves that word.
pub(super) fn clamp_file_selection(&mut self) {
let query = self.active_path_token().map(|token| token.query);
if query.is_none() {
self.input_ui.set_shell_completion_anchor(None);
}
if self.input_ui.file_query() != query.as_deref() {
self.input_ui.set_file_query(query);
self.input_ui.set_file_selection(0);
}
let match_count = self.file_match_list().len();
if match_count == 0 {
self.input_ui.set_file_selection(0);
} else if self.input_ui.file_selection() >= match_count {
self.input_ui.set_file_selection(match_count - 1);
}
}
}
fn selected_palette_entry(
matches: &FilePaletteMatches,
selection: usize,
) -> Option<FilePaletteEntry> {
matches.get(selection.min(matches.len().saturating_sub(1)))
}
#[cfg(test)]
#[path = "file_palette_tests.rs"]
mod tests;