mise-interactive-config 2026.6.2

Interactive TOML config editor for mise
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
//! Picker: Fuzzy-searchable list picker UI component

use nucleo_matcher::pattern::{Atom, AtomKind, CaseMatching, Normalization};
use nucleo_matcher::{Config, Matcher, Utf32Str};

/// An item that can be displayed in the picker
#[derive(Debug, Clone)]
pub struct PickerItem {
    /// Display name (used for matching and display)
    pub name: String,
    /// Optional description shown next to the name
    pub description: Option<String>,
    /// Optional data payload (e.g., tool backend info)
    pub data: Option<String>,
}

impl PickerItem {
    /// Create a new picker item
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            description: None,
            data: None,
        }
    }

    /// Add a description
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Add data payload
    #[allow(dead_code)]
    pub fn with_data(mut self, data: impl Into<String>) -> Self {
        self.data = Some(data.into());
        self
    }
}

/// Filtered item with match score for sorting
#[derive(Debug, Clone)]
pub struct FilteredItem {
    /// Index into the original items list
    pub index: usize,
    /// Match score (higher is better)
    pub score: i64,
    /// Matched positions in the name (for highlighting)
    pub positions: Vec<usize>,
}

/// State for the fuzzy picker
pub struct PickerState {
    /// All available items
    items: Vec<PickerItem>,
    /// Filtered items after applying search filter
    filtered: Vec<FilteredItem>,
    /// Current filter text
    filter: String,
    /// Selected index in the filtered list
    cursor: usize,
    /// Scroll offset for the visible window
    scroll_offset: usize,
    /// Height of visible area (number of items)
    visible_height: usize,
    /// Fuzzy matcher instance (created fresh, not stored for Clone/Debug)
    matcher: Matcher,
}

impl std::fmt::Debug for PickerState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PickerState")
            .field("items", &self.items)
            .field("filtered", &self.filtered)
            .field("filter", &self.filter)
            .field("cursor", &self.cursor)
            .field("scroll_offset", &self.scroll_offset)
            .field("visible_height", &self.visible_height)
            .finish_non_exhaustive()
    }
}

impl Clone for PickerState {
    fn clone(&self) -> Self {
        Self {
            items: self.items.clone(),
            filtered: self.filtered.clone(),
            filter: self.filter.clone(),
            cursor: self.cursor,
            scroll_offset: self.scroll_offset,
            visible_height: self.visible_height,
            matcher: Matcher::new(Config::DEFAULT),
        }
    }
}

impl PickerState {
    /// Create a new picker with the given items
    pub fn new(items: Vec<PickerItem>) -> Self {
        let filtered: Vec<FilteredItem> = items
            .iter()
            .enumerate()
            .map(|(i, _)| FilteredItem {
                index: i,
                score: 0,
                positions: Vec::new(),
            })
            .collect();

        Self {
            items,
            filtered,
            filter: String::new(),
            cursor: 0,
            scroll_offset: 0,
            visible_height: 10,
            matcher: Matcher::new(Config::DEFAULT),
        }
    }

    /// Set the visible height
    pub fn with_visible_height(mut self, height: usize) -> Self {
        self.visible_height = height;
        self
    }

    /// Get the current filter text
    pub fn filter(&self) -> &str {
        &self.filter
    }

    /// Get the currently selected item, if any
    pub fn selected(&self) -> Option<&PickerItem> {
        self.filtered.get(self.cursor).map(|f| &self.items[f.index])
    }

    /// Get visible items with their display info
    pub fn visible_items(&self) -> impl Iterator<Item = VisibleItem<'_>> {
        let start = self.scroll_offset;
        let end = (self.scroll_offset + self.visible_height).min(self.filtered.len());

