Skip to main content

editor_core/
workspace.rs

1//! Workspace and multi-buffer / multi-view model.
2//!
3//! `editor-core` is intentionally UI-agnostic, but a full-featured editor typically needs a
4//! kernel-level model for:
5//!
6//! - managing multiple open buffers (text + undo + derived metadata)
7//! - managing multiple views into the same buffer (split panes)
8//!
9//! This module provides a small [`Workspace`] that owns:
10//! - `BufferId` + `CommandExecutor` (buffer text + undo + derived state)
11//! - `ViewId` + per-view state (selections/cursors, wrap config, scroll)
12//!
13//! The workspace executes commands **against a specific view**. Text edits are applied to the
14//! underlying buffer, and any resulting [`crate::TextDelta`] is broadcast to all views of the
15//! same buffer.
16
17use crate::commands::{
18    AutoPairsConfig, Command, CommandExecutor, CommandResult, CursorCommand, EditCommand,
19    TextEditSpec, UndoHistoryRestoreError, UndoHistorySnapshot,
20};
21use crate::decorations::{Decoration, DecorationLayerId};
22use crate::delta::TextDelta;
23use crate::intervals::FoldRegion;
24use crate::processing::ProcessingEdit;
25use crate::search::{SearchError, SearchMatch, SearchOptions, find_all};
26use crate::selection_set::selection_direction;
27use crate::snippets::SnippetSession;
28use crate::state::CursorState;
29use crate::{AnchorBias, TextAnchor};
30use crate::{
31    IndentationConfig, LineEnding, LineIndex, Position, Selection, SelectionDirection,
32    TabKeyBehavior, ViewCommand,
33};
34use crate::{StateChange, StateChangeCallback, StateChangeType, WrapIndent, WrapMode};
35use std::collections::{BTreeMap, HashMap};
36use std::ops::Range;
37use std::sync::Arc;
38
39/// Opaque identifier for an open buffer in a [`Workspace`].
40#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
41pub struct BufferId(u64);
42
43impl BufferId {
44    /// Create a `BufferId` from a raw numeric id.
45    ///
46    /// This is intended for interoperability boundaries (e.g. FFI) that persist ids externally.
47    pub const fn from_raw(id: u64) -> Self {
48        Self(id)
49    }
50
51    /// Get the underlying numeric id.
52    pub fn get(self) -> u64 {
53        self.0
54    }
55}
56
57/// Opaque identifier for a view into a buffer in a [`Workspace`].
58#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
59pub struct ViewId(u64);
60
61impl ViewId {
62    /// Create a `ViewId` from a raw numeric id.
63    ///
64    /// This is intended for interoperability boundaries (e.g. FFI) that persist ids externally.
65    pub const fn from_raw(id: u64) -> Self {
66        Self(id)
67    }
68
69    /// Get the underlying numeric id.
70    pub fn get(self) -> u64 {
71        self.0
72    }
73}
74
75/// Metadata attached to a workspace buffer.
76#[derive(Debug, Clone)]
77pub struct BufferMetadata {
78    /// Optional buffer URI/path (host-provided).
79    pub uri: Option<String>,
80}
81
82/// Result of opening a buffer (a buffer always starts with a default view).
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub struct OpenBufferResult {
85    /// The created buffer id.
86    pub buffer_id: BufferId,
87    /// The initial view id into that buffer.
88    pub view_id: ViewId,
89}
90
91/// A navigation target produced by jump-list operations.
92#[derive(Debug, Clone, Copy, PartialEq, Eq)]
93pub struct JumpTarget {
94    /// Target buffer id.
95    pub buffer_id: BufferId,
96    /// Target position in logical coordinates.
97    pub position: Position,
98}
99
100#[derive(Debug, Clone, PartialEq, Eq)]
101struct ViewCore {
102    cursor_position: Position,
103    selection: Option<Selection>,
104    secondary_selections: Vec<Selection>,
105    viewport_width: usize,
106    wrap_mode: WrapMode,
107    wrap_indent: WrapIndent,
108    tab_width: usize,
109    tab_key_behavior: TabKeyBehavior,
110    indentation_config: IndentationConfig,
111    auto_pairs: AutoPairsConfig,
112    snippet_session: Option<SnippetSession>,
113    preferred_x_cells: Option<usize>,
114}
115
116impl ViewCore {
117    fn from_executor(executor: &CommandExecutor) -> Self {
118        let editor = executor.editor();
119        Self {
120            cursor_position: editor.cursor_position(),
121            selection: editor.selection().cloned(),
122            secondary_selections: editor.secondary_selections().to_vec(),
123            viewport_width: editor.viewport_width(),
124            wrap_mode: editor.layout_engine().wrap_mode(),
125            wrap_indent: editor.layout_engine().wrap_indent(),
126            tab_width: editor.layout_engine().tab_width(),
127            tab_key_behavior: executor.tab_key_behavior(),
128            indentation_config: executor.indentation_config().clone(),
129            auto_pairs: executor.auto_pairs_config().clone(),
130            snippet_session: executor.snippet_session().cloned(),
131            preferred_x_cells: executor.preferred_x_cells(),
132        }
133    }
134
135    fn apply_to_executor(&self, executor: &mut CommandExecutor) {
136        let mut invalidate_visual_rows = false;
137        let editor = executor.editor_mut();
138        editor.set_cursor_state(
139            self.cursor_position,
140            self.selection.clone(),
141            self.secondary_selections.clone(),
142        );
143
144        if editor.viewport_width() != self.viewport_width {
145            invalidate_visual_rows = true;
146        }
147
148        let before_wrap_mode = editor.layout_engine().wrap_mode();
149        let before_wrap_indent = editor.layout_engine().wrap_indent();
150        let before_tab_width = editor.layout_engine().tab_width();
151        let before_viewport_width = editor.layout_engine().viewport_width();
152        if before_wrap_mode != self.wrap_mode
153            || before_wrap_indent != self.wrap_indent
154            || before_tab_width != self.tab_width
155            || before_viewport_width != self.viewport_width
156        {
157            invalidate_visual_rows = true;
158        }
159
160        if invalidate_visual_rows {
161            editor.set_view_options(
162                self.viewport_width,
163                self.wrap_mode,
164                self.wrap_indent,
165                self.tab_width,
166            );
167        }
168
169        executor.set_tab_key_behavior(self.tab_key_behavior);
170        executor.set_indentation_config(self.indentation_config.clone());
171        executor.set_auto_pairs_config(self.auto_pairs.clone());
172        executor.set_snippet_session(self.snippet_session.clone());
173        executor.set_preferred_x_cells(self.preferred_x_cells);
174    }
175}
176
177struct BufferEntry {
178    meta: BufferMetadata,
179    executor: CommandExecutor,
180    version: u64,
181    last_text_delta: Option<Arc<TextDelta>>,
182    bookmarks: BookmarkSet,
183    marks: MarkSet,
184    /// Deterministic baseline view config for new views into this buffer.
185    ///
186    /// Captured once from the buffer's initial executor state, so `create_view` does not inherit
187    /// whichever view most recently loaded its scratch state into the shared executor (which would
188    /// make new views' config depend on call order).
189    default_view_core: ViewCore,
190}
191
192struct ViewEntry {
193    buffer: BufferId,
194    core: ViewCore,
195    version: u64,
196    callbacks: Vec<StateChangeCallback>,
197    scroll_top: usize,
198    scroll_sub_row_offset: u16,
199    overscan_rows: usize,
200    viewport_height: Option<usize>,
201    last_text_delta: Option<Arc<TextDelta>>,
202    jump_list: JumpList,
203}
204
205/// Workspace-level errors.
206#[derive(Debug, Clone, PartialEq, Eq)]
207pub enum WorkspaceError {
208    /// A buffer with this uri already exists.
209    UriAlreadyOpen(String),
210    /// A buffer id was not found.
211    BufferNotFound(BufferId),
212    /// A view id was not found.
213    ViewNotFound(ViewId),
214    /// Executing a command failed.
215    CommandFailed {
216        /// Target view id.
217        view: ViewId,
218        /// Error message.
219        message: String,
220    },
221    /// Applying edits to a buffer failed.
222    ApplyEditsFailed {
223        /// Target buffer id.
224        buffer: BufferId,
225        /// Error message.
226        message: String,
227    },
228}
229
230/// Errors produced when restoring undo history for a workspace buffer.
231#[derive(Debug, Clone, PartialEq, Eq)]
232pub enum WorkspaceUndoHistoryRestoreError {
233    /// A buffer id was not found.
234    BufferNotFound(BufferId),
235    /// Restoring the undo history failed (corrupt snapshot or version mismatch).
236    RestoreFailed {
237        /// Target buffer id.
238        buffer: BufferId,
239        /// Underlying restore error.
240        error: UndoHistoryRestoreError,
241    },
242}
243
244impl std::fmt::Display for WorkspaceUndoHistoryRestoreError {
245    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
246        match self {
247            Self::BufferNotFound(id) => write!(f, "Buffer not found (id={})", id.get()),
248            Self::RestoreFailed { buffer, error } => {
249                write!(
250                    f,
251                    "Restore undo history failed (buffer={}): {}",
252                    buffer.get(),
253                    error
254                )
255            }
256        }
257    }
258}
259
260impl std::error::Error for WorkspaceUndoHistoryRestoreError {}
261
262/// Search matches for a single open buffer in a [`Workspace`].
263#[derive(Debug, Clone, PartialEq, Eq)]
264pub struct WorkspaceSearchResult {
265    /// Buffer id.
266    pub id: BufferId,
267    /// Optional URI/path metadata.
268    pub uri: Option<String>,
269    /// All matches in this buffer (character offsets, half-open).
270    pub matches: Vec<SearchMatch>,
271}
272
273/// Smooth-scrolling state for a view.
274#[derive(Debug, Clone, Copy, PartialEq, Eq)]
275pub struct ViewSmoothScrollState {
276    /// Top visual row anchor.
277    pub top_visual_row: usize,
278    /// Sub-row offset within `top_visual_row` (0..=65535, normalized).
279    pub sub_row_offset: u16,
280    /// Overscan rows for prefetching.
281    pub overscan_rows: usize,
282}
283
284/// Viewport state for a workspace view, including visual totals and smooth-scrolling metadata.
285#[derive(Debug, Clone, PartialEq, Eq)]
286pub struct WorkspaceViewportState {
287    /// Viewport width (in cells).
288    pub width: usize,
289    /// Viewport height (line count, host-provided).
290    pub height: Option<usize>,
291    /// Current top visual row.
292    pub scroll_top: usize,
293    /// Visible visual range.
294    pub visible_lines: Range<usize>,
295    /// Total visual line count under current view config (wrap + folding aware).
296    pub total_visual_lines: usize,
297    /// Smooth-scroll metadata.
298    pub smooth_scroll: ViewSmoothScrollState,
299    /// Recommended prefetch range using overscan rows.
300    pub prefetch_lines: Range<usize>,
301}
302
303fn apply_char_offset_delta(mut offset: usize, delta: &TextDelta) -> usize {
304    for edit in &delta.edits {
305        let start = edit.start;
306        let end = edit.end();
307        let deleted_len = edit.deleted_len();
308        let inserted_len = edit.inserted_len();
309
310        if offset < start {
311            continue;
312        }
313
314        if offset < end {
315            // If the caret was inside the replaced range, anchor it at the end of the inserted text.
316            offset = start.saturating_add(inserted_len);
317            continue;
318        }
319
320        // After the replaced range: shift by the net length delta.
321        if inserted_len >= deleted_len {
322            offset = offset.saturating_add(inserted_len - deleted_len);
323        } else {
324            offset = offset.saturating_sub(deleted_len - inserted_len);
325        }
326    }
327
328    offset
329}
330
331fn apply_position_delta(
332    old_index: &LineIndex,
333    new_index: &LineIndex,
334    pos: Position,
335    delta: &TextDelta,
336) -> Position {
337    let before = old_index.position_to_char_offset(pos.line, pos.column);
338    let after = apply_char_offset_delta(before, delta);
339    let (line, column) = new_index.char_offset_to_position(after);
340    Position::new(line, column)
341}
342
343fn apply_selection_delta(
344    old_index: &LineIndex,
345    new_index: &LineIndex,
346    selection: &Selection,
347    delta: &TextDelta,
348) -> Selection {
349    let start = apply_position_delta(old_index, new_index, selection.start, delta);
350    let end = apply_position_delta(old_index, new_index, selection.end, delta);
351    Selection {
352        start,
353        end,
354        direction: selection_direction(start, end),
355    }
356}
357
358/// Coalesce a freshly produced delta into a slot that may still hold a previously produced but
359/// not-yet-consumed delta.
360///
361/// A consumer that only reads the latest stored delta (e.g. LSP incremental sync, search anchor
362/// shifting) would otherwise lose the earlier edit when two edits happen between consumptions.
363/// Merging keeps the slot equivalent to "all edits since the last take".
364fn coalesce_delta_slot(slot: &mut Option<Arc<TextDelta>>, next: &Arc<TextDelta>) {
365    *slot = Some(match slot.take() {
366        Some(existing) => Arc::new(TextDelta::merge(&existing, next)),
367        None => next.clone(),
368    });
369}
370
371#[derive(Debug, Default, Clone, PartialEq, Eq)]
372struct BookmarkSet {
373    anchors: Vec<TextAnchor>,
374}
375
376impl BookmarkSet {
377    fn toggle_line_start(&mut self, line_start_offset: usize) -> bool {
378        let anchor = TextAnchor::new(line_start_offset, AnchorBias::Left);
379        match self
380            .anchors
381            .binary_search_by_key(&anchor.offset, |a| a.offset)
382        {
383            Ok(idx) => {
384                self.anchors.remove(idx);
385                false
386            }
387            Err(idx) => {
388                self.anchors.insert(idx, anchor);
389                true
390            }
391        }
392    }
393
394    fn clear(&mut self) {
395        self.anchors.clear();
396    }
397
398    fn apply_delta(&mut self, delta: &TextDelta) {
399        for a in &mut self.anchors {
400            a.apply_delta(delta);
401        }
402        self.anchors.sort_by_key(|a| a.offset);
403        self.anchors.dedup_by_key(|a| a.offset);
404    }
405
406    fn line_numbers(&self, line_index: &LineIndex) -> Vec<usize> {
407        let mut lines: Vec<usize> = self
408            .anchors
409            .iter()
410            .map(|a| line_index.char_offset_to_position(a.offset).0)
411            .collect();
412        lines.sort_unstable();
413        lines.dedup();
414        lines
415    }
416
417    fn next_after_line_start(&self, current_line_start: usize) -> Option<TextAnchor> {
418        self.anchors
419            .iter()
420            .copied()
421            .find(|a| a.offset > current_line_start)
422            .or_else(|| self.anchors.first().copied())
423    }
424
425    fn prev_before_line_start(&self, current_line_start: usize) -> Option<TextAnchor> {
426        self.anchors
427            .iter()
428            .copied()
429            .rfind(|a| a.offset < current_line_start)
430            .or_else(|| self.anchors.last().copied())
431    }
432}
433
434#[derive(Debug, Default, Clone, PartialEq, Eq)]
435struct MarkSet {
436    marks: BTreeMap<String, TextAnchor>,
437}
438
439impl MarkSet {
440    fn set(&mut self, name: String, offset: usize) {
441        self.marks
442            .insert(name, TextAnchor::new(offset, AnchorBias::Right));
443    }
444
445    fn get(&self, name: &str) -> Option<TextAnchor> {
446        self.marks.get(name).copied()
447    }
448
449    fn remove(&mut self, name: &str) -> bool {
450        self.marks.remove(name).is_some()
451    }
452
453    fn clear(&mut self) {
454        self.marks.clear();
455    }
456
457    fn names(&self) -> Vec<String> {
458        self.marks.keys().cloned().collect()
459    }
460
461    fn apply_delta(&mut self, delta: &TextDelta) {
462        for anchor in self.marks.values_mut() {
463            anchor.apply_delta(delta);
464        }
465    }
466}
467
468#[derive(Debug, Clone, Copy, PartialEq, Eq)]
469struct JumpEntry {
470    buffer_id: BufferId,
471    anchor: TextAnchor,
472}
473
474#[derive(Debug, Default, Clone, PartialEq, Eq)]
475struct JumpList {
476    back: Vec<JumpEntry>,
477    forward: Vec<JumpEntry>,
478    max_len: usize,
479}
480
481impl JumpList {
482    fn new(max_len: usize) -> Self {
483        Self {
484            back: Vec::new(),
485            forward: Vec::new(),
486            max_len: max_len.max(1),
487        }
488    }
489
490    fn record(&mut self, entry: JumpEntry) {
491        if self.back.last().is_some_and(|last| *last == entry) {
492            return;
493        }
494
495        self.back.push(entry);
496        self.forward.clear();
497
498        if self.back.len() > self.max_len {
499            let overflow = self.back.len() - self.max_len;
500            self.back.drain(0..overflow);
501        }
502    }
503
504    fn back(&mut self, current: JumpEntry) -> Option<JumpEntry> {
505        let target = self.back.pop()?;
506        if !self.forward.last().is_some_and(|last| *last == current) {
507            self.forward.push(current);
508        }
509        Some(target)
510    }
511
512    fn forward(&mut self, current: JumpEntry) -> Option<JumpEntry> {
513        let target = self.forward.pop()?;
514        if !self.back.last().is_some_and(|last| *last == current) {
515            self.back.push(current);
516        }
517        Some(target)
518    }
519
520    fn clear(&mut self) {
521        self.back.clear();
522        self.forward.clear();
523    }
524
525    fn apply_delta(&mut self, buffer_id: BufferId, delta: &TextDelta) {
526        for entry in self
527            .back
528            .iter_mut()
529            .chain(self.forward.iter_mut())
530            .filter(|e| e.buffer_id == buffer_id)
531        {
532            entry.anchor.apply_delta(delta);
533        }
534    }
535}
536
537/// A collection of open buffers and their views.
538#[derive(Default)]
539pub struct Workspace {
540    next_buffer_id: u64,
541    buffers: BTreeMap<BufferId, BufferEntry>,
542    uri_to_buffer: HashMap<String, BufferId>,
543
544    next_view_id: u64,
545    views: BTreeMap<ViewId, ViewEntry>,
546    active_view: Option<ViewId>,
547
548    intelligence: crate::WorkspaceIntelligence,
549}
550
551impl std::fmt::Debug for Workspace {
552    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
553        f.debug_struct("Workspace")
554            .field("buffer_count", &self.buffers.len())
555            .field("view_count", &self.views.len())
556            .field("uri_count", &self.uri_to_buffer.len())
557            .field("active_view", &self.active_view)
558            .field("intelligence_set_count", &self.intelligence.len())
559            .finish()
560    }
561}
562
563impl Workspace {
564    /// Create an empty workspace.
565    pub fn new() -> Self {
566        Self::default()
567    }
568
569    /// Returns the number of open buffers.
570    pub fn len(&self) -> usize {
571        self.buffers.len()
572    }
573
574    /// Returns `true` if there are no open buffers.
575    pub fn is_empty(&self) -> bool {
576        self.buffers.is_empty()
577    }
578
579    /// Returns the number of open views.
580    pub fn view_count(&self) -> usize {
581        self.views.len()
582    }
583
584    /// Return the active view id (if any).
585    pub fn active_view_id(&self) -> Option<ViewId> {
586        self.active_view
587    }
588
589    /// Return the active buffer id (if any).
590    pub fn active_buffer_id(&self) -> Option<BufferId> {
591        let view_id = self.active_view?;
592        self.views.get(&view_id).map(|v| v.buffer)
593    }
594
595    /// Read workspace-scoped language intelligence result sets (references/call hierarchy/etc.).
596    pub fn intelligence(&self) -> &crate::WorkspaceIntelligence {
597        &self.intelligence
598    }
599
600    /// Mutate workspace-scoped language intelligence result sets (references/call hierarchy/etc.).
601    pub fn intelligence_mut(&mut self) -> &mut crate::WorkspaceIntelligence {
602        &mut self.intelligence
603    }
604
605    /// Set the active view.
606    pub fn set_active_view(&mut self, id: ViewId) -> Result<(), WorkspaceError> {
607        if !self.views.contains_key(&id) {
608            return Err(WorkspaceError::ViewNotFound(id));
609        }
610        self.active_view = Some(id);
611        Ok(())
612    }
613
614    /// Open a new buffer in the workspace, creating an initial view.
615    ///
616    /// - `uri` is optional and host-provided (e.g. `file:///...`).
617    /// - `text` is the initial contents.
618    /// - `viewport_width` is the initial view's wrap width.
619    pub fn open_buffer(
620        &mut self,
621        uri: Option<String>,
622        text: &str,
623        viewport_width: usize,
624    ) -> Result<OpenBufferResult, WorkspaceError> {
625        if let Some(uri) = uri.as_ref()
626            && self.uri_to_buffer.contains_key(uri)
627        {
628            return Err(WorkspaceError::UriAlreadyOpen(uri.clone()));
629        }
630
631        let buffer_id = BufferId(self.next_buffer_id);
632        self.next_buffer_id = self.next_buffer_id.saturating_add(1);
633
634        let executor = CommandExecutor::new(text, viewport_width);
635        // Capture the pristine view config now, before any command mutates the shared executor.
636        let default_view_core = ViewCore::from_executor(&executor);
637        let meta = BufferMetadata { uri: uri.clone() };
638        self.buffers.insert(
639            buffer_id,
640            BufferEntry {
641                meta,
642                executor,
643                version: 0,
644                last_text_delta: None,
645                bookmarks: BookmarkSet::default(),
646                marks: MarkSet::default(),
647                default_view_core,
648            },
649        );
650
651        if let Some(uri) = uri {
652            self.uri_to_buffer.insert(uri, buffer_id);
653        }
654
655        let view_id = self.create_view(buffer_id, viewport_width)?;
656
657        if self.active_view.is_none() {
658            self.active_view = Some(view_id);
659        }
660
661        Ok(OpenBufferResult { buffer_id, view_id })
662    }
663
664    /// Close a buffer (and all its views).
665    pub fn close_buffer(&mut self, id: BufferId) -> Result<(), WorkspaceError> {
666        let Some(entry) = self.buffers.remove(&id) else {
667            return Err(WorkspaceError::BufferNotFound(id));
668        };
669
670        if let Some(uri) = entry.meta.uri.as_ref() {
671            self.uri_to_buffer.remove(uri);
672        }
673
674        let views_to_remove: Vec<ViewId> = self
675            .views
676            .iter()
677            .filter_map(|(vid, v)| if v.buffer == id { Some(*vid) } else { None })
678            .collect();
679        for view_id in views_to_remove {
680            self.views.remove(&view_id);
681        }
682
683        if self
684            .active_view
685            .is_some_and(|active| !self.views.contains_key(&active))
686        {
687            self.active_view = self.views.keys().next().copied();
688        }
689
690        Ok(())
691    }
692
693    /// Close a view. If it was the last view of its buffer, the buffer is also closed.
694    pub fn close_view(&mut self, id: ViewId) -> Result<(), WorkspaceError> {
695        let Some(view) = self.views.remove(&id) else {
696            return Err(WorkspaceError::ViewNotFound(id));
697        };
698
699        if self.active_view == Some(id) {
700            self.active_view = self.views.keys().next().copied();
701        }
702
703        let still_has_views = self.views.values().any(|v| v.buffer == view.buffer);
704        if !still_has_views {
705            self.close_buffer(view.buffer)?;
706        }
707
708        Ok(())
709    }
710
711    /// Return all open buffer ids in deterministic order.
712    pub fn buffer_ids(&self) -> Vec<BufferId> {
713        let mut ids: Vec<BufferId> = self.buffers.keys().copied().collect();
714        ids.sort_by_key(|id| id.get());
715        ids
716    }
717
718    /// Return all open view ids in deterministic order.
719    pub fn view_ids(&self) -> Vec<ViewId> {
720        let mut ids: Vec<ViewId> = self.views.keys().copied().collect();
721        ids.sort_by_key(|id| id.get());
722        ids
723    }
724
725    /// Create a new view into an existing buffer.
726    ///
727    /// The new view starts from the buffer's deterministic default view config (see
728    /// [`BufferEntry::default_view_core`]) — independent of which view most recently executed a
729    /// command. To clone another view's config instead, use [`Workspace::create_view_from`].
730    pub fn create_view(
731        &mut self,
732        buffer: BufferId,
733        viewport_width: usize,
734    ) -> Result<ViewId, WorkspaceError> {
735        let Some(buffer_entry) = self.buffers.get(&buffer) else {
736            return Err(WorkspaceError::BufferNotFound(buffer));
737        };
738        let core = buffer_entry.default_view_core.clone();
739        Ok(self.insert_view_with_core(buffer, core, viewport_width))
740    }
741
742    /// Create a new view into the same buffer as `parent_view`, cloning that view's view-local
743    /// config (wrap mode, tab width, indentation, auto-pairs, …) but with an independent
744    /// cursor/selection and its own viewport width.
745    ///
746    /// This is the explicit "split / clone this view" operation, with predictable config
747    /// provenance (unlike deriving from shared executor scratch state).
748    pub fn create_view_from(
749        &mut self,
750        parent_view: ViewId,
751        viewport_width: usize,
752    ) -> Result<ViewId, WorkspaceError> {
753        let Some(parent) = self.views.get(&parent_view) else {
754            return Err(WorkspaceError::ViewNotFound(parent_view));
755        };
756        let buffer = parent.buffer;
757        let core = parent.core.clone();
758        Ok(self.insert_view_with_core(buffer, core, viewport_width))
759    }
760
761    /// Insert a new view for `buffer` from a base `ViewCore`, resetting cursor/selection/scroll and
762    /// applying `viewport_width`.
763    fn insert_view_with_core(
764        &mut self,
765        buffer: BufferId,
766        mut core: ViewCore,
767        viewport_width: usize,
768    ) -> ViewId {
769        core.cursor_position = Position::new(0, 0);
770        core.selection = None;
771        core.secondary_selections.clear();
772        core.snippet_session = None;
773        core.viewport_width = viewport_width.max(1);
774        core.preferred_x_cells = None;
775
776        let view_id = ViewId(self.next_view_id);
777        self.next_view_id = self.next_view_id.saturating_add(1);
778
779        self.views.insert(
780            view_id,
781            ViewEntry {
782                buffer,
783                core,
784                version: 0,
785                callbacks: Vec::new(),
786                scroll_top: 0,
787                scroll_sub_row_offset: 0,
788                overscan_rows: 0,
789                viewport_height: None,
790                last_text_delta: None,
791                jump_list: JumpList::new(200),
792            },
793        );
794
795        view_id
796    }
797
798    /// Look up a buffer by uri.
799    pub fn buffer_id_for_uri(&self, uri: &str) -> Option<BufferId> {
800        self.uri_to_buffer.get(uri).copied()
801    }
802
803    /// Get a reference to a buffer's line index (logical line/column <-> char offsets).
804    pub fn buffer_line_index(&self, buffer_id: BufferId) -> Result<&LineIndex, WorkspaceError> {
805        let Some(buffer) = self.buffers.get(&buffer_id) else {
806            return Err(WorkspaceError::BufferNotFound(buffer_id));
807        };
808        Ok(buffer.executor.editor().line_index())
809    }
810
811    /// Get the document length for a buffer in Unicode scalar values (Rust `char`s).
812    pub fn buffer_char_count(&self, buffer_id: BufferId) -> Result<usize, WorkspaceError> {
813        let Some(buffer) = self.buffers.get(&buffer_id) else {
814            return Err(WorkspaceError::BufferNotFound(buffer_id));
815        };
816        Ok(buffer.executor.editor().char_count())
817    }
818
819    /// Get a slice of the buffer text as a `String` by character offset + length.
820    ///
821    /// Notes:
822    /// - `start` and `len` are in Unicode scalar indices (Rust `char`s), not bytes.
823    /// - Out-of-bounds ranges are clamped by the underlying text buffer.
824    pub fn buffer_text_range(
825        &self,
826        buffer_id: BufferId,
827        start: usize,
828        len: usize,
829    ) -> Result<String, WorkspaceError> {
830        let Some(buffer) = self.buffers.get(&buffer_id) else {
831            return Err(WorkspaceError::BufferNotFound(buffer_id));
832        };
833        Ok(buffer.executor.editor().text_range(start, len))
834    }
835
836    /// Get all decoration layers for a buffer.
837    pub fn buffer_decorations(
838        &self,
839        buffer_id: BufferId,
840    ) -> Result<&BTreeMap<DecorationLayerId, Vec<Decoration>>, WorkspaceError> {
841        let Some(buffer) = self.buffers.get(&buffer_id) else {
842            return Err(WorkspaceError::BufferNotFound(buffer_id));
843        };
844        Ok(buffer.executor.editor().decorations())
845    }
846
847    /// Get the current folding regions for a buffer (user folds + derived folds).
848    pub fn folding_regions_for_buffer(
849        &self,
850        buffer_id: BufferId,
851    ) -> Result<Vec<FoldRegion>, WorkspaceError> {
852        let Some(buffer) = self.buffers.get(&buffer_id) else {
853            return Err(WorkspaceError::BufferNotFound(buffer_id));
854        };
855        Ok(buffer
856            .executor
857            .editor()
858            .folding_manager()
859            .regions()
860            .to_vec())
861    }
862
863    /// Returns whether a buffer has unsaved text edits.
864    ///
865    /// Notes:
866    /// - This tracks the executor's "clean point" (usually the last `mark_saved_*` call),
867    ///   and is restored by undoing back to that clean point.
868    pub fn buffer_is_modified(&self, buffer_id: BufferId) -> Result<bool, WorkspaceError> {
869        let Some(buffer) = self.buffers.get(&buffer_id) else {
870            return Err(WorkspaceError::BufferNotFound(buffer_id));
871        };
872        Ok(!buffer.executor.is_clean())
873    }
874
875    /// Return the preferred line ending for saving this buffer.
876    pub fn line_ending_for_buffer(
877        &self,
878        buffer_id: BufferId,
879    ) -> Result<LineEnding, WorkspaceError> {
880        let Some(buffer) = self.buffers.get(&buffer_id) else {
881            return Err(WorkspaceError::BufferNotFound(buffer_id));
882        };
883        Ok(buffer.executor.line_ending())
884    }
885
886    /// Override the preferred line ending for saving this buffer.
887    pub fn set_line_ending_for_buffer(
888        &mut self,
889        buffer_id: BufferId,
890        line_ending: LineEnding,
891    ) -> Result<(), WorkspaceError> {
892        let Some(buffer) = self.buffers.get_mut(&buffer_id) else {
893            return Err(WorkspaceError::BufferNotFound(buffer_id));
894        };
895        buffer.executor.set_line_ending(line_ending);
896        Ok(())
897    }
898
899    /// Returns whether the view's underlying buffer has unsaved text edits.
900    pub fn is_modified_for_view(&self, view_id: ViewId) -> Result<bool, WorkspaceError> {
901        let buffer_id = self.buffer_id_for_view(view_id)?;
902        self.buffer_is_modified(buffer_id)
903    }
904
905    /// Return the preferred line ending for saving this view's underlying buffer.
906    pub fn line_ending_for_view(&self, view_id: ViewId) -> Result<LineEnding, WorkspaceError> {
907        let buffer_id = self.buffer_id_for_view(view_id)?;
908        self.line_ending_for_buffer(buffer_id)
909    }
910
911    /// Override the preferred line ending for saving this view's underlying buffer.
912    pub fn set_line_ending_for_view(
913        &mut self,
914        view_id: ViewId,
915        line_ending: LineEnding,
916    ) -> Result<(), WorkspaceError> {
917        let buffer_id = self.buffer_id_for_view(view_id)?;
918        self.set_line_ending_for_buffer(buffer_id, line_ending)
919    }
920
921    /// Mark the current state of a buffer as saved (clean point).
922    pub fn mark_saved_for_buffer(&mut self, buffer_id: BufferId) -> Result<(), WorkspaceError> {
923        let Some(buffer) = self.buffers.get_mut(&buffer_id) else {
924            return Err(WorkspaceError::BufferNotFound(buffer_id));
925        };
926        buffer.executor.mark_clean();
927        Ok(())
928    }
929
930    /// Mark the current state of a view's buffer as saved (clean point).
931    pub fn mark_saved_for_view(&mut self, view_id: ViewId) -> Result<(), WorkspaceError> {
932        let buffer_id = self.buffer_id_for_view(view_id)?;
933        self.mark_saved_for_buffer(buffer_id)
934    }
935
936    /// Capture a persistable snapshot of a buffer's undo/redo history.
937    pub fn undo_history_snapshot_for_buffer(
938        &self,
939        buffer_id: BufferId,
940    ) -> Result<UndoHistorySnapshot, WorkspaceError> {
941        let Some(buffer) = self.buffers.get(&buffer_id) else {
942            return Err(WorkspaceError::BufferNotFound(buffer_id));
943        };
944        Ok(buffer.executor.undo_history_snapshot())
945    }
946
947    /// Restore a buffer's undo/redo history from a previously captured snapshot.
948    ///
949    /// Notes:
950    /// - This does **not** modify the current buffer text.
951    /// - Callers should only restore a snapshot into the **same text** it was captured from.
952    pub fn restore_undo_history_for_buffer(
953        &mut self,
954        buffer_id: BufferId,
955        snapshot: UndoHistorySnapshot,
956    ) -> Result<(), WorkspaceUndoHistoryRestoreError> {
957        let Some(buffer) = self.buffers.get_mut(&buffer_id) else {
958            return Err(WorkspaceUndoHistoryRestoreError::BufferNotFound(buffer_id));
959        };
960
961        buffer.last_text_delta = None;
962        for view in self.views.values_mut() {
963            if view.buffer == buffer_id {
964                view.last_text_delta = None;
965            }
966        }
967
968        buffer
969            .executor
970            .restore_undo_history(snapshot)
971            .map_err(|err| WorkspaceUndoHistoryRestoreError::RestoreFailed {
972                buffer: buffer_id,
973                error: err,
974            })?;
975
976        Ok(())
977    }
978
979    /// Get a buffer's metadata.
980    pub fn buffer_metadata(&self, id: BufferId) -> Option<&BufferMetadata> {
981        self.buffers.get(&id).map(|e| &e.meta)
982    }
983
984    /// Get the buffer id that a view is pointing at.
985    pub fn buffer_id_for_view(&self, id: ViewId) -> Result<BufferId, WorkspaceError> {
986        self.views
987            .get(&id)
988            .map(|v| v.buffer)
989            .ok_or(WorkspaceError::ViewNotFound(id))
990    }
991
992    /// Get the primary cursor position for a view.
993    pub fn cursor_position_for_view(&self, id: ViewId) -> Result<Position, WorkspaceError> {
994        self.views
995            .get(&id)
996            .map(|v| v.core.cursor_position)
997            .ok_or(WorkspaceError::ViewNotFound(id))
998    }
999
1000    /// Get the primary selection for a view (None means "empty selection / caret only").
1001    pub fn selection_for_view(&self, id: ViewId) -> Result<Option<Selection>, WorkspaceError> {
1002        self.views
1003            .get(&id)
1004            .map(|v| v.core.selection.clone())
1005            .ok_or(WorkspaceError::ViewNotFound(id))
1006    }
1007
1008    /// Get the current tab width setting for a view (in monospace cells).
1009    pub fn tab_width_for_view(&self, id: ViewId) -> Result<usize, WorkspaceError> {
1010        self.views
1011            .get(&id)
1012            .map(|v| v.core.tab_width)
1013            .ok_or(WorkspaceError::ViewNotFound(id))
1014    }
1015
1016    /// Get the current viewport width setting for a view (in monospace cells).
1017    pub fn viewport_width_for_view(&self, id: ViewId) -> Result<usize, WorkspaceError> {
1018        self.views
1019            .get(&id)
1020            .map(|v| v.core.viewport_width)
1021            .ok_or(WorkspaceError::ViewNotFound(id))
1022    }
1023
1024    /// Get the current soft wrap mode for a view.
1025    pub fn wrap_mode_for_view(&self, id: ViewId) -> Result<WrapMode, WorkspaceError> {
1026        self.views
1027            .get(&id)
1028            .map(|v| v.core.wrap_mode)
1029            .ok_or(WorkspaceError::ViewNotFound(id))
1030    }
1031
1032    /// Get the current wrapped-line indentation policy for a view.
1033    pub fn wrap_indent_for_view(&self, id: ViewId) -> Result<WrapIndent, WorkspaceError> {
1034        self.views
1035            .get(&id)
1036            .map(|v| v.core.wrap_indent)
1037            .ok_or(WorkspaceError::ViewNotFound(id))
1038    }
1039
1040    /// Get the current tab key behavior for a view.
1041    pub fn tab_key_behavior_for_view(&self, id: ViewId) -> Result<TabKeyBehavior, WorkspaceError> {
1042        self.views
1043            .get(&id)
1044            .map(|v| v.core.tab_key_behavior)
1045            .ok_or(WorkspaceError::ViewNotFound(id))
1046    }
1047
1048    /// Get the current indentation configuration for a view.
1049    pub fn indentation_config_for_view(
1050        &self,
1051        id: ViewId,
1052    ) -> Result<IndentationConfig, WorkspaceError> {
1053        self.views
1054            .get(&id)
1055            .map(|v| v.core.indentation_config.clone())
1056            .ok_or(WorkspaceError::ViewNotFound(id))
1057    }
1058
1059    /// Get the current auto-pairs configuration for a view.
1060    pub fn auto_pairs_config_for_view(
1061        &self,
1062        id: ViewId,
1063    ) -> Result<AutoPairsConfig, WorkspaceError> {
1064        self.views
1065            .get(&id)
1066            .map(|v| v.core.auto_pairs.clone())
1067            .ok_or(WorkspaceError::ViewNotFound(id))
1068    }
1069
1070    /// Get a view's normalized cursor/selection snapshot.
1071    ///
1072    /// This matches the semantics of `EditorStateManager::get_cursor_state`, but for workspace views.
1073    pub fn cursor_state_for_view(&self, id: ViewId) -> Result<CursorState, WorkspaceError> {
1074        let Some(view) = self.views.get(&id) else {
1075            return Err(WorkspaceError::ViewNotFound(id));
1076        };
1077        let Some(buffer) = self.buffers.get(&view.buffer) else {
1078            return Err(WorkspaceError::BufferNotFound(view.buffer));
1079        };
1080
1081        let line_index = buffer.executor.editor().line_index();
1082
1083        let mut selections: Vec<Selection> =
1084            Vec::with_capacity(1 + view.core.secondary_selections.len());
1085        let primary = view.core.selection.clone().unwrap_or(Selection {
1086            start: view.core.cursor_position,
1087            end: view.core.cursor_position,
1088            direction: SelectionDirection::Forward,
1089        });
1090        selections.push(primary);
1091        selections.extend(view.core.secondary_selections.iter().cloned());
1092
1093        let (selections, primary_selection_index) =
1094            crate::selection_set::normalize_selections(selections, 0);
1095        let primary = selections
1096            .get(primary_selection_index)
1097            .cloned()
1098            .unwrap_or(Selection {
1099                start: view.core.cursor_position,
1100                end: view.core.cursor_position,
1101                direction: SelectionDirection::Forward,
1102            });
1103
1104        let position = primary.end;
1105        let offset = line_index.position_to_char_offset(position.line, position.column);
1106
1107        let selection = if primary.start == primary.end {
1108            None
1109        } else {
1110            Some(primary)
1111        };
1112
1113        let multi_cursors: Vec<Position> = selections
1114            .iter()
1115            .enumerate()
1116            .filter_map(|(idx, sel)| {
1117                if idx == primary_selection_index {
1118                    None
1119                } else {
1120                    Some(sel.end)
1121                }
1122            })
1123            .collect();
1124
1125        Ok(CursorState {
1126            position,
1127            offset,
1128            multi_cursors,
1129            selection,
1130            selections,
1131            primary_selection_index,
1132        })
1133    }
1134
1135    /// Get the scroll position (top visual row) for a view.
1136    pub fn scroll_top_for_view(&self, id: ViewId) -> Result<usize, WorkspaceError> {
1137        self.views
1138            .get(&id)
1139            .map(|v| v.scroll_top)
1140            .ok_or(WorkspaceError::ViewNotFound(id))
1141    }
1142
1143    /// Get the sub-row smooth-scroll offset for a view.
1144    pub fn scroll_sub_row_offset_for_view(&self, id: ViewId) -> Result<u16, WorkspaceError> {
1145        self.views
1146            .get(&id)
1147            .map(|v| v.scroll_sub_row_offset)
1148            .ok_or(WorkspaceError::ViewNotFound(id))
1149    }
1150
1151    /// Get overscan rows for a view.
1152    pub fn overscan_rows_for_view(&self, id: ViewId) -> Result<usize, WorkspaceError> {
1153        self.views
1154            .get(&id)
1155            .map(|v| v.overscan_rows)
1156            .ok_or(WorkspaceError::ViewNotFound(id))
1157    }
1158
1159    /// Get smooth-scroll state for a view.
1160    pub fn smooth_scroll_state_for_view(
1161        &self,
1162        id: ViewId,
1163    ) -> Result<ViewSmoothScrollState, WorkspaceError> {
1164        let Some(view) = self.views.get(&id) else {
1165            return Err(WorkspaceError::ViewNotFound(id));
1166        };
1167        Ok(ViewSmoothScrollState {
1168            top_visual_row: view.scroll_top,
1169            sub_row_offset: view.scroll_sub_row_offset,
1170            overscan_rows: view.overscan_rows,
1171        })
1172    }
1173
1174    /// Update a buffer's uri/path.
1175    pub fn set_buffer_uri(
1176        &mut self,
1177        id: BufferId,
1178        uri: Option<String>,
1179    ) -> Result<(), WorkspaceError> {
1180        let Some(entry) = self.buffers.get_mut(&id) else {
1181            return Err(WorkspaceError::BufferNotFound(id));
1182        };
1183
1184        if let Some(next) = uri.as_ref()
1185            && self.uri_to_buffer.contains_key(next)
1186            && entry.meta.uri.as_deref() != Some(next.as_str())
1187        {
1188            return Err(WorkspaceError::UriAlreadyOpen(next.clone()));
1189        }
1190
1191        if let Some(prev) = entry.meta.uri.take() {
1192            self.uri_to_buffer.remove(&prev);
1193        }
1194
1195        if let Some(next) = uri.clone() {
1196            self.uri_to_buffer.insert(next, id);
1197        }
1198
1199        entry.meta.uri = uri;
1200        Ok(())
1201    }
1202
1203    /// Get a view's current version (increments on view-local changes and buffer changes).
1204    pub fn view_version(&self, id: ViewId) -> Option<u64> {
1205        self.views.get(&id).map(|v| v.version)
1206    }
1207
1208    /// Get the last broadcast text delta for this view (if any).
1209    pub fn last_text_delta_for_view(&self, id: ViewId) -> Option<&Arc<TextDelta>> {
1210        self.views.get(&id)?.last_text_delta.as_ref()
1211    }
1212
1213    /// Take the last broadcast text delta for this view (if any).
1214    pub fn take_last_text_delta_for_view(&mut self, id: ViewId) -> Option<Arc<TextDelta>> {
1215        self.views.get_mut(&id)?.last_text_delta.take()
1216    }
1217
1218    /// Take the last text delta for a buffer (if any).
1219    ///
1220    /// This is useful for incremental consumers (e.g. LSP sync) that want to observe each buffer
1221    /// edit exactly once, regardless of how many views exist for that buffer.
1222    pub fn take_last_text_delta_for_buffer(
1223        &mut self,
1224        id: BufferId,
1225    ) -> Result<Option<Arc<TextDelta>>, WorkspaceError> {
1226        let Some(buffer) = self.buffers.get_mut(&id) else {
1227            return Err(WorkspaceError::BufferNotFound(id));
1228        };
1229        Ok(buffer.last_text_delta.take())
1230    }
1231
1232    /// Subscribe to changes for a view.
1233    pub fn subscribe_view<F>(&mut self, id: ViewId, callback: F) -> Result<(), WorkspaceError>
1234    where
1235        F: FnMut(&StateChange) + Send + 'static,
1236    {
1237        let Some(view) = self.views.get_mut(&id) else {
1238            return Err(WorkspaceError::ViewNotFound(id));
1239        };
1240
1241        view.callbacks.push(Box::new(callback));
1242        Ok(())
1243    }
1244
1245    fn notify_view(
1246        view: &mut ViewEntry,
1247        change_type: StateChangeType,
1248        delta: Option<Arc<TextDelta>>,
1249    ) {
1250        let old_version = view.version;
1251        view.version = view.version.saturating_add(1);
1252
1253        let mut change = StateChange::new(change_type, old_version, view.version);
1254        if let Some(delta) = delta {
1255            change = change.with_text_delta(delta);
1256        }
1257
1258        for cb in &mut view.callbacks {
1259            cb(&change);
1260        }
1261    }
1262
1263    fn command_change_type(command: &Command) -> Option<StateChangeType> {
1264        match command {
1265            Command::Edit(EditCommand::Delete { length: 0, .. }) => None,
1266            Command::Edit(EditCommand::Replace {
1267                length: 0, text, ..
1268            }) if text.is_empty() => None,
1269            Command::Edit(EditCommand::EndUndoGroup) => None,
1270            Command::Edit(_) => Some(StateChangeType::DocumentModified),
1271            Command::Cursor(
1272                CursorCommand::MoveTo { .. }
1273                | CursorCommand::MoveBy { .. }
1274                | CursorCommand::MoveVisualBy { .. }
1275                | CursorCommand::MoveToVisual { .. }
1276                | CursorCommand::MoveToLineStart
1277                | CursorCommand::MoveToLineEnd
1278                | CursorCommand::MoveToVisualLineStart
1279                | CursorCommand::MoveToVisualLineEnd
1280                | CursorCommand::MoveGraphemeLeft
1281                | CursorCommand::MoveGraphemeRight
1282                | CursorCommand::MoveWordLeft
1283                | CursorCommand::MoveWordRight
1284                | CursorCommand::MoveToMatchingBracket
1285                | CursorCommand::FindNext { .. }
1286                | CursorCommand::FindPrev { .. },
1287            ) => Some(StateChangeType::CursorMoved),
1288            Command::Cursor(_) => Some(StateChangeType::SelectionChanged),
1289            Command::View(ViewCommand::ScrollTo { .. } | ViewCommand::GetViewport { .. }) => None,
1290            Command::View(_) => Some(StateChangeType::ViewportChanged),
1291            Command::Style(
1292                crate::StyleCommand::AddStyle { .. }
1293                | crate::StyleCommand::RemoveStyle { .. }
1294                | crate::StyleCommand::UpdateBracketMatchHighlights
1295                | crate::StyleCommand::ClearBracketMatchHighlights,
1296            ) => Some(StateChangeType::StyleChanged),
1297            Command::Style(
1298                crate::StyleCommand::Fold { .. }
1299                | crate::StyleCommand::Unfold { .. }
1300                | crate::StyleCommand::UnfoldAll,
1301            ) => Some(StateChangeType::FoldingChanged),
1302        }
1303    }
1304
1305    /// Execute a command against a specific view.
1306    ///
1307    /// - Cursor/selection state is view-local.
1308    /// - Text edits and derived-state edits are applied to the underlying buffer.
1309    /// - Any text delta is broadcast to all views of that buffer.
1310    pub fn execute(
1311        &mut self,
1312        view_id: ViewId,
1313        command: Command,
1314    ) -> Result<CommandResult, WorkspaceError> {
1315        let Some(buffer_id) = self.views.get(&view_id).map(|v| v.buffer) else {
1316            return Err(WorkspaceError::ViewNotFound(view_id));
1317        };
1318
1319        let change_type = Self::command_change_type(&command);
1320        if change_type.is_none() {
1321            // Still run command because it may validate (e.g. ScrollTo), but treat as no version bump.
1322        }
1323
1324        // Borrow maps separately so we can mutably access a view and its buffer.
1325        let views = &mut self.views;
1326        let buffers = &mut self.buffers;
1327
1328        let Some(view) = views.get_mut(&view_id) else {
1329            return Err(WorkspaceError::ViewNotFound(view_id));
1330        };
1331        let Some(buffer) = buffers.get_mut(&buffer_id) else {
1332            return Err(WorkspaceError::BufferNotFound(buffer_id));
1333        };
1334
1335        let before_view_core = view.core.clone();
1336        let before_line_index = buffer.executor.editor().line_index().clone();
1337        let before_char_count = buffer.executor.editor().char_count();
1338
1339        // Load view-local state into the executor, execute, then snapshot it back.
1340        view.core.apply_to_executor(&mut buffer.executor);
1341
1342        let result = buffer.executor.execute(command.clone()).map_err(|err| {
1343            WorkspaceError::CommandFailed {
1344                view: view_id,
1345                message: err.to_string(),
1346            }
1347        })?;
1348
1349        view.core = ViewCore::from_executor(&buffer.executor);
1350
1351        let delta = buffer.executor.take_last_text_delta().map(Arc::new);
1352        let after_char_count = buffer.executor.editor().char_count();
1353
1354        // Detect no-ops: successful execution but no meaningful state change.
1355        let view_changed = view.core != before_view_core;
1356        let buffer_text_changed = delta.is_some()
1357            // `Backspace`/`DeleteForward` can succeed as boundary no-ops; detect via char count.
1358            || after_char_count != before_char_count;
1359
1360        let buffer_derived_changed = matches!(command, Command::Style(_));
1361
1362        if !(view_changed || buffer_text_changed || buffer_derived_changed) {
1363            return Ok(result);
1364        }
1365
1366        let change_type = if buffer_text_changed {
1367            StateChangeType::DocumentModified
1368        } else {
1369            change_type.unwrap_or(StateChangeType::ViewportChanged)
1370        };
1371
1372        if buffer_text_changed || buffer_derived_changed {
1373            // Broadcast to all views of this buffer.
1374            //
1375            // Coalesce (merge) into the delta slots rather than overwrite: a consumer that has not
1376            // taken the previous delta yet must still observe this edit. A change without a text
1377            // delta (e.g. a style-only change) must NOT clear an unconsumed text delta.
1378            if let Some(delta_arc) = delta.clone() {
1379                coalesce_delta_slot(&mut buffer.last_text_delta, &delta_arc);
1380                for other in views.values_mut() {
1381                    if other.buffer != buffer_id {
1382                        continue;
1383                    }
1384                    coalesce_delta_slot(&mut other.last_text_delta, &delta_arc);
1385                }
1386            }
1387
1388            // Shift other views' cursor/selections through the delta (if any).
1389            if let Some(ref delta_arc) = delta {
1390                let new_index = buffer.executor.editor().line_index();
1391                for (other_id, other) in views.iter_mut() {
1392                    if other.buffer != buffer_id || *other_id == view_id {
1393                        continue;
1394                    }
1395
1396                    other.core.cursor_position = apply_position_delta(
1397                        &before_line_index,
1398                        new_index,
1399                        other.core.cursor_position,
1400                        delta_arc,
1401                    );
1402
1403                    if let Some(ref sel) = other.core.selection {
1404                        other.core.selection = Some(apply_selection_delta(
1405                            &before_line_index,
1406                            new_index,
1407                            sel,
1408                            delta_arc,
1409                        ));
1410                    }
1411
1412                    for sel in &mut other.core.secondary_selections {
1413                        *sel = apply_selection_delta(&before_line_index, new_index, sel, delta_arc);
1414                    }
1415
1416                    if let Some(ref mut session) = other.core.snippet_session {
1417                        session.apply_delta(delta_arc);
1418                    }
1419                }
1420
1421                // Keep navigation state stable under edits.
1422                buffer.bookmarks.apply_delta(delta_arc);
1423                buffer.marks.apply_delta(delta_arc);
1424                for other in views.values_mut() {
1425                    if other.buffer != buffer_id {
1426                        continue;
1427                    }
1428                    other.jump_list.apply_delta(buffer_id, delta_arc);
1429                }
1430            }
1431
1432            for other in views.values_mut() {
1433                if other.buffer != buffer_id {
1434                    continue;
1435                }
1436                Self::notify_view(other, change_type, delta.clone());
1437            }
1438
1439            if buffer_text_changed && let Some(uri) = buffer.meta.uri.as_deref() {
1440                self.intelligence.mark_stale_for_uri(uri);
1441            }
1442
1443            buffer.version = buffer.version.saturating_add(1);
1444        } else {
1445            Self::notify_view(view, change_type, None);
1446        }
1447
1448        Ok(result)
1449    }
1450
1451    /// Return `true` if the given view currently has an active snippet session.
1452    ///
1453    /// Snippet sessions are created by snippet inserts (for example LSP completion items with
1454    /// `insertTextFormat == 2`) and allow tab/shift-tab navigation between placeholders.
1455    pub fn has_active_snippet_session(&self, view_id: ViewId) -> Result<bool, WorkspaceError> {
1456        let Some(view) = self.views.get(&view_id) else {
1457            return Err(WorkspaceError::ViewNotFound(view_id));
1458        };
1459        Ok(view
1460            .core
1461            .snippet_session
1462            .as_ref()
1463            .map(|s| s.is_active())
1464            .unwrap_or(false))
1465    }
1466
1467    /// Toggle a bookmark at the **current cursor line** for the given view.
1468    ///
1469    /// Returns `true` if a bookmark was added, or `false` if an existing bookmark on that line was
1470    /// removed.
1471    pub fn toggle_bookmark_at_cursor_line(
1472        &mut self,
1473        view_id: ViewId,
1474    ) -> Result<bool, WorkspaceError> {
1475        let Some(buffer_id) = self.views.get(&view_id).map(|v| v.buffer) else {
1476            return Err(WorkspaceError::ViewNotFound(view_id));
1477        };
1478        let Some(buffer) = self.buffers.get_mut(&buffer_id) else {
1479            return Err(WorkspaceError::BufferNotFound(buffer_id));
1480        };
1481        let Some(view) = self.views.get(&view_id) else {
1482            return Err(WorkspaceError::ViewNotFound(view_id));
1483        };
1484
1485        let line_start = buffer
1486            .executor
1487            .editor()
1488            .line_index()
1489            .position_to_char_offset(view.core.cursor_position.line, 0);
1490
1491        let added = buffer.bookmarks.toggle_line_start(line_start);
1492
1493        for v in self.views.values_mut() {
1494            if v.buffer == buffer_id {
1495                Self::notify_view(v, StateChangeType::NavigationChanged, None);
1496            }
1497        }
1498
1499        Ok(added)
1500    }
1501
1502    /// Return all bookmark line numbers (0-based) for a buffer.
1503    pub fn bookmark_lines(&self, buffer_id: BufferId) -> Result<Vec<usize>, WorkspaceError> {
1504        let Some(buffer) = self.buffers.get(&buffer_id) else {
1505            return Err(WorkspaceError::BufferNotFound(buffer_id));
1506        };
1507        Ok(buffer
1508            .bookmarks
1509            .line_numbers(buffer.executor.editor().line_index()))
1510    }
1511
1512    /// Clear all bookmarks for a buffer.
1513    pub fn clear_bookmarks(&mut self, buffer_id: BufferId) -> Result<(), WorkspaceError> {
1514        let Some(buffer) = self.buffers.get_mut(&buffer_id) else {
1515            return Err(WorkspaceError::BufferNotFound(buffer_id));
1516        };
1517        buffer.bookmarks.clear();
1518
1519        for v in self.views.values_mut() {
1520            if v.buffer == buffer_id {
1521                Self::notify_view(v, StateChangeType::NavigationChanged, None);
1522            }
1523        }
1524
1525        Ok(())
1526    }
1527
1528    fn move_view_cursor_to_anchor(
1529        view: &mut ViewEntry,
1530        buffer: &BufferEntry,
1531        anchor: TextAnchor,
1532    ) -> Position {
1533        let (line, column) = buffer
1534            .executor
1535            .editor()
1536            .line_index()
1537            .char_offset_to_position(anchor.offset);
1538        view.core.cursor_position = Position::new(line, column);
1539        view.core.preferred_x_cells = buffer
1540            .executor
1541            .editor()
1542            .logical_position_to_visual(line, column)
1543            .map(|(_, x)| x);
1544        view.core.selection = None;
1545        view.core.secondary_selections.clear();
1546        view.core.cursor_position
1547    }
1548
1549    /// Move the cursor to the next bookmark (wrapping to the first bookmark).
1550    ///
1551    /// Returns the new cursor position, or `None` if there are no bookmarks.
1552    pub fn goto_next_bookmark(
1553        &mut self,
1554        view_id: ViewId,
1555    ) -> Result<Option<Position>, WorkspaceError> {
1556        let Some(buffer_id) = self.views.get(&view_id).map(|v| v.buffer) else {
1557            return Err(WorkspaceError::ViewNotFound(view_id));
1558        };
1559        let Some(buffer) = self.buffers.get(&buffer_id) else {
1560            return Err(WorkspaceError::BufferNotFound(buffer_id));
1561        };
1562
1563        let current_line_start = buffer
1564            .executor
1565            .editor()
1566            .line_index()
1567            .position_to_char_offset(
1568                self.views
1569                    .get(&view_id)
1570                    .ok_or(WorkspaceError::ViewNotFound(view_id))?
1571                    .core
1572                    .cursor_position
1573                    .line,
1574                0,
1575            );
1576
1577        let Some(target) = buffer.bookmarks.next_after_line_start(current_line_start) else {
1578            return Ok(None);
1579        };
1580
1581        let Some(view) = self.views.get_mut(&view_id) else {
1582            return Err(WorkspaceError::ViewNotFound(view_id));
1583        };
1584        let pos = Self::move_view_cursor_to_anchor(view, buffer, target);
1585        Self::notify_view(view, StateChangeType::SelectionChanged, None);
1586        Ok(Some(pos))
1587    }
1588
1589    /// Move the cursor to the previous bookmark (wrapping to the last bookmark).
1590    ///
1591    /// Returns the new cursor position, or `None` if there are no bookmarks.
1592    pub fn goto_prev_bookmark(
1593        &mut self,
1594        view_id: ViewId,
1595    ) -> Result<Option<Position>, WorkspaceError> {
1596        let Some(buffer_id) = self.views.get(&view_id).map(|v| v.buffer) else {
1597            return Err(WorkspaceError::ViewNotFound(view_id));
1598        };
1599        let Some(buffer) = self.buffers.get(&buffer_id) else {
1600            return Err(WorkspaceError::BufferNotFound(buffer_id));
1601        };
1602
1603        let current_line_start = buffer
1604            .executor
1605            .editor()
1606            .line_index()
1607            .position_to_char_offset(
1608                self.views
1609                    .get(&view_id)
1610                    .ok_or(WorkspaceError::ViewNotFound(view_id))?
1611                    .core
1612                    .cursor_position
1613                    .line,
1614                0,
1615            );
1616
1617        let Some(target) = buffer.bookmarks.prev_before_line_start(current_line_start) else {
1618            return Ok(None);
1619        };
1620
1621        let Some(view) = self.views.get_mut(&view_id) else {
1622            return Err(WorkspaceError::ViewNotFound(view_id));
1623        };
1624        let pos = Self::move_view_cursor_to_anchor(view, buffer, target);
1625        Self::notify_view(view, StateChangeType::SelectionChanged, None);
1626        Ok(Some(pos))
1627    }
1628
1629    /// Set (or replace) a named mark at the current cursor position of the given view.
1630    pub fn set_mark_at_cursor(
1631        &mut self,
1632        view_id: ViewId,
1633        name: String,
1634    ) -> Result<(), WorkspaceError> {
1635        if name.trim().is_empty() {
1636            return Err(WorkspaceError::CommandFailed {
1637                view: view_id,
1638                message: "Mark name cannot be empty".to_string(),
1639            });
1640        }
1641
1642        let Some(buffer_id) = self.views.get(&view_id).map(|v| v.buffer) else {
1643            return Err(WorkspaceError::ViewNotFound(view_id));
1644        };
1645        let Some(buffer) = self.buffers.get_mut(&buffer_id) else {
1646            return Err(WorkspaceError::BufferNotFound(buffer_id));
1647        };
1648        let Some(view) = self.views.get(&view_id) else {
1649            return Err(WorkspaceError::ViewNotFound(view_id));
1650        };
1651
1652        let pos = view.core.cursor_position;
1653        let offset = buffer
1654            .executor
1655            .editor()
1656            .line_index()
1657            .position_to_char_offset(pos.line, pos.column);
1658        buffer.marks.set(name, offset);
1659
1660        for v in self.views.values_mut() {
1661            if v.buffer == buffer_id {
1662                Self::notify_view(v, StateChangeType::NavigationChanged, None);
1663            }
1664        }
1665
1666        Ok(())
1667    }
1668
1669    /// Move the cursor to a named mark (if present).
1670    ///
1671    /// Returns the new cursor position, or `None` if the mark does not exist.
1672    pub fn goto_mark(
1673        &mut self,
1674        view_id: ViewId,
1675        name: &str,
1676    ) -> Result<Option<Position>, WorkspaceError> {
1677        let Some(buffer_id) = self.views.get(&view_id).map(|v| v.buffer) else {
1678            return Err(WorkspaceError::ViewNotFound(view_id));
1679        };
1680        let Some(buffer) = self.buffers.get(&buffer_id) else {
1681            return Err(WorkspaceError::BufferNotFound(buffer_id));
1682        };
1683
1684        let Some(anchor) = buffer.marks.get(name) else {
1685            return Ok(None);
1686        };
1687
1688        let Some(view) = self.views.get_mut(&view_id) else {
1689            return Err(WorkspaceError::ViewNotFound(view_id));
1690        };
1691        let pos = Self::move_view_cursor_to_anchor(view, buffer, anchor);
1692        Self::notify_view(view, StateChangeType::SelectionChanged, None);
1693        Ok(Some(pos))
1694    }
1695
1696    /// Remove a named mark from a buffer.
1697    ///
1698    /// Returns `true` if the mark existed.
1699    pub fn clear_mark(&mut self, buffer_id: BufferId, name: &str) -> Result<bool, WorkspaceError> {
1700        let Some(buffer) = self.buffers.get_mut(&buffer_id) else {
1701            return Err(WorkspaceError::BufferNotFound(buffer_id));
1702        };
1703        let existed = buffer.marks.remove(name);
1704        if existed {
1705            for v in self.views.values_mut() {
1706                if v.buffer == buffer_id {
1707                    Self::notify_view(v, StateChangeType::NavigationChanged, None);
1708                }
1709            }
1710        }
1711        Ok(existed)
1712    }
1713
1714    /// Return all mark names for a buffer (deterministic order).
1715    pub fn mark_names(&self, buffer_id: BufferId) -> Result<Vec<String>, WorkspaceError> {
1716        let Some(buffer) = self.buffers.get(&buffer_id) else {
1717            return Err(WorkspaceError::BufferNotFound(buffer_id));
1718        };
1719        Ok(buffer.marks.names())
1720    }
1721
1722    /// Clear all marks for a buffer.
1723    pub fn clear_all_marks(&mut self, buffer_id: BufferId) -> Result<(), WorkspaceError> {
1724        let Some(buffer) = self.buffers.get_mut(&buffer_id) else {
1725            return Err(WorkspaceError::BufferNotFound(buffer_id));
1726        };
1727        buffer.marks.clear();
1728        for v in self.views.values_mut() {
1729            if v.buffer == buffer_id {
1730                Self::notify_view(v, StateChangeType::NavigationChanged, None);
1731            }
1732        }
1733        Ok(())
1734    }
1735
1736    /// Record the current cursor position as a jump-list location for a view.
1737    ///
1738    /// Typical usage: call this *before* performing a “jump” (go-to-definition, search result,
1739    /// symbol navigation, ...).
1740    pub fn push_jump_location(&mut self, view_id: ViewId) -> Result<(), WorkspaceError> {
1741        let Some(buffer_id) = self.views.get(&view_id).map(|v| v.buffer) else {
1742            return Err(WorkspaceError::ViewNotFound(view_id));
1743        };
1744        let Some(buffer) = self.buffers.get(&buffer_id) else {
1745            return Err(WorkspaceError::BufferNotFound(buffer_id));
1746        };
1747        let Some(view) = self.views.get_mut(&view_id) else {
1748            return Err(WorkspaceError::ViewNotFound(view_id));
1749        };
1750
1751        let pos = view.core.cursor_position;
1752        let offset = buffer
1753            .executor
1754            .editor()
1755            .line_index()
1756            .position_to_char_offset(pos.line, pos.column);
1757
1758        view.jump_list.record(JumpEntry {
1759            buffer_id,
1760            anchor: TextAnchor::new(offset, AnchorBias::Right),
1761        });
1762
1763        Self::notify_view(view, StateChangeType::NavigationChanged, None);
1764        Ok(())
1765    }
1766
1767    /// Jump back in the view's jump list.
1768    ///
1769    /// Returns the navigation target (including the buffer id). If the target belongs to the
1770    /// current view's buffer, this method also moves the cursor and clears selection.
1771    pub fn jump_back(&mut self, view_id: ViewId) -> Result<Option<JumpTarget>, WorkspaceError> {
1772        let Some(buffer_id) = self.views.get(&view_id).map(|v| v.buffer) else {
1773            return Err(WorkspaceError::ViewNotFound(view_id));
1774        };
1775        let Some(buffer) = self.buffers.get(&buffer_id) else {
1776            return Err(WorkspaceError::BufferNotFound(buffer_id));
1777        };
1778
1779        let current_pos = self
1780            .views
1781            .get(&view_id)
1782            .ok_or(WorkspaceError::ViewNotFound(view_id))?
1783            .core
1784            .cursor_position;
1785        let current_offset = buffer
1786            .executor
1787            .editor()
1788            .line_index()
1789            .position_to_char_offset(current_pos.line, current_pos.column);
1790        let current = JumpEntry {
1791            buffer_id,
1792            anchor: TextAnchor::new(current_offset, AnchorBias::Right),
1793        };
1794
1795        let Some(view) = self.views.get_mut(&view_id) else {
1796            return Err(WorkspaceError::ViewNotFound(view_id));
1797        };
1798        let Some(target) = view.jump_list.back(current) else {
1799            return Ok(None);
1800        };
1801
1802        let Some(target_buffer) = self.buffers.get(&target.buffer_id) else {
1803            Self::notify_view(view, StateChangeType::NavigationChanged, None);
1804            return Ok(None);
1805        };
1806
1807        let (line, column) = target_buffer
1808            .executor
1809            .editor()
1810            .line_index()
1811            .char_offset_to_position(target.anchor.offset);
1812        let target_pos = Position::new(line, column);
1813
1814        let out = JumpTarget {
1815            buffer_id: target.buffer_id,
1816            position: target_pos,
1817        };
1818
1819        if target.buffer_id == buffer_id {
1820            Self::move_view_cursor_to_anchor(view, buffer, target.anchor);
1821            Self::notify_view(view, StateChangeType::SelectionChanged, None);
1822        } else {
1823            Self::notify_view(view, StateChangeType::NavigationChanged, None);
1824        }
1825
1826        Ok(Some(out))
1827    }
1828
1829    /// Jump forward in the view's jump list.
1830    ///
1831    /// Returns the navigation target (including the buffer id). If the target belongs to the
1832    /// current view's buffer, this method also moves the cursor and clears selection.
1833    pub fn jump_forward(&mut self, view_id: ViewId) -> Result<Option<JumpTarget>, WorkspaceError> {
1834        let Some(buffer_id) = self.views.get(&view_id).map(|v| v.buffer) else {
1835            return Err(WorkspaceError::ViewNotFound(view_id));
1836        };
1837        let Some(buffer) = self.buffers.get(&buffer_id) else {
1838            return Err(WorkspaceError::BufferNotFound(buffer_id));
1839        };
1840
1841        let current_pos = self
1842            .views
1843            .get(&view_id)
1844            .ok_or(WorkspaceError::ViewNotFound(view_id))?
1845            .core
1846            .cursor_position;
1847        let current_offset = buffer
1848            .executor
1849            .editor()
1850            .line_index()
1851            .position_to_char_offset(current_pos.line, current_pos.column);
1852        let current = JumpEntry {
1853            buffer_id,
1854            anchor: TextAnchor::new(current_offset, AnchorBias::Right),
1855        };
1856
1857        let Some(view) = self.views.get_mut(&view_id) else {
1858            return Err(WorkspaceError::ViewNotFound(view_id));
1859        };
1860        let Some(target) = view.jump_list.forward(current) else {
1861            return Ok(None);
1862        };
1863
1864        let Some(target_buffer) = self.buffers.get(&target.buffer_id) else {
1865            Self::notify_view(view, StateChangeType::NavigationChanged, None);
1866            return Ok(None);
1867        };
1868
1869        let (line, column) = target_buffer
1870            .executor
1871            .editor()
1872            .line_index()
1873            .char_offset_to_position(target.anchor.offset);
1874        let target_pos = Position::new(line, column);
1875
1876        let out = JumpTarget {
1877            buffer_id: target.buffer_id,
1878            position: target_pos,
1879        };
1880
1881        if target.buffer_id == buffer_id {
1882            Self::move_view_cursor_to_anchor(view, buffer, target.anchor);
1883            Self::notify_view(view, StateChangeType::SelectionChanged, None);
1884        } else {
1885            Self::notify_view(view, StateChangeType::NavigationChanged, None);
1886        }
1887
1888        Ok(Some(out))
1889    }
1890
1891    /// Clear the jump list (both back/forward stacks) for a view.
1892    pub fn clear_jump_list(&mut self, view_id: ViewId) -> Result<(), WorkspaceError> {
1893        let Some(view) = self.views.get_mut(&view_id) else {
1894            return Err(WorkspaceError::ViewNotFound(view_id));
1895        };
1896        view.jump_list.clear();
1897        Self::notify_view(view, StateChangeType::NavigationChanged, None);
1898        Ok(())
1899    }
1900
1901    /// Apply a previously produced [`JumpTarget`] to a view (moves the cursor and clears
1902    /// selection).
1903    pub fn apply_jump_target(
1904        &mut self,
1905        view_id: ViewId,
1906        target: JumpTarget,
1907    ) -> Result<(), WorkspaceError> {
1908        let Some(view) = self.views.get_mut(&view_id) else {
1909            return Err(WorkspaceError::ViewNotFound(view_id));
1910        };
1911        if view.buffer != target.buffer_id {
1912            return Err(WorkspaceError::CommandFailed {
1913                view: view_id,
1914                message: "JumpTarget buffer does not match view buffer".to_string(),
1915            });
1916        }
1917
1918        let Some(buffer) = self.buffers.get(&view.buffer) else {
1919            return Err(WorkspaceError::BufferNotFound(view.buffer));
1920        };
1921
1922        view.core.cursor_position = target.position;
1923        view.core.preferred_x_cells = buffer
1924            .executor
1925            .editor()
1926            .logical_position_to_visual(target.position.line, target.position.column)
1927            .map(|(_, x)| x);
1928        view.core.selection = None;
1929        view.core.secondary_selections.clear();
1930
1931        Self::notify_view(view, StateChangeType::SelectionChanged, None);
1932        Ok(())
1933    }
1934
1935    /// Set the viewport height for a view (used for `ViewportState` calculations).
1936    pub fn set_viewport_height(
1937        &mut self,
1938        view_id: ViewId,
1939        height: usize,
1940    ) -> Result<(), WorkspaceError> {
1941        let Some(view) = self.views.get_mut(&view_id) else {
1942            return Err(WorkspaceError::ViewNotFound(view_id));
1943        };
1944        view.viewport_height = Some(height);
1945        Ok(())
1946    }
1947
1948    /// Set the scroll position (top visual row) for a view.
1949    pub fn set_scroll_top(
1950        &mut self,
1951        view_id: ViewId,
1952        scroll_top: usize,
1953    ) -> Result<(), WorkspaceError> {
1954        let Some(view) = self.views.get_mut(&view_id) else {
1955            return Err(WorkspaceError::ViewNotFound(view_id));
1956        };
1957        view.scroll_top = scroll_top;
1958        Ok(())
1959    }
1960
1961    /// Set sub-row smooth-scroll offset for a view.
1962    pub fn set_scroll_sub_row_offset(
1963        &mut self,
1964        view_id: ViewId,
1965        sub_row_offset: u16,
1966    ) -> Result<(), WorkspaceError> {
1967        let Some(view) = self.views.get_mut(&view_id) else {
1968            return Err(WorkspaceError::ViewNotFound(view_id));
1969        };
1970        view.scroll_sub_row_offset = sub_row_offset;
1971        Ok(())
1972    }
1973
1974    /// Set overscan rows for a view.
1975    pub fn set_overscan_rows(
1976        &mut self,
1977        view_id: ViewId,
1978        overscan_rows: usize,
1979    ) -> Result<(), WorkspaceError> {
1980        let Some(view) = self.views.get_mut(&view_id) else {
1981            return Err(WorkspaceError::ViewNotFound(view_id));
1982        };
1983        view.overscan_rows = overscan_rows;
1984        Ok(())
1985    }
1986
1987    /// Set smooth-scroll state for a view.
1988    pub fn set_smooth_scroll_state(
1989        &mut self,
1990        view_id: ViewId,
1991        state: ViewSmoothScrollState,
1992    ) -> Result<(), WorkspaceError> {
1993        let Some(view) = self.views.get_mut(&view_id) else {
1994            return Err(WorkspaceError::ViewNotFound(view_id));
1995        };
1996        view.scroll_top = state.top_visual_row;
1997        view.scroll_sub_row_offset = state.sub_row_offset;
1998        view.overscan_rows = state.overscan_rows;
1999        Ok(())
2000    }
2001
2002    /// Get viewport state for a view, including total visual lines and overscan prefetch range.
2003    pub fn viewport_state_for_view(
2004        &mut self,
2005        view_id: ViewId,
2006    ) -> Result<WorkspaceViewportState, WorkspaceError> {
2007        let Some((
2008            buffer_id,
2009            view_core,
2010            scroll_top,
2011            viewport_height,
2012            sub_row_offset,
2013            overscan_rows,
2014        )) = self.views.get(&view_id).map(|v| {
2015            (
2016                v.buffer,
2017                v.core.clone(),
2018                v.scroll_top,
2019                v.viewport_height,
2020                v.scroll_sub_row_offset,
2021                v.overscan_rows,
2022            )
2023        })
2024        else {
2025            return Err(WorkspaceError::ViewNotFound(view_id));
2026        };
2027
2028        let Some(buffer) = self.buffers.get_mut(&buffer_id) else {
2029            return Err(WorkspaceError::BufferNotFound(buffer_id));
2030        };
2031        view_core.apply_to_executor(&mut buffer.executor);
2032        let editor = buffer.executor.editor();
2033
2034        let total_visual_lines = editor.visual_line_count();
2035        let visible_end = if let Some(height) = viewport_height {
2036            scroll_top.saturating_add(height).min(total_visual_lines)
2037        } else {
2038            total_visual_lines
2039        };
2040        let visible_lines = scroll_top.min(total_visual_lines)..visible_end;
2041        let prefetch_start = visible_lines.start.saturating_sub(overscan_rows);
2042        let prefetch_end = visible_lines
2043            .end
2044            .saturating_add(overscan_rows)
2045            .min(total_visual_lines);
2046
2047        Ok(WorkspaceViewportState {
2048            width: editor.viewport_width(),
2049            height: viewport_height,
2050            scroll_top,
2051            visible_lines,
2052            total_visual_lines,
2053            smooth_scroll: ViewSmoothScrollState {
2054                top_visual_row: scroll_top,
2055                sub_row_offset,
2056                overscan_rows,
2057            },
2058            prefetch_lines: prefetch_start..prefetch_end,
2059        })
2060    }
2061
2062    /// Get total visual lines for a view (wrap + folding aware).
2063    pub fn total_visual_lines_for_view(
2064        &mut self,
2065        view_id: ViewId,
2066    ) -> Result<usize, WorkspaceError> {
2067        Ok(self.viewport_state_for_view(view_id)?.total_visual_lines)
2068    }
2069
2070    /// Map global visual row to `(logical_line, visual_in_logical)` for a view.
2071    pub fn visual_to_logical_for_view(
2072        &mut self,
2073        view_id: ViewId,
2074        visual_row: usize,
2075    ) -> Result<(usize, usize), WorkspaceError> {
2076        let Some((buffer_id, view_core)) =
2077            self.views.get(&view_id).map(|v| (v.buffer, v.core.clone()))
2078        else {
2079            return Err(WorkspaceError::ViewNotFound(view_id));
2080        };
2081        let Some(buffer) = self.buffers.get_mut(&buffer_id) else {
2082            return Err(WorkspaceError::BufferNotFound(buffer_id));
2083        };
2084        view_core.apply_to_executor(&mut buffer.executor);
2085        Ok(buffer.executor.editor().visual_to_logical_line(visual_row))
2086    }
2087
2088    /// Map logical position to global visual `(row, x_cells)` for a view.
2089    pub fn logical_to_visual_for_view(
2090        &mut self,
2091        view_id: ViewId,
2092        line: usize,
2093        column: usize,
2094    ) -> Result<Option<(usize, usize)>, WorkspaceError> {
2095        let Some((buffer_id, view_core)) =
2096            self.views.get(&view_id).map(|v| (v.buffer, v.core.clone()))
2097        else {
2098            return Err(WorkspaceError::ViewNotFound(view_id));
2099        };
2100        let Some(buffer) = self.buffers.get_mut(&buffer_id) else {
2101            return Err(WorkspaceError::BufferNotFound(buffer_id));
2102        };
2103        view_core.apply_to_executor(&mut buffer.executor);
2104        Ok(buffer
2105            .executor
2106            .editor()
2107            .logical_position_to_visual(line, column))
2108    }
2109
2110    /// Map visual `(row, x_cells)` back to logical position for a view.
2111    pub fn visual_position_to_logical_for_view(
2112        &mut self,
2113        view_id: ViewId,
2114        visual_row: usize,
2115        x_cells: usize,
2116    ) -> Result<Option<Position>, WorkspaceError> {
2117        let Some((buffer_id, view_core)) =
2118            self.views.get(&view_id).map(|v| (v.buffer, v.core.clone()))
2119        else {
2120            return Err(WorkspaceError::ViewNotFound(view_id));
2121        };
2122        let Some(buffer) = self.buffers.get_mut(&buffer_id) else {
2123            return Err(WorkspaceError::BufferNotFound(buffer_id));
2124        };
2125        view_core.apply_to_executor(&mut buffer.executor);
2126        Ok(buffer
2127            .executor
2128            .editor()
2129            .visual_position_to_logical(visual_row, x_cells))
2130    }
2131
2132    /// Get the full document text for a buffer.
2133    pub fn buffer_text(&self, buffer_id: BufferId) -> Result<String, WorkspaceError> {
2134        let Some(buffer) = self.buffers.get(&buffer_id) else {
2135            return Err(WorkspaceError::BufferNotFound(buffer_id));
2136        };
2137        Ok(buffer.executor.editor().get_text())
2138    }
2139
2140    /// Get the full document text converted to the buffer's preferred line ending for saving.
2141    pub fn buffer_text_for_saving(&self, buffer_id: BufferId) -> Result<String, WorkspaceError> {
2142        let Some(buffer) = self.buffers.get(&buffer_id) else {
2143            return Err(WorkspaceError::BufferNotFound(buffer_id));
2144        };
2145        let text = buffer.executor.editor().get_text();
2146        Ok(buffer.executor.line_ending().apply_to_text(&text))
2147    }
2148
2149    /// Get the full document text converted to the view's preferred line ending for saving.
2150    pub fn text_for_saving_for_view(&self, view_id: ViewId) -> Result<String, WorkspaceError> {
2151        let buffer_id = self.buffer_id_for_view(view_id)?;
2152        self.buffer_text_for_saving(buffer_id)
2153    }
2154
2155    /// Get styled viewport content for a view (by visual line).
2156    pub fn get_viewport_content_styled(
2157        &mut self,
2158        view_id: ViewId,
2159        start_visual_row: usize,
2160        count: usize,
2161    ) -> Result<crate::HeadlessGrid, WorkspaceError> {
2162        let Some(buffer_id) = self.views.get(&view_id).map(|v| v.buffer) else {
2163            return Err(WorkspaceError::ViewNotFound(view_id));
2164        };
2165
2166        let view_core = self
2167            .views
2168            .get(&view_id)
2169            .map(|v| v.core.clone())
2170            .ok_or(WorkspaceError::ViewNotFound(view_id))?;
2171
2172        let Some(buffer) = self.buffers.get_mut(&buffer_id) else {
2173            return Err(WorkspaceError::BufferNotFound(buffer_id));
2174        };
2175
2176        view_core.apply_to_executor(&mut buffer.executor);
2177        Ok(buffer
2178            .executor
2179            .editor()
2180            .get_headless_grid_styled(start_visual_row, count))
2181    }
2182
2183    /// Get lightweight minimap content for a view (by visual line).
2184    pub fn get_minimap_content(
2185        &mut self,
2186        view_id: ViewId,
2187        start_visual_row: usize,
2188        count: usize,
2189    ) -> Result<crate::MinimapGrid, WorkspaceError> {
2190        let Some(buffer_id) = self.views.get(&view_id).map(|v| v.buffer) else {
2191            return Err(WorkspaceError::ViewNotFound(view_id));
2192        };
2193
2194        let view_core = self
2195            .views
2196            .get(&view_id)
2197            .map(|v| v.core.clone())
2198            .ok_or(WorkspaceError::ViewNotFound(view_id))?;
2199
2200        let Some(buffer) = self.buffers.get_mut(&buffer_id) else {
2201            return Err(WorkspaceError::BufferNotFound(buffer_id));
2202        };
2203
2204        view_core.apply_to_executor(&mut buffer.executor);
2205        Ok(buffer
2206            .executor
2207            .editor()
2208            .get_minimap_grid(start_visual_row, count))
2209    }
2210
2211    /// Get a decoration-aware composed viewport snapshot for a view (by composed visual line).
2212    ///
2213    /// This snapshot can include virtual text (inlay hints, code lens) injected from the buffer's
2214    /// decoration layers. See [`crate::EditorCore::get_headless_grid_composed`] for details.
2215    pub fn get_viewport_content_composed(
2216        &mut self,
2217        view_id: ViewId,
2218        start_visual_row: usize,
2219        count: usize,
2220    ) -> Result<crate::ComposedGrid, WorkspaceError> {
2221        let Some(buffer_id) = self.views.get(&view_id).map(|v| v.buffer) else {
2222            return Err(WorkspaceError::ViewNotFound(view_id));
2223        };
2224
2225        let view_core = self
2226            .views
2227            .get(&view_id)
2228            .map(|v| v.core.clone())
2229            .ok_or(WorkspaceError::ViewNotFound(view_id))?;
2230
2231        let Some(buffer) = self.buffers.get_mut(&buffer_id) else {
2232            return Err(WorkspaceError::BufferNotFound(buffer_id));
2233        };
2234
2235        view_core.apply_to_executor(&mut buffer.executor);
2236        Ok(buffer
2237            .executor
2238            .editor()
2239            .get_headless_grid_composed(start_visual_row, count))
2240    }
2241
2242    /// Apply derived-state edits to a buffer and broadcast them to all views of that buffer.
2243    pub fn apply_processing_edits<I>(
2244        &mut self,
2245        buffer_id: BufferId,
2246        edits: I,
2247    ) -> Result<(), WorkspaceError>
2248    where
2249        I: IntoIterator<Item = ProcessingEdit>,
2250    {
2251        let Some(buffer) = self.buffers.get_mut(&buffer_id) else {
2252            return Err(WorkspaceError::BufferNotFound(buffer_id));
2253        };
2254
2255        let mut style_changed = false;
2256        let mut folding_changed = false;
2257        let mut diagnostics_changed = false;
2258        let mut decorations_changed = false;
2259        let mut symbols_changed = false;
2260
2261        for edit in edits {
2262            match edit {
2263                ProcessingEdit::ReplaceStyleLayer { layer, intervals } => {
2264                    buffer
2265                        .executor
2266                        .editor_mut()
2267                        .replace_style_layer(layer, intervals);
2268                    style_changed = true;
2269                }
2270                ProcessingEdit::ClearStyleLayer { layer } => {
2271                    buffer.executor.editor_mut().clear_style_layer(layer);
2272                    style_changed = true;
2273                }
2274                ProcessingEdit::ReplaceFoldingRegions {
2275                    regions,
2276                    preserve_collapsed,
2277                } => {
2278                    buffer
2279                        .executor
2280                        .editor_mut()
2281                        .replace_folding_regions(regions, preserve_collapsed);
2282                    folding_changed = true;
2283                }
2284                ProcessingEdit::ClearFoldingRegions => {
2285                    buffer.executor.editor_mut().clear_derived_folding_regions();
2286                    folding_changed = true;
2287                }
2288                ProcessingEdit::ReplaceDiagnostics { diagnostics } => {
2289                    buffer
2290                        .executor
2291                        .editor_mut()
2292                        .replace_diagnostics(diagnostics);
2293                    diagnostics_changed = true;
2294                }
2295                ProcessingEdit::ClearDiagnostics => {
2296                    buffer.executor.editor_mut().clear_diagnostics();
2297                    diagnostics_changed = true;
2298                }
2299                ProcessingEdit::ReplaceDecorations { layer, decorations } => {
2300                    buffer
2301                        .executor
2302                        .editor_mut()
2303                        .replace_decorations(layer, decorations);
2304                    decorations_changed = true;
2305                }
2306                ProcessingEdit::ClearDecorations { layer } => {
2307                    buffer.executor.editor_mut().clear_decorations(layer);
2308                    decorations_changed = true;
2309                }
2310                ProcessingEdit::ReplaceDocumentSymbols { symbols } => {
2311                    buffer
2312                        .executor
2313                        .editor_mut()
2314                        .replace_document_symbols(symbols);
2315                    symbols_changed = true;
2316                }
2317                ProcessingEdit::ClearDocumentSymbols => {
2318                    buffer.executor.editor_mut().clear_document_symbols();
2319                    symbols_changed = true;
2320                }
2321            }
2322        }
2323
2324        let change_type = if folding_changed {
2325            Some(StateChangeType::FoldingChanged)
2326        } else if style_changed {
2327            Some(StateChangeType::StyleChanged)
2328        } else if decorations_changed {
2329            Some(StateChangeType::DecorationsChanged)
2330        } else if diagnostics_changed {
2331            Some(StateChangeType::DiagnosticsChanged)
2332        } else if symbols_changed {
2333            Some(StateChangeType::SymbolsChanged)
2334        } else {
2335            None
2336        };
2337
2338        if let Some(change_type) = change_type {
2339            for view in self.views.values_mut() {
2340                if view.buffer == buffer_id {
2341                    Self::notify_view(view, change_type, None);
2342                }
2343            }
2344            buffer.version = buffer.version.saturating_add(1);
2345        }
2346
2347        Ok(())
2348    }
2349
2350    /// Search across all open buffers in the workspace.
2351    ///
2352    /// - This is purely in-memory (no file I/O).
2353    /// - Match ranges are returned as **character offsets** (half-open).
2354    pub fn search_all_open_buffers(
2355        &self,
2356        query: &str,
2357        options: SearchOptions,
2358    ) -> Result<Vec<WorkspaceSearchResult>, SearchError> {
2359        let mut out: Vec<WorkspaceSearchResult> = Vec::new();
2360
2361        for (id, entry) in &self.buffers {
2362            let text = entry.executor.editor().get_text();
2363            let matches = find_all(&text, query, options)?;
2364            if matches.is_empty() {
2365                continue;
2366            }
2367
2368            out.push(WorkspaceSearchResult {
2369                id: *id,
2370                uri: entry.meta.uri.clone(),
2371                matches,
2372            });
2373        }
2374
2375        Ok(out)
2376    }
2377
2378    /// Apply a set of text edits to multiple open buffers.
2379    ///
2380    /// - This is purely in-memory (no file I/O).
2381    /// - Edits are applied as a single undoable step **per buffer**.
2382    /// - Buffers are applied in deterministic `BufferId` order.
2383    pub fn apply_text_edits<I>(
2384        &mut self,
2385        edits: I,
2386    ) -> Result<Vec<(BufferId, usize)>, WorkspaceError>
2387    where
2388        I: IntoIterator<Item = (BufferId, Vec<TextEditSpec>)>,
2389    {
2390        let mut by_id: BTreeMap<BufferId, Vec<TextEditSpec>> = BTreeMap::new();
2391        for (id, mut buffer_edits) in edits {
2392            by_id.entry(id).or_default().append(&mut buffer_edits);
2393        }
2394
2395        let mut applied: Vec<(BufferId, usize)> = Vec::new();
2396        for (buffer_id, buffer_edits) in by_id {
2397            let edit_count = buffer_edits.len();
2398            if edit_count == 0 {
2399                continue;
2400            }
2401
2402            let Some(buffer) = self.buffers.get_mut(&buffer_id) else {
2403                return Err(WorkspaceError::BufferNotFound(buffer_id));
2404            };
2405
2406            let before_line_index = buffer.executor.editor().line_index().clone();
2407            let before_char_count = buffer.executor.editor().char_count();
2408
2409            // Apply without relying on any specific view selection: load a neutral view state.
2410            let neutral = ViewCore {
2411                cursor_position: Position::new(0, 0),
2412                selection: None,
2413                secondary_selections: Vec::new(),
2414                viewport_width: buffer.executor.editor().viewport_width().max(1),
2415                wrap_mode: buffer.executor.editor().layout_engine().wrap_mode(),
2416                wrap_indent: buffer.executor.editor().layout_engine().wrap_indent(),
2417                tab_width: buffer.executor.editor().layout_engine().tab_width(),
2418                tab_key_behavior: buffer.executor.tab_key_behavior(),
2419                indentation_config: buffer.executor.indentation_config().clone(),
2420                auto_pairs: buffer.executor.auto_pairs_config().clone(),
2421                snippet_session: None,
2422                preferred_x_cells: None,
2423            };
2424            neutral.apply_to_executor(&mut buffer.executor);
2425
2426            buffer
2427                .executor
2428                .execute(Command::Edit(EditCommand::ApplyTextEdits {
2429                    edits: buffer_edits,
2430                }))
2431                .map_err(|err| WorkspaceError::ApplyEditsFailed {
2432                    buffer: buffer_id,
2433                    message: err.to_string(),
2434                })?;
2435
2436            let delta = buffer.executor.take_last_text_delta().map(Arc::new);
2437            let after_char_count = buffer.executor.editor().char_count();
2438            let changed = delta.is_some() || after_char_count != before_char_count;
2439
2440            if changed {
2441                if let Some(uri) = buffer.meta.uri.as_deref() {
2442                    self.intelligence.mark_stale_for_uri(uri);
2443                }
2444
2445                if let Some(ref delta_arc) = delta {
2446                    // Coalesce into the delta slots (see `coalesce_delta_slot`) so an unconsumed
2447                    // delta from a prior edit is not lost.
2448                    coalesce_delta_slot(&mut buffer.last_text_delta, delta_arc);
2449                    let new_index = buffer.executor.editor().line_index();
2450                    for view in self.views.values_mut() {
2451                        if view.buffer != buffer_id {
2452                            continue;
2453                        }
2454
2455                        coalesce_delta_slot(&mut view.last_text_delta, delta_arc);
2456
2457                        view.core.cursor_position = apply_position_delta(
2458                            &before_line_index,
2459                            new_index,
2460                            view.core.cursor_position,
2461                            delta_arc,
2462                        );
2463                        if let Some(ref sel) = view.core.selection {
2464                            view.core.selection = Some(apply_selection_delta(
2465                                &before_line_index,
2466                                new_index,
2467                                sel,
2468                                delta_arc,
2469                            ));
2470                        }
2471                        for sel in &mut view.core.secondary_selections {
2472                            *sel = apply_selection_delta(
2473                                &before_line_index,
2474                                new_index,
2475                                sel,
2476                                delta_arc,
2477                            );
2478                        }
2479
2480                        Self::notify_view(
2481                            view,
2482                            StateChangeType::DocumentModified,
2483                            Some(delta_arc.clone()),
2484                        );
2485                    }
2486                } else {
2487                    // No text delta for this change; do not clear an unconsumed text delta.
2488                    for view in self.views.values_mut() {
2489                        if view.buffer == buffer_id {
2490                            Self::notify_view(view, StateChangeType::DocumentModified, None);
2491                        }
2492                    }
2493                }
2494
2495                buffer.version = buffer.version.saturating_add(1);
2496            }
2497
2498            applied.push((buffer_id, edit_count));
2499        }
2500
2501        Ok(applied)
2502    }
2503}