fresh-editor 0.2.25

A lightweight, fast terminal-based text editor with LSP support and TypeScript plugins
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
//! Popup action handlers.
//!
//! This module contains handlers for popup-related actions like confirmation and cancellation.

use super::Editor;
use crate::model::event::Event;
use crate::primitives::snippet::{expand_snippet, is_snippet};
use crate::primitives::word_navigation::find_completion_word_start;
use rust_i18n::t;

/// Result of handling a popup confirmation.
pub enum PopupConfirmResult {
    /// Popup handled, continue normally
    Done,
    /// Popup handled, should return early from handle_action
    EarlyReturn,
}

impl Editor {
    /// Handle PopupConfirm action.
    ///
    /// Returns `PopupConfirmResult` indicating what the caller should do next.
    pub fn handle_popup_confirm(&mut self) -> PopupConfirmResult {
        // Check if this is an LSP status details popup
        if self.pending_lsp_status_popup.is_some() {
            let action_key = self
                .active_state()
                .popups
                .top()
                .and_then(|p| p.selected_item())
                .and_then(|item| item.data.clone());

            self.hide_popup();
            self.pending_lsp_status_popup = None;

            if let Some(key) = action_key {
                self.handle_lsp_status_action(&key);
            }
            return PopupConfirmResult::EarlyReturn;
        }

        // Check if this is an action popup (from plugin showActionPopup)
        if let Some((popup_id, _actions)) = &self.active_action_popup {
            let popup_id = popup_id.clone();
            let action_id = self
                .active_state()
                .popups
                .top()
                .and_then(|p| p.selected_item())
                .and_then(|item| item.data.clone())
                .unwrap_or_else(|| "dismissed".to_string());

            self.hide_popup();
            self.active_action_popup = None;

            // Fire the ActionPopupResult hook
            self.plugin_manager.run_hook(
                "action_popup_result",
                crate::services::plugins::hooks::HookArgs::ActionPopupResult {
                    popup_id,
                    action_id,
                },
            );

            return PopupConfirmResult::EarlyReturn;
        }

        // Check if this is a code action popup
        if self.pending_code_actions.is_some() {
            let selected_index = self
                .active_state()
                .popups
                .top()
                .and_then(|p| p.selected_item())
                .and_then(|item| item.data.as_ref())
                .and_then(|data| data.parse::<usize>().ok());

            self.hide_popup();
            if let Some(index) = selected_index {
                self.execute_code_action(index);
            }
            self.pending_code_actions = None;
            return PopupConfirmResult::EarlyReturn;
        }

        // Check if this is an LSP confirmation popup
        if self.pending_lsp_confirmation.is_some() {
            let action = self
                .active_state()
                .popups
                .top()
                .and_then(|p| p.selected_item())
                .and_then(|item| item.data.clone());
            if let Some(action) = action {
                self.hide_popup();
                self.handle_lsp_confirmation_response(&action);
                return PopupConfirmResult::EarlyReturn;
            }
        }

        // If it's a completion popup, insert the selected item
        let completion_info = self
            .active_state()
            .popups
            .top()
            .filter(|p| p.kind == crate::view::popup::PopupKind::Completion)
            .and_then(|p| p.selected_item())
            .map(|item| (item.text.clone(), item.data.clone()));

        // Perform the completion if we have text
        if let Some((label, insert_text)) = completion_info {
            if let Some(text) = insert_text {
                self.insert_completion_text(text);
            }

            // Apply additional_text_edits (e.g., auto-imports) from the matching CompletionItem
            self.apply_completion_additional_edits(&label);
        }

        self.hide_popup();
        PopupConfirmResult::Done
    }

    /// Insert completion text, replacing the word prefix at cursor.
    /// If the text contains LSP snippet syntax, it will be expanded.
    fn insert_completion_text(&mut self, text: String) {
        // Check if this is a snippet and expand it
        let (insert_text, cursor_offset) = if is_snippet(&text) {
            let expanded = expand_snippet(&text);
            (expanded.text, Some(expanded.cursor_offset))
        } else {
            (text, None)
        };

        let (cursor_id, cursor_pos, word_start) = {
            let cursors = self.active_cursors();
            let cursor_id = cursors.primary_id();
            let cursor_pos = cursors.primary().position;
            let state = self.active_state();
            let word_start = find_completion_word_start(&state.buffer, cursor_pos);
            (cursor_id, cursor_pos, word_start)
        };

        let deleted_text = if word_start < cursor_pos {
            self.active_state_mut()
                .get_text_range(word_start, cursor_pos)
        } else {
            String::new()
        };

        let insert_pos = if word_start < cursor_pos {
            let delete_event = Event::Delete {
                range: word_start..cursor_pos,
                deleted_text,
                cursor_id,
            };

            self.log_and_apply_event(&delete_event);

            let buffer_len = self.active_state().buffer.len();
            word_start.min(buffer_len)
        } else {
            cursor_pos
        };

        let insert_event = Event::Insert {
            position: insert_pos,
            text: insert_text.clone(),
            cursor_id,
        };

        self.log_and_apply_event(&insert_event);

        // If this was a snippet, position cursor at the snippet's $0 location
        if let Some(offset) = cursor_offset {
            let new_cursor_pos = insert_pos + offset;
            // Get current cursor position after the insert
            let current_pos = self.active_cursors().primary().position;
            if current_pos != new_cursor_pos {
                let move_event = Event::MoveCursor {
                    cursor_id,
                    old_position: current_pos,
                    new_position: new_cursor_pos,
                    old_anchor: None,
                    new_anchor: None,
                    old_sticky_column: 0,
                    new_sticky_column: 0,
                };
                let split_id = self.split_manager.active_split();
                let buffer_id = self.active_buffer();
                let state = self.buffers.get_mut(&buffer_id).unwrap();
                let cursors = &mut self.split_view_states.get_mut(&split_id).unwrap().cursors;
                state.apply(cursors, &move_event);
            }
        }
    }

