limit-cli 0.0.46

AI-powered terminal coding assistant with TUI. Multi-provider LLM support, session persistence, and built-in tools.
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
//! File autocomplete manager for TUI
//!
//! Manages file path autocomplete with @ prefix.

use crate::file_finder::FileFinder;
use limit_tui::components::FileMatchData;
use std::path::PathBuf;

/// Manages file autocomplete state and operations
pub struct FileAutocompleteManager {
    /// Base path for file searching
    base_path: PathBuf,
    /// File finder instance
    file_finder: FileFinder,
    /// Current autocomplete state
    state: Option<AutocompleteState>,
    /// Reusable buffer for file matches (avoids allocations)
    matches_buffer: Vec<FileMatchData>,
}

/// State for active autocomplete session
#[derive(Debug, Clone, Default)]
pub struct AutocompleteState {
    /// Whether autocomplete is active
    pub is_active: bool,
    /// Query typed after @
    pub query: String,
    /// Position of @ trigger in input
    pub trigger_pos: usize,
    /// Matching files
    pub matches: Vec<FileMatchData>,
    /// Currently selected index
    pub selected_index: usize,
}

impl FileAutocompleteManager {
    /// Create a new autocomplete manager
    pub fn new(working_dir: PathBuf) -> Self {
        Self {
            base_path: working_dir.clone(),
            file_finder: FileFinder::new(working_dir),
            state: None,
            matches_buffer: Vec::with_capacity(64),
        }
    }

    /// Get the base path for file searching
    #[inline]
    pub fn base_path(&self) -> &PathBuf {
        &self.base_path
    }

    /// Check if autocomplete is currently active
    #[inline]
    pub fn is_active(&self) -> bool {
        self.state.as_ref().is_some_and(|s| s.is_active)
    }

    /// Get current autocomplete state
    #[inline]
    pub fn state(&self) -> Option<&AutocompleteState> {
        self.state.as_ref()
    }

    /// Get mutable autocomplete state
    #[inline]
    pub fn state_mut(&mut self) -> Option<&mut AutocompleteState> {
        self.state.as_mut()
    }

    /// Activate autocomplete at the given trigger position
    pub fn activate(&mut self, trigger_pos: usize) {
        let matches = self.get_matches("");

        self.state = Some(AutocompleteState {
            is_active: true,
            query: String::with_capacity(64),
            trigger_pos,
            matches,
            selected_index: 0,
        });

        tracing::debug!("Activated autocomplete at pos {}", trigger_pos);
    }

    /// Deactivate autocomplete
    #[inline]
    pub fn deactivate(&mut self) {
        self.state = None;
    }

    /// Update the query and refresh matches
    pub fn update_query(&mut self, query: &str) {
        if let Some(ref mut state) = self.state {
            // First update query
            state.query.clear();
            state.query.push_str(query);

            // Get matches separately to avoid borrow conflicts
            let matches = self.get_matches(query);

            // Update state
            if let Some(ref mut state) = self.state {
                state.matches = matches;
                state.selected_index = 0;
            }
        }
    }

    /// Add a character to the query (avoids String allocation)
    pub fn append_char(&mut self, c: char) {
        if let Some(ref mut state) = self.state {
            state.query.push(c);
            let query = state.query.clone();

            let matches = self.get_matches(&query);

            if let Some(ref mut state) = self.state {
                state.matches = matches;
                state.selected_index = 0;
            }
        }
    }

    /// Remove last character from query
    pub fn backspace(&mut self) -> bool {
        let should_close = self
            .state
            .as_ref()
            .map(|s| s.query.is_empty())
            .unwrap_or(false);

        if should_close {
            return true;
        }

        if let Some(ref mut state) = self.state {
            state.query.pop();
            let query = state.query.clone();

            let matches = self.get_matches(&query);

            if let Some(ref mut state) = self.state {
                state.matches = matches;
                state.selected_index = 0;
            }
        }
        false
    }

    /// Navigate up in matches
    #[inline]
    pub fn navigate_up(&mut self) {
        if let Some(ref mut state) = self.state {
            state.selected_index = state.selected_index.saturating_sub(1);
        }
    }

    /// Navigate down in matches
    #[inline]
    pub fn navigate_down(&mut self) {
        if let Some(ref mut state) = self.state {
            let max_idx = state.matches.len().saturating_sub(1);
            state.selected_index = state
                .selected_index
                .min(max_idx)
                .saturating_add(1)
                .min(max_idx);
        }
    }

    /// Get selected match
    #[inline]
    pub fn selected_match(&self) -> Option<&FileMatchData> {
        self.state
            .as_ref()
            .and_then(|s| s.matches.get(s.selected_index))
    }

    /// Get trigger position
    #[inline]
    pub fn trigger_pos(&self) -> Option<usize> {
        self.state.as_ref().map(|s| s.trigger_pos)
    }

    /// Accept selected completion and return the text to insert
    pub fn accept_completion(&mut self) -> Option<String> {
        let selected = self.selected_match()?;

        // Pre-allocate with space for path + space
        let mut result = String::with_capacity(selected.path.len() + 1);
        result.push_str(&selected.path);
        result.push(' ');

        self.state = None;
        Some(result)
    }