        self.filtered[start..end]
            .iter()
            .enumerate()
            .map(move |(i, filtered)| VisibleItem {
                item: &self.items[filtered.index],
                is_selected: start + i == self.cursor,
                positions: &filtered.positions,
            })
    }

    /// Check if there are more items above the visible area
    pub fn has_more_above(&self) -> bool {
        self.scroll_offset > 0
    }

    /// Check if there are more items below the visible area
    pub fn has_more_below(&self) -> bool {
        self.scroll_offset + self.visible_height < self.filtered.len()
    }

    /// Get the total number of filtered items
    pub fn filtered_count(&self) -> usize {
        self.filtered.len()
    }

    /// Get the total number of items
    #[allow(dead_code)]
    pub fn total_count(&self) -> usize {
        self.items.len()
    }

    /// Add a character to the filter
    pub fn type_char(&mut self, c: char) {
        self.filter.push(c);
        self.apply_filter();
    }

    /// Remove the last character from the filter
    pub fn backspace(&mut self) {
        self.filter.pop();
        self.apply_filter();
    }

    /// Clear the filter
    #[allow(dead_code)]
    pub fn clear_filter(&mut self) {
        self.filter.clear();
        self.apply_filter();
    }

    /// Move cursor up
    pub fn move_up(&mut self) {
        if self.cursor > 0 {
            self.cursor -= 1;
            self.ensure_cursor_visible();
        }
    }

    /// Move cursor down
    pub fn move_down(&mut self) {
        if self.cursor + 1 < self.filtered.len() {
            self.cursor += 1;
            self.ensure_cursor_visible();
        }
    }

    /// Apply the current filter to the items
    fn apply_filter(&mut self) {
        if self.filter.is_empty() {
            // No filter - show all items in original order
            self.filtered = self
                .items
                .iter()
                .enumerate()
                .map(|(i, _)| FilteredItem {
                    index: i,
                    score: 0,
                    positions: Vec::new(),
                })
                .collect();
        } else {
            // Apply fuzzy matching
            let pattern = fuzzy_pattern(&self.filter);
            let mut haystack_buf = Vec::new();
            let filtered = self
                .items
                .iter()
                .enumerate()
                .filter_map(|(i, item)| {
                    // Match against name and description
                    let name_match =
                        fuzzy_indices(&mut self.matcher, &mut haystack_buf, &item.name, &pattern);
                    let desc_match = item.description.as_ref().and_then(|d| {
                        fuzzy_match(&mut self.matcher, &mut haystack_buf, d, &pattern)
                    });

                    // Take the best score
                    match (name_match, desc_match) {
                        (Some((name_score, positions)), Some(desc_score)) => Some(FilteredItem {
                            index: i,
                            score: name_score.max(desc_score),
                            positions,
                        }),
                        (Some((score, positions)), None) => Some(FilteredItem {
                            index: i,
                            score,
                            positions,
                        }),
                        (None, Some(score)) => Some(FilteredItem {
                            index: i,
                            score,
                            positions: Vec::new(),
                        }),
                        (None, None) => None,
                    }
                })
                .collect();
            self.filtered = filtered;

            // Sort by score (highest first)
            self.filtered
                .sort_by_key(|item| std::cmp::Reverse(item.score));
        }

        // Reset cursor to start
        self.cursor = 0;
        self.scroll_offset = 0;
    }

    /// Ensure the cursor is visible in the viewport
    fn ensure_cursor_visible(&mut self) {
        if self.cursor < self.scroll_offset {
            self.scroll_offset = self.cursor;
        } else if self.cursor >= self.scroll_offset + self.visible_height {
            self.scroll_offset = self.cursor.saturating_sub(self.visible_height - 1);
        }
    }
}

fn fuzzy_pattern(needle: &str) -> Atom {
    Atom::new(
        needle,
        CaseMatching::Smart,
        Normalization::Smart,
        AtomKind::Fuzzy,
        false,
    )
}

fn fuzzy_match(
    matcher: &mut Matcher,
    haystack_buf: &mut Vec<char>,
    haystack: &str,
    pattern: &Atom,
) -> Option<i64> {
    pattern
        .score(Utf32Str::new(haystack, haystack_buf), matcher)
        .map(i64::from)
}

fn fuzzy_indices(
    matcher: &mut Matcher,
    haystack_buf: &mut Vec<char>,
    haystack: &str,
    pattern: &Atom,
) -> Option<(i64, Vec<usize>)> {
    let mut indices = Vec::new();
    pattern
        .indices(Utf32Str::new(haystack, haystack_buf), matcher, &mut indices)
        .map(|score| {
            indices.sort_unstable();
            indices.dedup();
            (
                i64::from(score),
                indices.into_iter().map(|index| index as usize).collect(),
            )
        })
}

/// A visible item in the picker with display metadata
#[derive(Debug)]
pub struct VisibleItem<'a> {
    /// The item to display
    pub item: &'a PickerItem,
    /// Whether this item is currently selected
    pub is_selected: bool,
    /// Character positions to highlight (from fuzzy match)
    pub positions: &'a [usize],
}

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

    #[test]
    fn test_picker_basic() {
        let items = vec![
            PickerItem::new("node").with_description("Node.js runtime"),
            PickerItem::new("python").with_description("Python interpreter"),
            PickerItem::new("ruby").with_description("Ruby interpreter"),
        ];

        let picker = PickerState::new(items);
        assert_eq!(picker.filtered_count(), 3);
        assert_eq!(picker.selected().unwrap().name, "node");
    }

    #[test]
    fn test_picker_filter() {
        let items = vec![
            PickerItem::new("node"),
            PickerItem::new("python"),
            PickerItem::new("ruby"),
            PickerItem::new("nodenv"),
        ];

        let mut picker = PickerState::new(items);
        picker.type_char('n');
        picker.type_char('o');
        picker.type_char('d');

        // Should match "node" and "nodenv"
        assert_eq!(picker.filtered_count(), 2);

        // "node" should rank higher (exact prefix match)
        let selected = picker.selected().unwrap();
        assert!(selected.name == "node" || selected.name == "nodenv");
    }

    #[test]
    fn test_picker_navigation() {
        let items = vec![
            PickerItem::new("a"),
            PickerItem::new("b"),
            PickerItem::new("c"),
        ];

        let mut picker = PickerState::new(items);
        assert_eq!(picker.selected().unwrap().name, "a");

        picker.move_down();
        assert_eq!(picker.selected().unwrap().name, "b");

        picker.move_down();
        assert_eq!(picker.selected().unwrap().name, "c");

        picker.move_down(); // Should stay at end
        assert_eq!(picker.selected().unwrap().name, "c");

        picker.move_up();
        assert_eq!(picker.selected().unwrap().name, "b");
    }

    #[test]
    fn test_picker_backspace() {
        let items = vec![PickerItem::new("node"), PickerItem::new("python")];

        let mut picker = PickerState::new(items);
        picker.type_char('p');
        picker.type_char('y');
        assert_eq!(picker.filtered_count(), 1);

        picker.backspace();
        picker.backspace();
        assert_eq!(picker.filtered_count(), 2);
    }
}