    /// Apply additional_text_edits from the accepted completion item (e.g. auto-imports).
    /// If the item already has additional_text_edits, apply them directly.
    /// If not and the server supports completionItem/resolve, send a resolve request
    /// so the server can fill them in (the response is handled asynchronously).
    fn apply_completion_additional_edits(&mut self, label: &str) {
        // Find the matching CompletionItem from stored items
        let item = self
            .completion_items
            .as_ref()
            .and_then(|items| items.iter().find(|item| item.label == label).cloned());

        let Some(item) = item else { return };

        if let Some(edits) = &item.additional_text_edits {
            if !edits.is_empty() {
                tracing::info!(
                    "Applying {} additional text edits from completion '{}'",
                    edits.len(),
                    label
                );
                let buffer_id = self.active_buffer();
                if let Err(e) = self.apply_lsp_text_edits(buffer_id, edits.clone()) {
                    tracing::error!("Failed to apply completion additional_text_edits: {}", e);
                }
                return;
            }
        }

        // No additional_text_edits present — try resolve if server supports it
        if self.server_supports_completion_resolve() {
            tracing::info!(
                "Completion '{}' has no additional_text_edits, sending completionItem/resolve",
                label
            );
            self.send_completion_resolve(item);
        }
    }

    /// Handle PopupCancel action.
    pub fn handle_popup_cancel(&mut self) {
        tracing::info!(
            "handle_popup_cancel: active_action_popup={:?}",
            self.active_action_popup.as_ref().map(|(id, _)| id)
        );

        // Check if this is an LSP status details popup
        if self.pending_lsp_status_popup.take().is_some() {
            self.hide_popup();
            return;
        }

        // Check if this is an action popup (from plugin showActionPopup)
        if let Some((popup_id, _actions)) = self.active_action_popup.take() {
            tracing::info!(
                "handle_popup_cancel: dismissing action popup id={}",
                popup_id
            );
            self.hide_popup();

            // Fire the ActionPopupResult hook with "dismissed"
            self.plugin_manager.run_hook(
                "action_popup_result",
                crate::services::plugins::hooks::HookArgs::ActionPopupResult {
                    popup_id,
                    action_id: "dismissed".to_string(),
                },
            );
            tracing::info!("handle_popup_cancel: action_popup_result hook fired");
            return;
        }

        if self.pending_code_actions.is_some() {
            self.pending_code_actions = None;
            self.hide_popup();
            return;
        }

        if self.pending_lsp_confirmation.is_some() {
            self.pending_lsp_confirmation = None;
            self.set_status_message(t!("lsp.startup_cancelled_msg").to_string());
        }
        self.hide_popup();
        // Clear completion items when popup is closed
        self.completion_items = None;
    }

    /// Get the formatted key hint for the completion accept action (e.g. "Tab").
    /// Looks up the keybinding for the ConfirmPopup/Tab action in completion context.
    pub(crate) fn completion_accept_key_hint(&self) -> Option<String> {
        // Tab is hardcoded in the completion input handler, so default to "Tab"
        Some("Tab".to_string())
    }

    /// Handle typing a character while completion popup is open.
    /// Inserts the character into the buffer and re-filters the completion list.
    pub fn handle_popup_type_char(&mut self, c: char) {
        // First, insert the character into the buffer
        let (cursor_id, cursor_pos) = {
            let cursors = self.active_cursors();
            (cursors.primary_id(), cursors.primary().position)
        };

        let insert_event = Event::Insert {
            position: cursor_pos,
            text: c.to_string(),
            cursor_id,
        };

        self.log_and_apply_event(&insert_event);

        // Now re-filter the completion list
        self.refilter_completion_popup();
    }

    /// Handle backspace while completion popup is open.
    /// Deletes a character and re-filters the completion list.
    pub fn handle_popup_backspace(&mut self) {
        let (cursor_id, cursor_pos) = {
            let cursors = self.active_cursors();
            (cursors.primary_id(), cursors.primary().position)
        };

        // Don't do anything if at start of buffer
        if cursor_pos == 0 {
            return;
        }

        // Find the previous character boundary
        let prev_pos = {
            let state = self.active_state();
            let text = match state.buffer.to_string() {
                Some(t) => t,
                None => return,
            };
            // Find the previous character
            text[..cursor_pos]
                .char_indices()
                .last()
                .map(|(i, _)| i)
                .unwrap_or(0)
        };

        let deleted_text = self.active_state_mut().get_text_range(prev_pos, cursor_pos);

        let delete_event = Event::Delete {
            range: prev_pos..cursor_pos,
            deleted_text,
            cursor_id,
        };

        self.log_and_apply_event(&delete_event);

        // Now re-filter the completion list
        self.refilter_completion_popup();
    }