    /// Get file matches for query (reuses internal buffer)
    fn get_matches(&mut self, query: &str) -> Vec<FileMatchData> {
        // Clear buffer for reuse
        self.matches_buffer.clear();

        // Scan files and clone to avoid holding borrow
        let files = self.file_finder.scan_files().clone();

        // Filter files (now we don't hold the borrow)
        let matches = self.file_finder.filter_files(&files, query);

        self.matches_buffer
            .extend(matches.into_iter().map(|m| FileMatchData {
                path: m.path.to_string_lossy().to_string(),
                is_dir: m.is_dir,
            }));

        // Clone the buffer to return (matches_buffer is reused next call)
        self.matches_buffer.clone()
    }

    /// Convert to legacy FileAutocompleteState for rendering
    pub fn to_legacy_state(&self) -> Option<crate::tui::FileAutocompleteState> {
        self.state
            .as_ref()
            .map(|s| crate::tui::FileAutocompleteState {
                is_active: s.is_active,
                query: s.query.clone(),
                trigger_pos: s.trigger_pos,
                matches: s.matches.clone(),
                selected_index: s.selected_index,
            })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::env;

    #[test]
    fn test_autocomplete_manager_creation() {
        let dir = env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        let manager = FileAutocompleteManager::new(dir);
        assert!(!manager.is_active());
    }

    #[test]
    fn test_activate_deactivate() {
        let dir = env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        let mut manager = FileAutocompleteManager::new(dir);

        assert!(!manager.is_active());

        manager.activate(0);
        assert!(manager.is_active());

        manager.deactivate();
        assert!(!manager.is_active());
    }

    #[test]
    fn test_navigation() {
        let dir = env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        let mut manager = FileAutocompleteManager::new(dir);

        manager.activate(0);

        manager.navigate_up();
        manager.navigate_down();
    }

    #[test]
    fn test_navigation_with_empty_matches() {
        let dir = env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        let mut manager = FileAutocompleteManager::new(dir);

        manager.activate(0);
        manager.update_query("zzzzzzz_nonexistent_file_xyz");

        manager.navigate_up();
        manager.navigate_down();

        let has_selection = manager.selected_match().is_some();
        let match_count = manager.state().map(|s| s.matches.len()).unwrap_or(0);
        if match_count == 0 {
            assert!(!has_selection, "Should have no selection when no matches");
        }
    }

    #[test]
    fn test_accept_completion() {
        let dir = env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        let mut manager = FileAutocompleteManager::new(dir);

        manager.activate(0);

        if manager.selected_match().is_some() {
            let result = manager.accept_completion();
            assert!(result.is_some());
            assert!(!manager.is_active(), "Should deactivate after accepting");
        }
    }

    #[test]
    fn test_accept_completion_empty() {
        let dir = env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        let mut manager = FileAutocompleteManager::new(dir);

        manager.activate(0);
        manager.update_query("zzzzzzz_nonexistent_file_xyz");

        let result = manager.accept_completion();
        assert!(result.is_none() || !manager.is_active());
    }

    #[test]
    fn test_backspace_states() {
        let dir = env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        let mut manager = FileAutocompleteManager::new(dir);

        let should_close = manager.backspace();
        assert!(!should_close);

        manager.activate(0);

        let should_close = manager.backspace();
        assert!(should_close, "Should close when query is empty");

        manager.append_char('C');
        assert!(
            !manager.backspace(),
            "Should not close when query has content"
        );

        let state = manager.state().unwrap();
        assert_eq!(state.query, "");
    }

    #[test]
    fn test_to_legacy_state() {
        let dir = env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        let manager = FileAutocompleteManager::new(dir);

        assert!(manager.to_legacy_state().is_none());

        let mut manager = manager;
        manager.activate(5);

        let legacy = manager.to_legacy_state();
        assert!(legacy.is_some());

        let legacy = legacy.unwrap();
        assert!(legacy.is_active);
        assert_eq!(legacy.query, "");
        assert_eq!(legacy.trigger_pos, 5);
        assert_eq!(legacy.selected_index, 0);
    }

    #[test]
    fn test_update_query() {
        let dir = env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        let mut manager = FileAutocompleteManager::new(dir);

        manager.activate(0);
        manager.update_query("Cargo");

        let state = manager.state().unwrap();
        assert_eq!(state.query, "Cargo");
        assert_eq!(
            state.selected_index, 0,
            "Should reset selection on query update"
        );
    }

    #[test]
    fn test_trigger_pos() {
        let dir = env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        let mut manager = FileAutocompleteManager::new(dir);

        assert_eq!(manager.trigger_pos(), None);

        manager.activate(10);
        assert_eq!(manager.trigger_pos(), Some(10));

        manager.deactivate();
        assert_eq!(manager.trigger_pos(), None);
    }

    #[test]
    fn test_navigation_bounds() {
        let dir = env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        let mut manager = FileAutocompleteManager::new(dir);

        manager.activate(0);

        let match_count = manager.state().map(|s| s.matches.len()).unwrap_or(0);

        if match_count > 0 {
            manager.navigate_up();
            assert_eq!(manager.state().unwrap().selected_index, 0);

            for _ in 0..match_count {
                manager.navigate_down();
            }

            let final_index = manager.state().unwrap().selected_index;
            assert!(final_index < match_count || match_count == 0);
        }
    }
}