Skip to main content

fresh/app/
buffer_management.rs

1//! Buffer management operations for the Editor.
2//!
3//! This module contains all methods related to buffer lifecycle and navigation:
4//! - Opening files (with and without focus)
5//! - Creating new buffers (regular and virtual)
6//! - Closing buffers and tabs
7//! - Switching between buffers
8//! - Navigate back/forward in position history
9//! - Buffer state persistence
10
11use rust_i18n::t;
12use std::collections::HashSet;
13use std::path::Path;
14use std::sync::Arc;
15
16use crate::model::event::{BufferId, Event, LeafId};
17use crate::state::EditorState;
18
19use super::buffer_config_resolve;
20use super::Editor;
21
22impl Editor {
23    /// Resolve the effective line_wrap setting for a buffer, considering language overrides.
24    pub(super) fn resolve_line_wrap_for_buffer(&self, buffer_id: BufferId) -> bool {
25        match self.buffers.get(&buffer_id) {
26            Some(state) => buffer_config_resolve::line_wrap(&state.language, &self.config),
27            None => self.config.editor.line_wrap,
28        }
29    }
30
31    /// Resolve page view settings for a buffer from its language config.
32    pub(super) fn resolve_page_view_for_buffer(
33        &self,
34        buffer_id: BufferId,
35    ) -> Option<Option<usize>> {
36        let state = self.buffers.get(&buffer_id)?;
37        buffer_config_resolve::page_view(&state.language, &self.config)
38    }
39
40    /// Resolve the effective wrap_column for a buffer, considering language overrides.
41    pub(super) fn resolve_wrap_column_for_buffer(&self, buffer_id: BufferId) -> Option<usize> {
42        match self.buffers.get(&buffer_id) {
43            Some(state) => buffer_config_resolve::wrap_column(&state.language, &self.config),
44            None => self.config.editor.wrap_column,
45        }
46    }
47
48    /// Get the preferred split for opening a file.
49    /// If the active split has no label, use it (normal case).
50    /// Otherwise find an unlabeled leaf so files don't open in labeled splits (e.g., sidebars).
51    pub(super) fn preferred_split_for_file(&self) -> LeafId {
52        let active = self.split_manager.active_split();
53        if self.split_manager.get_label(active.into()).is_none() {
54            return active;
55        }
56        self.split_manager.find_unlabeled_leaf().unwrap_or(active)
57    }
58
59    /// Open a file in "preview" (ephemeral) mode and return its buffer ID.
60    ///
61    /// Used for exploratory single-click opens from the file explorer. If the
62    /// `file_explorer.preview_tabs` setting is disabled, this is equivalent to
63    /// `open_file`.
64    ///
65    /// Semantics (see `Editor::preview` for the full invariants):
66    /// - Preview is anchored to a specific split. At most one preview exists
67    ///   editor-wide.
68    /// - If the file is already open (deduped by canonical path, including
69    ///   symlinks and relative paths, by delegating to `open_file_no_focus`),
70    ///   just switch to it. No preview-state changes in either direction.
71    /// - Otherwise, if there's an existing preview in the **same** target
72    ///   split, close it and replace it. If it's in a **different** split,
73    ///   promote it (walking away is commitment) and start a fresh preview
74    ///   in the target split.
75    /// - Skips writing to position history, so a string of exploratory
76    ///   clicks doesn't flood back/forward navigation with stale entries.
77    ///
78    /// TODO(perf): Each preview swap today triggers LSP didClose + didOpen.
79    /// For heavy language servers (rust-analyzer, tsserver) that's wasteful
80    /// on rapid browsing. A future optimization is to keep the LSP session
81    /// for the outgoing buffer until the user commits to the new one.
82    pub fn open_file_preview(&mut self, path: &Path) -> anyhow::Result<BufferId> {
83        // Feature gate — fall back to normal open when preview tabs are off.
84        if !self.config.file_explorer.preview_tabs {
85            return self.open_file(path);
86        }
87
88        // Decide target split up-front. `open_file_no_focus` will target
89        // the same one (it calls `preferred_split_for_file` internally),
90        // so this mirrors its logic. If that invariant ever drifts we'd
91        // open the preview in one split and track it in another.
92        let target_split = self.preferred_split_for_file();
93
94        // Snapshot the buffer IDs that already back a real file, so we can
95        // tell "opened a previously-unknown file" from "switched to one
96        // that was already open". We delegate the symlink/relative-path
97        // dedup to `open_file_no_focus` (which canonicalizes) — any buffer
98        // with a non-empty file path is a candidate match. Note: the
99        // initial empty buffer has a `BufferKind::File` with an empty
100        // `PathBuf`, and we deliberately exclude it here because
101        // `open_file_no_focus` may *repurpose* that buffer (same ID, new
102        // content) for the newly-opened file.
103        let previously_file_backed: HashSet<BufferId> = self
104            .buffers
105            .iter()
106            .filter_map(|(id, state)| {
107                state.buffer.file_path().and_then(|p| {
108                    if p.as_os_str().is_empty() {
109                        None
110                    } else {
111                        Some(*id)
112                    }
113                })
114            })
115            .collect();
116
117        // Route through `open_file` with position-history suppression.
118        // Using the regular `open_file` path keeps all cross-cutting concerns
119        // (LSP, language detection, split targeting, status message, plugin
120        // hooks) consistent with a normal open.
121        self.suppress_position_history_once = true;
122        let open_result = self.open_file(path);
123        self.suppress_position_history_once = false;
124        let buffer_id = open_result?;
125        let is_new = !previously_file_backed.contains(&buffer_id);
126
127        // Already-open buffer: leave preview state untouched. A previously-
128        // committed tab must not be demoted back to preview, and the existing
129        // preview (if any, in whichever split) is still valid.
130        if !is_new {
131            return Ok(buffer_id);
132        }
133
134        // New buffer. Resolve the existing preview (if any) relative to the
135        // target split.
136        match self.preview.take() {
137            Some((prev_split, old_id)) if prev_split == target_split => {
138                // Same split: close the old preview so the new one takes its
139                // place. If close fails (modified buffer — shouldn't happen
140                // because edits promote, but defend in depth), demote the
141                // orphan to a permanent tab rather than leaving behind an
142                // italic "(preview)" tab that will never be replaced.
143                if let Err(e) = self.close_buffer(old_id) {
144                    tracing::warn!(
145                        "preview: could not replace stale preview buffer {:?}, demoting to permanent: {}",
146                        old_id,
147                        e
148                    );
149                    if let Some(m) = self.buffer_metadata.get_mut(&old_id) {
150                        m.is_preview = false;
151                    }
152                }
153            }
154            Some((_other_split, old_id)) => {
155                // Different split: user walked away from the old preview
156                // before this click. Promote it to permanent — their focus
157                // moving to another split was the commitment signal.
158                if let Some(m) = self.buffer_metadata.get_mut(&old_id) {
159                    m.is_preview = false;
160                }
161            }
162            None => {}
163        }
164
165        // Mark the new buffer as the preview, anchored to its split.
166        if let Some(meta) = self.buffer_metadata.get_mut(&buffer_id) {
167            meta.is_preview = true;
168        }
169        self.preview = Some((target_split, buffer_id));
170
171        Ok(buffer_id)
172    }
173
174    /// Promote a specific buffer from preview to permanent, if it was in
175    /// preview mode. No-op if the buffer is not currently a preview.
176    pub(crate) fn promote_buffer_from_preview(&mut self, buffer_id: BufferId) {
177        if let Some(m) = self.buffer_metadata.get_mut(&buffer_id) {
178            m.is_preview = false;
179        }
180        if let Some((_, id)) = self.preview {
181            if id == buffer_id {
182                self.preview = None;
183            }
184        }
185    }
186
187    /// Promote the active buffer from preview to permanent, if applicable.
188    /// Called on any buffer mutation so that touching a preview buffer
189    /// commits it to a permanent tab.
190    pub(crate) fn promote_active_buffer_from_preview(&mut self) {
191        let id = self.active_buffer();
192        self.promote_buffer_from_preview(id);
193    }
194
195    /// Re-point every buffer whose file path sits at or under `old_root`
196    /// to the equivalent location under `new_root`. Returns the ids of
197    /// the buffers that were actually relocated.
198    ///
199    /// Handles three shapes of path change uniformly:
200    ///
201    /// - Single-file rename: `old_root = /a/foo.txt`, `new_root = /a/bar.txt`
202    ///   → the buffer for foo.txt re-points to bar.txt.
203    /// - Directory rename: `old_root = /a/dir`, `new_root = /a/renamed`
204    ///   → every buffer for a file inside `dir` (e.g. `/a/dir/x.txt`)
205    ///   re-points under `/a/renamed` (`/a/renamed/x.txt`).
206    /// - Cut+paste move: `old_root = /a/foo.txt`, `new_root = /b/foo.txt`
207    ///   → the buffer for the moved file re-points to its new home.
208    ///
209    /// For each affected buffer we update the persistence path on the
210    /// Buffer itself, rebuild the `BufferMetadata::kind` (new path + new
211    /// LSP URI), and recompute the display name. Without this, a save
212    /// on the buffer would write to the old (now gone or stale) path
213    /// and silently resurrect / duplicate the file.
214    pub(crate) fn relocate_buffers_for_rename(
215        &mut self,
216        old_root: &std::path::Path,
217        new_root: &std::path::Path,
218    ) -> Vec<BufferId> {
219        let affected = self.buffer_ids_under_path(old_root);
220        for &id in &affected {
221            let Some(state) = self.buffers.get(&id) else {
222                continue;
223            };
224            let Some(current) = state.buffer.file_path().map(|p| p.to_path_buf()) else {
225                continue;
226            };
227            // For buffers equal to old_root, the new path is simply
228            // new_root. For buffers under old_root (directory case),
229            // strip the old prefix and re-root under new_root.
230            let new_path = if current == old_root {
231                new_root.to_path_buf()
232            } else if let Ok(relative) = current.strip_prefix(old_root) {
233                new_root.join(relative)
234            } else {
235                // Defensive: buffer_ids_under_path already filtered, so
236                // this shouldn't happen. Skip rather than corrupt state.
237                continue;
238            };
239
240            if let Some(state) = self.buffers.get_mut(&id) {
241                state.buffer.rename_file_path(new_path.clone());
242            }
243            if let Some(metadata) = self.buffer_metadata.get_mut(&id) {
244                let file_uri = super::types::file_path_to_lsp_uri(&new_path);
245                metadata.kind = super::BufferKind::File {
246                    path: new_path.clone(),
247                    uri: file_uri,
248                };
249                metadata.display_name =
250                    super::BufferMetadata::display_name_for_path(&new_path, &self.working_dir);
251            }
252        }
253        affected
254    }
255
256    /// Promote the current preview, regardless of which buffer it points at.
257    /// Used before layout changes (split, close-split, move-tab) where the
258    /// preview invariant ("anchored to a specific split") would otherwise
259    /// be broken by the operation itself.
260    pub(crate) fn promote_current_preview(&mut self) {
261        if let Some((_, id)) = self.preview.take() {
262            if let Some(m) = self.buffer_metadata.get_mut(&id) {
263                m.is_preview = false;
264            }
265        }
266    }
267
268    /// Promote the current preview if it belongs to a split other than
269    /// `new_split`. Called from split-focus-change paths so that moving
270    /// focus away from the preview's pane commits it.
271    pub(crate) fn promote_preview_if_not_in_split(&mut self, new_split: LeafId) {
272        if let Some((preview_split, _)) = self.preview {
273            if preview_split != new_split {
274                self.promote_current_preview();
275            }
276        }
277    }
278
279    /// Whether the given buffer is currently in preview (ephemeral) mode.
280    /// Primarily for tests; production code should use `self.preview`.
281    pub fn is_buffer_preview(&self, buffer_id: BufferId) -> bool {
282        self.buffer_metadata
283            .get(&buffer_id)
284            .map(|m| m.is_preview)
285            .unwrap_or(false)
286    }
287
288    /// Number of open buffers (including hidden/virtual buffers).
289    /// Intended for tests that verify preview tabs don't accumulate.
290    pub fn open_buffer_count(&self) -> usize {
291        self.buffers.len()
292    }
293
294    /// The (split, buffer) tuple of the current preview tab, if any.
295    /// Intended for tests that verify preview anchoring semantics.
296    pub fn current_preview(&self) -> Option<(LeafId, BufferId)> {
297        self.preview
298    }
299
300    /// Navigate to a specific line and column in the active buffer.
301    ///
302    /// Line and column are 1-indexed (matching typical editor conventions).
303    /// If the line is out of bounds, navigates to the last line.
304    /// If the column is out of bounds, navigates to the end of the line.
305    pub fn goto_line_col(&mut self, line: usize, column: Option<usize>) {
306        if line == 0 {
307            return; // Line numbers are 1-indexed
308        }
309
310        let buffer_id = self.active_buffer();
311
312        // Read cursor state from split view state
313        let cursors = self.active_cursors();
314        let cursor_id = cursors.primary_id();
315        let old_position = cursors.primary().position;
316        let old_anchor = cursors.primary().anchor;
317        let old_sticky_column = cursors.primary().sticky_column;
318
319        if let Some(state) = self.buffers.get(&buffer_id) {
320            let has_line_index = state.buffer.line_count().is_some();
321            let has_line_scan = state.buffer.has_line_feed_scan();
322            let buffer_len = state.buffer.len();
323
324            // Convert 1-indexed line to 0-indexed
325            let target_line = line.saturating_sub(1);
326            // Column is also 1-indexed, convert to 0-indexed
327            let target_col = column.map(|c| c.saturating_sub(1)).unwrap_or(0);
328
329            // Track the known exact line number for scanned large files,
330            // since offset_to_position may not be able to reverse-resolve it accurately.
331            let mut known_line: Option<usize> = None;
332
333            let position = if has_line_scan && has_line_index {
334                // Scanned large file: use tree metadata to find exact line offset
335                let max_line = state.buffer.line_count().unwrap_or(1).saturating_sub(1);
336                let actual_line = target_line.min(max_line);
337                known_line = Some(actual_line);
338                // Need mutable access to potentially read chunk data from disk
339                if let Some(state) = self.buffers.get_mut(&buffer_id) {
340                    state
341                        .buffer
342                        .resolve_line_byte_offset(actual_line)
343                        .map(|offset| (offset + target_col).min(buffer_len))
344                        .unwrap_or(0)
345                } else {
346                    0
347                }
348            } else {
349                // Small file with full line starts or no line index:
350                // use exact line position
351                let max_line = state.buffer.line_count().unwrap_or(1).saturating_sub(1);
352                let actual_line = target_line.min(max_line);
353                state.buffer.line_col_to_position(actual_line, target_col)
354            };
355
356            let event = Event::MoveCursor {
357                cursor_id,
358                old_position,
359                new_position: position,
360                old_anchor,
361                new_anchor: None,
362                old_sticky_column,
363                new_sticky_column: target_col,
364            };
365
366            let split_id = self.split_manager.active_split();
367            let state = self.buffers.get_mut(&buffer_id).unwrap();
368            let view_state = self.split_view_states.get_mut(&split_id).unwrap();
369            state.apply(&mut view_state.cursors, &event);
370
371            // For scanned large files, override the line number with the known exact value
372            // since offset_to_position may fall back to proportional estimation.
373            if let Some(line) = known_line {
374                state.primary_cursor_line_number = crate::model::buffer::LineNumber::Absolute(line);
375            }
376
377            // Center the target line in the viewport. The default
378            // `ensure_visible` behavior only scrolls just enough to reveal
379            // the cursor, which pins a forward jump to the bottom row — and
380            // for live-preview jumps (Quick Open `:N`, Goto Line prompt) the
381            // suggestion/prompt popup overlays the bottom of the screen,
382            // obscuring the very line the user is navigating to. Recentering
383            // puts the target in the middle so it stays visible.
384            self.apply_event_to_active_buffer(&Event::Recenter);
385        }
386    }
387
388    /// Select a range in the active buffer. Lines/columns are 1-indexed.
389    /// The cursor moves to the end of the range and the anchor is set to the
390    /// start, producing a visual selection.
391    pub fn select_range(
392        &mut self,
393        start_line: usize,
394        start_col: Option<usize>,
395        end_line: usize,
396        end_col: Option<usize>,
397    ) {
398        if start_line == 0 || end_line == 0 {
399            return;
400        }
401
402        let buffer_id = self.active_buffer();
403
404        let cursors = self.active_cursors();
405        let cursor_id = cursors.primary_id();
406        let old_position = cursors.primary().position;
407        let old_anchor = cursors.primary().anchor;
408        let old_sticky_column = cursors.primary().sticky_column;
409
410        if let Some(state) = self.buffers.get(&buffer_id) {
411            let buffer_len = state.buffer.len();
412
413            // Convert 1-indexed to 0-indexed
414            let start_line_0 = start_line.saturating_sub(1);
415            let start_col_0 = start_col.map(|c| c.saturating_sub(1)).unwrap_or(0);
416            let end_line_0 = end_line.saturating_sub(1);
417            let end_col_0 = end_col.map(|c| c.saturating_sub(1)).unwrap_or(0);
418
419            let max_line = state.buffer.line_count().unwrap_or(1).saturating_sub(1);
420
421            let start_pos = state
422                .buffer
423                .line_col_to_position(start_line_0.min(max_line), start_col_0)
424                .min(buffer_len);
425            let end_pos = state
426                .buffer
427                .line_col_to_position(end_line_0.min(max_line), end_col_0)
428                .min(buffer_len);
429
430            let event = Event::MoveCursor {
431                cursor_id,
432                old_position,
433                new_position: end_pos,
434                old_anchor,
435                new_anchor: Some(start_pos),
436                old_sticky_column,
437                new_sticky_column: end_col_0,
438            };
439
440            let split_id = self.split_manager.active_split();
441            let state = self.buffers.get_mut(&buffer_id).unwrap();
442            let view_state = self.split_view_states.get_mut(&split_id).unwrap();
443            state.apply(&mut view_state.cursors, &event);
444        }
445    }
446
447    /// Go to an exact byte offset in the buffer (used in byte-offset mode for large files)
448    pub fn goto_byte_offset(&mut self, offset: usize) {
449        let buffer_id = self.active_buffer();
450
451        let cursors = self.active_cursors();
452        let cursor_id = cursors.primary_id();
453        let old_position = cursors.primary().position;
454        let old_anchor = cursors.primary().anchor;
455        let old_sticky_column = cursors.primary().sticky_column;
456
457        if let Some(state) = self.buffers.get(&buffer_id) {
458            let buffer_len = state.buffer.len();
459            let position = offset.min(buffer_len);
460
461            let event = Event::MoveCursor {
462                cursor_id,
463                old_position,
464                new_position: position,
465                old_anchor,
466                new_anchor: None,
467                old_sticky_column,
468                new_sticky_column: 0,
469            };
470
471            let split_id = self.split_manager.active_split();
472            let state = self.buffers.get_mut(&buffer_id).unwrap();
473            let view_state = self.split_view_states.get_mut(&split_id).unwrap();
474            state.apply(&mut view_state.cursors, &event);
475        }
476    }
477
478    /// Create a new empty buffer
479    pub fn new_buffer(&mut self) -> BufferId {
480        // Save current position before switching to new buffer
481        self.position_history.commit_pending_movement();
482
483        // Explicitly record current position before switching
484        let cursors = self.active_cursors();
485        let position = cursors.primary().position;
486        let anchor = cursors.primary().anchor;
487        self.position_history
488            .record_movement(self.active_buffer(), position, anchor);
489        self.position_history.commit_pending_movement();
490
491        let buffer_id = BufferId(self.next_buffer_id);
492        self.next_buffer_id += 1;
493
494        let mut state = EditorState::new(
495            self.terminal_width,
496            self.terminal_height,
497            self.config.editor.large_file_threshold_bytes as usize,
498            Arc::clone(&self.authority.filesystem),
499        );
500        // Note: line_wrap_enabled is set on SplitViewState.viewport when the split is created
501        state
502            .margins
503            .configure_for_line_numbers(self.config.editor.line_numbers);
504        // Set default line ending for new buffers from config
505        state
506            .buffer
507            .set_default_line_ending(self.config.editor.default_line_ending.to_line_ending());
508        self.buffers.insert(buffer_id, state);
509        self.event_logs
510            .insert(buffer_id, crate::model::event::EventLog::new());
511        self.buffer_metadata
512            .insert(buffer_id, crate::app::types::BufferMetadata::new());
513
514        self.set_active_buffer(buffer_id);
515
516        // Initialize per-buffer view state with config defaults.
517        // Must happen AFTER set_active_buffer, because switch_buffer creates
518        // the new BufferViewState with defaults (show_line_numbers=true).
519        let active_split = self.split_manager.active_split();
520        let line_wrap = self.resolve_line_wrap_for_buffer(buffer_id);
521        let wrap_column = self.resolve_wrap_column_for_buffer(buffer_id);
522        if let Some(view_state) = self.split_view_states.get_mut(&active_split) {
523            view_state.apply_config_defaults(
524                self.config.editor.line_numbers,
525                self.config.editor.highlight_current_line,
526                line_wrap,
527                self.config.editor.wrap_indent,
528                wrap_column,
529                self.config.editor.rulers.clone(),
530            );
531        }
532
533        self.status_message = Some(t!("buffer.new").to_string());
534
535        buffer_id
536    }
537
538    /// Get the current mouse hover state for testing
539    /// Returns Some((byte_position, screen_x, screen_y)) if hovering over text
540    pub fn get_mouse_hover_state(&self) -> Option<(usize, u16, u16)> {
541        self.mouse_state
542            .lsp_hover_state
543            .map(|(pos, _, x, y)| (pos, x, y))
544    }
545
546    /// Check if a transient popup (hover/signature help) is currently visible
547    pub fn has_transient_popup(&self) -> bool {
548        self.active_state()
549            .popups
550            .top()
551            .is_some_and(|p| p.transient)
552    }
553
554    /// Force check the mouse hover timer (for testing)
555    /// This bypasses the normal 500ms delay
556    pub fn force_check_mouse_hover(&mut self) -> bool {
557        if let Some((byte_pos, _, screen_x, screen_y)) = self.mouse_state.lsp_hover_state {
558            if !self.mouse_state.lsp_hover_request_sent {
559                self.hover.set_screen_position((screen_x, screen_y));
560                match self.request_hover_at_position(byte_pos) {
561                    Ok(true) => {
562                        self.mouse_state.lsp_hover_request_sent = true;
563                        return true;
564                    }
565                    Ok(false) => return false, // no server ready, retry later
566                    Err(e) => {
567                        tracing::debug!("Failed to request hover: {}", e);
568                        return false;
569                    }
570                }
571            }
572        }
573        false
574    }
575}