    /// Re-filter the completion popup based on current prefix.
    /// If no items match, dismiss the popup.
    fn refilter_completion_popup(&mut self) {
        // Get stored LSP completion items (may be empty if no LSP).
        let lsp_items = self.completion_items.clone().unwrap_or_default();

        // Get current prefix
        let (word_start, cursor_pos) = {
            let cursor_pos = self.active_cursors().primary().position;
            let state = self.active_state();
            let word_start = find_completion_word_start(&state.buffer, cursor_pos);
            (word_start, cursor_pos)
        };

        let prefix = if word_start < cursor_pos {
            self.active_state_mut()
                .get_text_range(word_start, cursor_pos)
                .to_lowercase()
        } else {
            String::new()
        };

        // Filter LSP items
        let filtered_lsp: Vec<&lsp_types::CompletionItem> = if prefix.is_empty() {
            lsp_items.iter().collect()
        } else {
            lsp_items
                .iter()
                .filter(|item| {
                    item.label.to_lowercase().starts_with(&prefix)
                        || item
                            .filter_text
                            .as_ref()
                            .map(|ft| ft.to_lowercase().starts_with(&prefix))
                            .unwrap_or(false)
                })
                .collect()
        };

        // Build combined items: LSP first, then buffer-word results.
        let mut all_popup_items = lsp_items_to_popup_items(&filtered_lsp);
        let buffer_word_items = self.get_buffer_completion_popup_items();
        let lsp_labels: std::collections::HashSet<String> = all_popup_items
            .iter()
            .map(|i| i.text.to_lowercase())
            .collect();
        all_popup_items.extend(
            buffer_word_items
                .into_iter()
                .filter(|item| !lsp_labels.contains(&item.text.to_lowercase())),
        );

        // If no items match from either source, dismiss popup.
        if all_popup_items.is_empty() {
            self.hide_popup();
            self.completion_items = None;
            return;
        }

        // Get current selection to try preserving it
        let current_selection = self
            .active_state()
            .popups
            .top()
            .and_then(|p| p.selected_item())
            .map(|item| item.text.clone());

        // Try to preserve selection
        let selected = current_selection
            .and_then(|sel| all_popup_items.iter().position(|item| item.text == sel))
            .unwrap_or(0);

        let popup_data = build_completion_popup_from_items(all_popup_items, selected);
        let accept_hint = self.completion_accept_key_hint();

        // Close old popup and show new one
        self.hide_popup();
        let buffer_id = self.active_buffer();
        let state = self.buffers.get_mut(&buffer_id).unwrap();
        let mut popup_obj = crate::state::convert_popup_data_to_popup(&popup_data);
        popup_obj.accept_key_hint = accept_hint;
        state.popups.show_or_replace(popup_obj);
    }
}

/// Build a completion popup from a combined list of already-converted items.
///
/// Used when merging LSP results + buffer-word results into a single popup.
pub(crate) fn build_completion_popup_from_items(
    items: Vec<crate::model::event::PopupListItemData>,
    selected: usize,
) -> crate::model::event::PopupData {
    use crate::model::event::{PopupContentData, PopupKindHint, PopupPositionData};

    crate::model::event::PopupData {
        kind: PopupKindHint::Completion,
        title: None,
        description: None,
        transient: false,
        content: PopupContentData::List { items, selected },
        position: PopupPositionData::BelowCursor,
        width: 50,
        max_height: 15,
        bordered: true,
    }
}

/// Convert LSP `CompletionItem`s to `PopupListItemData`s.
pub(crate) fn lsp_items_to_popup_items(
    items: &[&lsp_types::CompletionItem],
) -> Vec<crate::model::event::PopupListItemData> {
    use crate::model::event::PopupListItemData;

    items
        .iter()
        .map(|item| {
            let icon = match item.kind {
                Some(lsp_types::CompletionItemKind::FUNCTION)
                | Some(lsp_types::CompletionItemKind::METHOD) => Some("λ".to_string()),
                Some(lsp_types::CompletionItemKind::VARIABLE) => Some("v".to_string()),
                Some(lsp_types::CompletionItemKind::STRUCT)
                | Some(lsp_types::CompletionItemKind::CLASS) => Some("S".to_string()),
                Some(lsp_types::CompletionItemKind::CONSTANT) => Some("c".to_string()),
                Some(lsp_types::CompletionItemKind::KEYWORD) => Some("k".to_string()),
                _ => None,
            };

            PopupListItemData {
                text: item.label.clone(),
                detail: item.detail.clone(),
                icon,
                data: item
                    .insert_text
                    .clone()
                    .or_else(|| Some(item.label.clone())),
            }
        })
        .collect()
}