Skip to main content

ratatui_code_editor/
editor.rs

1use crate::actions::*;
2use crate::click::{ClickKind, ClickTracker};
3use crate::code::Code;
4use crate::code::{EditBatch, Operation};
5use crate::code::{RopeGraphemes, grapheme_width, grapheme_width_and_chars_len};
6use crate::selection::{Selection, SelectionSnap};
7use crate::types::{CodeFoldingOptions, DiffOptions, HightlightCache, Theme, VisualRow, LineDiffCache};
8use crate::utils;
9use crate::view::{View, ViewMode};
10use anyhow::{Result, anyhow};
11use ratatui_core::layout::Rect;
12use ratatui_core::style::{Color, Style};
13use std::cell::RefCell;
14use std::cmp::Ordering;
15use std::collections::HashMap;
16use std::time::Duration;
17use unicode_width::UnicodeWidthStr;
18
19/// Represents the text editor, which holds the code buffer, cursor, selection,
20/// theme, scroll offsets, highlight cache, clipboard, and user mark intervals.
21pub struct Editor {
22    /// Code buffer and editing/highlighting logic for the current language
23    pub(crate) code: Code,
24
25    /// Current cursor position as a character index in the document
26    pub(crate) cursor: usize,
27
28    /// Vertical scroll offset: index of the first visible line
29    pub(crate) offset_y: usize,
30
31    /// Horizontal scroll offset in characters (visual columns)
32    pub(crate) offset_x: usize,
33
34    /// Syntax theme: mapping of token name to ratatui Style
35    pub(crate) theme: Theme,
36
37    /// Current text selection, if any
38    pub(crate) selection: Option<Selection>,
39
40    /// Click tracker to detect single/double/triple clicks
41    pub(crate) clicks: ClickTracker,
42
43    /// Selection snapping mode (to word, to line, or none)
44    pub(crate) selection_snap: SelectionSnap,
45
46    /// Fallback clipboard storage when the system clipboard is unavailable
47    pub(crate) clipboard: Option<String>,
48
49    /// User marks for intervals: (start, end, color)
50    pub(crate) marks: Option<Vec<(usize, usize, Color)>>,
51
52    /// Syntax highlight cache by intervals to speed up rendering
53    pub(crate) highlights_cache: RefCell<HightlightCache>,
54
55    /// Cache for line diff highlights to speed up rendering
56    pub(crate) line_diff_cache: RefCell<LineDiffCache>,
57
58    /// Controls whether to highlight occurrences of the word under the cursor
59    pub(crate) word_highlight_enabled: bool,
60
61    /// Cache for word highlight ranges: (cursor, list of ranges)
62    pub(crate) word_highlight_cache: RefCell<Option<(usize, Vec<(usize, usize)>)>>,
63
64    /// Controls when to show the line numbers
65    pub(crate) show_line_numbers: bool,
66
67    /// Controls whether the code-fold gutter is shown and interactive.
68    pub(crate) code_folding_options: CodeFoldingOptions,
69
70    /// Controls the left padding before writing the code
71    pub(crate) left_code_padding: usize,
72
73    /// Current document-to-screen view mode.
74    pub(crate) view_mode: ViewMode,
75
76    /// Original code snapshot used for diff and ghost-line highlighting.
77    pub(crate) original_code: Option<Code>,
78
79    /// Options for diff and diff-focus modes.
80    pub(crate) diff_options: DiffOptions,
81
82    /// Derived view rows and line mappings used for scrolling, rendering, and navigation.
83    pub(crate) view: View,
84}
85
86impl Editor {
87    pub fn new(lang: &str, text: &str, theme: Vec<(&str, &str)>) -> Result<Self> {
88        Self::new_with_highlights(lang, text, theme, None)
89    }
90
91    pub fn new_with_highlights(
92        lang: &str,
93        text: &str,
94        theme: Vec<(&str, &str)>,
95        custom_highlights: Option<HashMap<String, String>>,
96    ) -> Result<Self> {
97        let code = Code::new(text, lang, custom_highlights.clone())
98            .or_else(|_| Code::new(text, "text", custom_highlights))?;
99
100        let theme = Self::build_theme(&theme);
101        let highlights_cache = RefCell::new(HashMap::new());
102        let line_diff_cache = RefCell::new(HashMap::new());
103        let view = View::new(&code, ViewMode::Plain);
104
105        Ok(Self {
106            code,
107            cursor: 0,
108            offset_y: 0,
109            offset_x: 0,
110            theme,
111            selection: None,
112            clicks: ClickTracker::new(Duration::from_millis(700)),
113            selection_snap: SelectionSnap::None,
114            clipboard: None,
115            marks: None,
116            highlights_cache,
117            line_diff_cache,
118            word_highlight_enabled: true,
119            word_highlight_cache: RefCell::new(None),
120            show_line_numbers: true,
121            code_folding_options: CodeFoldingOptions::default(),
122            left_code_padding: 2,
123            view_mode: ViewMode::Plain,
124            original_code: None,
125            diff_options: DiffOptions::default(),
126            view,
127        })
128    }
129
130    pub(crate) fn get_line_number_width(&self) -> usize {
131        let fold_gutter_width = self.fold_gutter_width();
132        if self.show_line_numbers {
133            let total_lines = self.code.len_lines();
134            let max_line_number = total_lines.max(1);
135            let line_number_digits = max_line_number.to_string().len().max(5);
136            line_number_digits + self.left_code_padding + fold_gutter_width
137        } else {
138            self.left_code_padding + fold_gutter_width
139        }
140    }
141
142    pub fn focus(&mut self, area: &Rect) {
143        self.fit_cursor();
144        if self.is_diff_focus_active() {
145            self.clamp_cursor_to_focus_rows();
146        }
147        self.clamp_offset_y();
148
149        let width = area.width as usize;
150        let height = area.height as usize;
151        let line_number_width = self.get_line_number_width();
152
153        let line = self.code.char_to_line(self.cursor);
154        let col = self.cursor - self.code.line_to_char(line);
155
156        let visible_width = width.saturating_sub(line_number_width);
157        let visible_height = height;
158
159        let step_size = 10;
160        if col < self.offset_x {
161            self.offset_x = col.saturating_sub(step_size);
162        } else if col >= self.offset_x + visible_width {
163            self.offset_x = col.saturating_sub(visible_width.saturating_sub(step_size));
164        }
165
166        let visual_line = self.visual_line_idx(line);
167        if visual_line == usize::MAX {
168            return;
169        }
170
171        if visual_line < self.offset_y {
172            self.offset_y = visual_line;
173        } else if visual_line >= self.offset_y + visible_height {
174            self.offset_y = visual_line.saturating_sub(visible_height.saturating_sub(1));
175        }
176    }
177
178    /// Handles a mouse button press at the given cursor position, updating selection and click state.
179    pub fn handle_mouse_down(&mut self, cursor: usize) {
180        let kind = self.clicks.register(cursor);
181        let (start, end, snap) = match kind {
182            ClickKind::Triple => {
183                let (line_start, line_end) = self.code.line_boundaries(cursor);
184                (line_start, line_end, SelectionSnap::Line { anchor: cursor })
185            }
186            ClickKind::Double => {
187                let (word_start, word_end) = self.code.word_boundaries(cursor);
188                (word_start, word_end, SelectionSnap::Word { anchor: cursor })
189            }
190            ClickKind::Single => (cursor, cursor, SelectionSnap::None),
191        };
192
193        self.selection = Some(Selection::from_anchor_and_cursor(start, end));
194        self.cursor = end;
195        self.selection_snap = snap;
196    }
197
198    /// Handles a mouse drag event at the given cursor position, extending the selection.
199    pub fn handle_mouse_drag(&mut self, cursor: usize) {
200        match self.selection_snap {
201            SelectionSnap::Line { anchor } => {
202                let (anchor_start, anchor_end) = self.code.line_boundaries(anchor);
203                let (cur_start, cur_end) = self.code.line_boundaries(cursor);
204
205                let (sel_start, sel_end, new_cursor) = match cursor.cmp(&anchor) {
206                    Ordering::Greater => (anchor_start, cur_end, cur_end), // forward
207                    Ordering::Less => (cur_start, anchor_end, cur_start),  // backward
208                    Ordering::Equal => (anchor_start, anchor_end, anchor_end),
209                };
210
211                self.selection = Some(Selection::from_anchor_and_cursor(sel_start, sel_end));
212                self.cursor = new_cursor;
213            }
214            SelectionSnap::Word { anchor } => {
215                let (anchor_start, anchor_end) = self.code.word_boundaries(anchor);
216                let (cur_start, cur_end) = self.code.word_boundaries(cursor);
217
218                let (sel_start, sel_end, new_cursor) = match cursor.cmp(&anchor) {
219                    Ordering::Greater => (anchor_start, cur_end, cur_end), // forward
220                    Ordering::Less => (cur_start, anchor_end, cur_start),  // backward
221                    Ordering::Equal => (anchor_start, anchor_end, anchor_end),
222                };
223
224                self.selection = Some(Selection::from_anchor_and_cursor(sel_start, sel_end));
225                self.cursor = new_cursor;
226            }
227            SelectionSnap::None => {
228                let anchor = self.selection_anchor();
229                self.selection = Some(Selection::from_anchor_and_cursor(anchor, cursor));
230                self.cursor = cursor;
231            }
232        }
233    }
234
235    /// Converts mouse coordinates to a cursor position within the editor area, returning `None` if outside.
236    pub fn cursor_from_mouse(&self, mouse_x: u16, mouse_y: u16, area: &Rect) -> Option<usize> {
237        let line_number_width = self.get_line_number_width() as u16;
238
239        if mouse_y < area.top()
240            || mouse_y >= area.bottom()
241            || mouse_x < area.left() + line_number_width
242        {
243            return None;
244        }
245
246        let clicked_visual_row = (mouse_y - area.top()) as usize + self.offset_y;
247        let clicked_row = self.line_for_visual_row(clicked_visual_row)?;
248        if clicked_row >= self.code.len_lines() {
249            return None;
250        }
251
252        let clicked_col = (mouse_x - area.left() - line_number_width) as usize;
253
254        let line_start_char = self.code.line_to_char(clicked_row);
255        let line_len = self.code.line_len(clicked_row);
256
257        let start_col = self.offset_x.min(line_len);
258        let end_col = line_len;
259
260        let char_start = line_start_char + start_col;
261        let char_end = line_start_char + end_col;
262
263        let mut current_col = 0;
264        let mut char_idx = start_col;
265        let visible_chars = self.code.char_slice(char_start, char_end);
266        for g in RopeGraphemes::new(&visible_chars) {
267            let (g_width, g_chars) = grapheme_width_and_chars_len(g);
268            if current_col + g_width > clicked_col {
269                break;
270            }
271            current_col += g_width;
272            char_idx += g_chars;
273        }
274
275        let line = self
276            .code
277            .char_slice(line_start_char, line_start_char + line_len);
278        let visual_width: usize = RopeGraphemes::new(&line).map(grapheme_width).sum();
279
280        if clicked_col + self.offset_x >= visual_width {
281            let mut end_idx = line.len_chars();
282            if end_idx > 0 && line.char(end_idx - 1) == '\n' {
283                end_idx -= 1;
284            }
285            char_idx = end_idx;
286        }
287
288        Some(line_start_char + char_idx)
289    }
290
291    pub(crate) fn toggle_fold_at_mouse(&mut self, mouse_x: u16, mouse_y: u16, area: &Rect) -> bool {
292        if !self.is_code_folding_enabled() {
293            return false;
294        }
295
296        let line_number_width = self.get_line_number_width();
297        let fold_gutter_width = self.fold_gutter_width();
298        let Some(fold_gutter_start) = line_number_width.checked_sub(fold_gutter_width) else {
299            return false;
300        };
301
302        if mouse_x < area.left() + fold_gutter_start as u16
303            || mouse_x >= area.left() + line_number_width as u16
304            || mouse_y < area.top()
305            || mouse_y >= area.bottom()
306        {
307            return false;
308        }
309
310        let visual_row = self.offset_y + (mouse_y - area.top()) as usize;
311        let Some(line) = self.line_for_visual_row(visual_row) else {
312            return false;
313        };
314
315        self.toggle_fold_at_line(line)
316    }
317
318    pub fn expand_hidden_diff_at_mouse(&mut self, mouse_x: u16, mouse_y: u16, area: &Rect) -> bool {
319        if !self.is_diff_focus_active() {
320            return false;
321        }
322
323        let line_number_width = self.get_line_number_width() as u16;
324        if mouse_y < area.top()
325            || mouse_y >= area.bottom()
326            || mouse_x < area.left() + line_number_width
327        {
328            return false;
329        }
330
331        let clicked_visual_row = (mouse_y - area.top()) as usize + self.offset_y;
332        let text_x = area.left() + line_number_width;
333        let clicked_col = mouse_x.saturating_sub(text_x) as usize;
334        let visible_width = area.width.saturating_sub(line_number_width) as usize;
335
336        let expanded = self.view.expand_hidden_at_visual_row(
337            &self.code,
338            self.original_code.as_ref(),
339            self.active_view_mode(),
340            clicked_visual_row,
341            clicked_col,
342            visible_width,
343            self.diff_options.expand_amount,
344        );
345
346        if expanded {
347            self.clamp_offset_y();
348        }
349
350        expanded
351    }
352
353    /// Clears any active selection.
354    pub fn clear_selection(&mut self) {
355        self.selection = None;
356    }
357
358    /// Extends or starts a selection from the current cursor to `new_cursor`.
359    pub fn extend_selection(&mut self, new_cursor: usize) {
360        // If there was already a selection, preserve the anchor (start point)
361        // otherwise, use the current cursor as the anchor.
362        let anchor = self.selection_anchor();
363        self.selection = Some(Selection::from_anchor_and_cursor(anchor, new_cursor));
364    }
365
366    /// Returns the selection anchor position, or the cursor if no selection exists.
367    pub fn selection_anchor(&self) -> usize {
368        self.selection
369            .as_ref()
370            .map(|s| {
371                if self.cursor == s.start {
372                    s.end
373                } else {
374                    s.start
375                }
376            })
377            .unwrap_or(self.cursor)
378    }
379
380    pub fn apply<A: Action>(&mut self, mut action: A) {
381        action.apply(self);
382    }
383
384    pub fn set_content(&mut self, content: &str) {
385        self.code.tx();
386        self.code.set_state_before(self.cursor, self.selection);
387        self.code.remove(0, self.code.len());
388        self.code.insert(0, content);
389        self.code.set_state_after(self.cursor, self.selection);
390        self.code.commit();
391        self.reset_highlight_cache();
392    }
393
394    pub fn set_original_code(&mut self, content: &str) -> Result<()> {
395        let original = Code::new(content, self.code_ref().lang(), None)
396            .or_else(|_| Code::new(content, "text", None))?;
397        self.highlights_cache.borrow_mut().clear();
398        self.line_diff_cache.borrow_mut().clear();
399        self.original_code = Some(original);
400        self.rebuild_view();
401        Ok(())
402    }
403
404    pub fn clear_original_code(&mut self) {
405        self.highlights_cache.borrow_mut().clear();
406        self.line_diff_cache.borrow_mut().clear();
407        self.original_code = None;
408        self.rebuild_view();
409        self.clamp_offset_y();
410    }
411
412    pub fn has_diff(&self) -> bool {
413        self.view_mode.has_diff() && self.original_code.is_some()
414    }
415
416    pub fn set_diff_enabled(&mut self, enabled: bool) {
417        if enabled {
418            if self.view_mode == ViewMode::Plain {
419                self.view_mode = ViewMode::Diff;
420            }
421        } else {
422            self.view_mode = ViewMode::Plain;
423        }
424        self.rebuild_view();
425        self.clamp_offset_y();
426    }
427
428    pub fn is_diff_enabled(&self) -> bool {
429        self.view_mode.has_diff()
430    }
431
432    pub fn set_diff_focus_enabled(&mut self, enabled: bool) {
433        self.view_mode = if enabled {
434            ViewMode::DiffFocus {
435                context_lines: self.diff_options.focus_context,
436            }
437        } else if self.view_mode.has_diff() {
438            ViewMode::Diff
439        } else {
440            ViewMode::Plain
441        };
442        self.rebuild_view();
443        self.clamp_cursor_to_focus_rows();
444        self.clamp_offset_y();
445    }
446
447    pub fn toggle_diff_focus(&mut self) {
448        self.set_diff_focus_enabled(!self.view_mode.is_diff_focus());
449    }
450
451    pub fn set_diff_focus_context(&mut self, context_lines: usize) {
452        self.diff_options.focus_context = context_lines;
453        if self.view_mode.is_diff_focus() {
454            self.view_mode = ViewMode::DiffFocus { context_lines };
455        }
456        self.rebuild_view();
457        self.clamp_cursor_to_focus_rows();
458        self.clamp_offset_y();
459    }
460
461    pub fn set_diff_expand_amount(&mut self, amount: usize) {
462        self.diff_options.expand_amount = amount;
463        self.rebuild_view();
464    }
465
466    pub fn set_diff_options(&mut self, options: DiffOptions) {
467        self.diff_options = options;
468        if self.view_mode.is_diff_focus() {
469            self.view_mode = ViewMode::DiffFocus {
470                context_lines: options.focus_context,
471            };
472        }
473        self.rebuild_view();
474        self.clamp_cursor_to_focus_rows();
475        self.clamp_offset_y();
476    }
477
478    pub fn diff_options(&self) -> DiffOptions {
479        self.diff_options
480    }
481
482    pub fn apply_batch(&mut self, batch: &EditBatch) {
483        self.code.tx();
484
485        if let Some(state) = &batch.state_before {
486            self.code.set_state_before(state.offset, state.selection);
487        }
488        if let Some(state) = &batch.state_after {
489            self.code.set_state_after(state.offset, state.selection);
490        }
491
492        for edit in &batch.edits {
493            match edit.operation {
494                Operation::Insert => {
495                    self.code.insert(edit.start, &edit.text);
496                }
497                Operation::Remove => {
498                    self.code
499                        .remove(edit.start, edit.start + edit.text.chars().count());
500                }
501            }
502        }
503        self.code.commit();
504        self.reset_highlight_cache();
505    }
506
507    pub fn set_cursor(&mut self, cursor: usize) {
508        self.cursor = cursor;
509        self.fit_cursor();
510    }
511
512    /// Toggles the Rust Tree-sitter fold that begins on `line_idx`.
513    pub fn toggle_fold_at_line(&mut self, line_idx: usize) -> bool {
514        if !self.code_folding_options.enabled {
515            return false;
516        }
517        let top_line = self.line_for_visual_row(self.offset_y);
518        let toggled = self.view.toggle_code_fold(
519            &self.code,
520            self.original_code.as_ref(),
521            self.active_view_mode(),
522            line_idx,
523        );
524        if toggled {
525            if let Some(top_line) = top_line {
526                let visual_line = self.visual_line_idx(top_line);
527                if visual_line != usize::MAX {
528                    self.offset_y = visual_line;
529                }
530            }
531            self.clamp_offset_y();
532        }
533        toggled
534    }
535
536    pub fn toggle_fold_at_cursor(&mut self) -> bool {
537        let line_idx = self.code.char_to_line(self.cursor);
538        self.toggle_fold_at_line(line_idx)
539    }
540
541    pub fn set_code_folding_enabled(&mut self, enabled: bool) {
542        self.code_folding_options.enabled = enabled;
543        if !enabled {
544            self.view.clear_code_folds();
545        }
546        self.rebuild_view();
547    }
548
549    pub fn is_code_folding_enabled(&self) -> bool {
550        self.code_folding_options.enabled
551    }
552
553    pub fn set_code_folding_options(&mut self, options: CodeFoldingOptions) {
554        let enabled = options.enabled;
555        self.code_folding_options = options;
556        if !enabled {
557            self.view.clear_code_folds();
558        }
559        self.rebuild_view();
560    }
561
562    pub fn code_folding_options(&self) -> CodeFoldingOptions {
563        self.code_folding_options.clone()
564    }
565
566    pub(crate) fn fold_gutter_width(&self) -> usize {
567        if !self.code_folding_options.enabled {
568            return 0;
569        }
570        self.code_folding_options
571            .indicators
572            .expanded
573            .width()
574            .max(self.code_folding_options.indicators.collapsed.width())
575            + 1
576    }
577
578    pub(crate) fn code_fold_indicator(&self, line_idx: usize) -> Option<bool> {
579        self.code_folding_options
580            .enabled
581            .then(|| self.view.code_fold_indicator(&self.code, line_idx))
582            .flatten()
583    }
584
585    pub fn fit_cursor(&mut self) {
586        // make sure cursor is not out of bounds
587        let len = self.code.len_chars();
588        self.cursor = self.cursor.min(len);
589
590        // make sure cursor is not out of bounds on the line
591        let (row, col) = self.code.point(self.cursor);
592        if col > self.code.line_len(row) {
593            self.cursor = self.code.line_to_char(row) + self.code.line_len(row);
594        }
595    }
596
597    pub fn scroll_up(&mut self) {
598        if self.offset_y > 0 {
599            self.offset_y -= 1;
600        }
601    }
602
603    pub fn scroll_down(&mut self, area_height: usize) {
604        let len_lines = self.visual_len_lines();
605        if self.offset_y < len_lines.saturating_sub(area_height) {
606            self.offset_y += 1;
607        }
608    }
609
610    pub fn build_theme(theme: &Vec<(&str, &str)>) -> Theme {
611        theme
612            .into_iter()
613            .map(|(name, hex)| {
614                let (r, g, b) = utils::rgb(hex);
615                let color = Color::Rgb(r, g, b);
616                let style = match *name {
617                    "diff_added"
618                    | "diff_added_word"
619                    | "diff_deleted"
620                    | "diff_deleted_word"
621                    | "word_highlight" => Style::default().bg(color),
622                    _ => Style::default().fg(color),
623                };
624                (name.to_string(), style)
625            })
626            .collect()
627    }
628
629    pub(crate) fn theme_style(&self, key: &str) -> Style {
630        self.theme.get(key).cloned().unwrap_or_default()
631    }
632
633    pub fn get_content(&self) -> String {
634        self.code.get_content()
635    }
636
637    pub fn get_content_slice(&self, start: usize, end: usize) -> String {
638        self.code.slice(start, end)
639    }
640
641    pub fn get_cursor(&self) -> usize {
642        self.cursor
643    }
644
645    pub fn set_clipboard(&mut self, text: &str) -> Result<()> {
646        arboard::Clipboard::new()
647            .and_then(|mut c| c.set_text(text.to_string()))
648            .unwrap_or_else(|_| self.clipboard = Some(text.to_string()));
649        Ok(())
650    }
651
652    pub fn get_clipboard(&self) -> Result<String> {
653        arboard::Clipboard::new()
654            .and_then(|mut c| c.get_text())
655            .ok()
656            .or_else(|| self.clipboard.clone())
657            .ok_or_else(|| anyhow!("cant get clipboard"))
658    }
659
660    pub fn set_marks(&mut self, marks: Vec<(usize, usize, &str)>) {
661        self.marks = Some(
662            marks
663                .into_iter()
664                .map(|(start, end, color)| {
665                    let (r, g, b) = utils::rgb(color);
666                    (start, end, Color::Rgb(r, g, b))
667                })
668                .collect(),
669        );
670    }
671
672    pub fn remove_marks(&mut self) {
673        self.marks = None;
674    }
675
676    pub fn has_marks(&self) -> bool {
677        self.marks.is_some()
678    }
679
680    pub fn get_marks(&self) -> Option<&Vec<(usize, usize, Color)>> {
681        self.marks.as_ref()
682    }
683
684    pub fn get_selection_text(&mut self) -> Option<String> {
685        if let Some(selection) = &self.selection
686            && !selection.is_empty()
687        {
688            let text = self.code.slice(selection.start, selection.end);
689            return Some(text);
690        }
691        None
692    }
693
694    pub fn get_selection(&mut self) -> Option<Selection> {
695        return self.selection;
696    }
697
698    pub fn set_selection(&mut self, selection: Option<Selection>) {
699        self.selection = selection;
700    }
701
702    pub fn set_offset_y(&mut self, offset_y: usize) {
703        self.offset_y = offset_y.min(self.visual_len_lines().saturating_sub(1));
704    }
705
706    pub fn set_offset_x(&mut self, offset_x: usize) {
707        self.offset_x = offset_x;
708    }
709
710    pub fn get_offset_y(&self) -> usize {
711        self.offset_y
712    }
713
714    pub fn get_offset_x(&self) -> usize {
715        self.offset_x
716    }
717
718    pub(crate) fn visual_len_lines(&self) -> usize {
719        self.view
720            .visual_len_lines(&self.code, self.active_view_mode())
721    }
722
723    pub(crate) fn line_for_visual_row(&self, visual_row: usize) -> Option<usize> {
724        self.view
725            .line_for_visual_row(&self.code, self.active_view_mode(), visual_row)
726    }
727
728    pub(crate) fn visual_row(&self, visual_row: usize) -> Option<VisualRow> {
729        if self.has_diff() || !self.view.rows().is_empty() {
730            self.view.rows().get(visual_row).cloned()
731        } else if visual_row < self.code.len_lines() {
732            Some(VisualRow::Real {
733                line_idx: visual_row,
734                is_added: false,
735                orig_line_idx: None,
736            })
737        } else {
738            None
739        }
740    }
741
742    pub(crate) fn visual_line_idx(&self, line_idx: usize) -> usize {
743        self.view
744            .visual_row_for_line(self.active_view_mode(), line_idx)
745            .unwrap_or(usize::MAX)
746    }
747
748    pub fn code_mut(&mut self) -> &mut Code {
749        &mut self.code
750    }
751
752    pub fn code_ref(&self) -> &Code {
753        &self.code
754    }
755
756    /// Set the change callback function for handling document changes
757    pub fn set_change_callback(
758        &mut self,
759        callback: Box<dyn Fn(Vec<(usize, usize, usize, usize, String)>)>,
760    ) {
761        self.code.set_change_callback(callback);
762    }
763
764    pub fn highlight_interval(
765        &self,
766        start: usize,
767        end: usize,
768        theme: &Theme,
769    ) -> Vec<(usize, usize, Style)> {
770        let mut cache = self.highlights_cache.borrow_mut();
771        let key = (0, start, end);
772        if let Some(v) = cache.get(&key) {
773            return v.clone();
774        }
775
776        let highlights = self.code.highlight_interval(start, end, theme);
777        cache.insert(key, highlights.clone());
778        highlights
779    }
780
781    pub fn highlight_interval_original(
782        &self,
783        start: usize,
784        end: usize,
785        theme: &Theme,
786    ) -> Vec<(usize, usize, Style)> {
787        let Some(original) = &self.original_code else {
788            return Vec::new();
789        };
790        let mut cache = self.highlights_cache.borrow_mut();
791        let key = (1, start, end);
792        if let Some(v) = cache.get(&key) {
793            return v.clone();
794        }
795
796        let highlights = original.highlight_interval(start, end, theme);
797        cache.insert(key, highlights.clone());
798        highlights
799    }
800
801    pub fn word_highlight_ranges(&self) -> Vec<(usize, usize)> {
802        if !self.word_highlight_enabled {
803            return Vec::new();
804        }
805
806        let mut cache = self.word_highlight_cache.borrow_mut();
807        if let Some((cached_cursor, cached_ranges)) = &*cache {
808            if *cached_cursor == self.cursor {
809                return cached_ranges.clone();
810            }
811        }
812
813        let (start, end) = self.code.word_boundaries(self.cursor);
814        if start == end {
815            *cache = Some((self.cursor, Vec::new()));
816            return Vec::new();
817        }
818
819        let word = self.code.slice(start, end);
820        if word.is_empty() {
821            *cache = Some((self.cursor, Vec::new()));
822            return Vec::new();
823        }
824
825        let is_word_char = |c: char| c.is_alphanumeric() || c == '_';
826        if !word.chars().next().map_or(false, is_word_char) {
827            *cache = Some((self.cursor, Vec::new()));
828            return Vec::new();
829        }
830
831        let mut ranges = Vec::new();
832        let word_chars: Vec<char> = word.chars().collect();
833        let word_len = word_chars.len();
834        let content = &self.code.content;
835        let total_chars = content.len_chars();
836
837        if total_chars >= word_len {
838            for line_idx in 0..content.len_lines() {
839                let line = content.line(line_idx);
840                let line_len_chars = line.len_chars();
841                if line_len_chars < word_len {
842                    continue;
843                }
844
845                let line_chars: Vec<char> = line.chars().collect();
846                let line_start_char = content.line_to_char(line_idx);
847
848                for i in 0..=(line_chars.len() - word_len) {
849                    if line_chars[i..(i + word_len)] == word_chars {
850                        let prev_ok = i == 0 || !is_word_char(line_chars[i - 1]);
851                        let next_idx = i + word_len;
852                        let next_ok = next_idx >= line_chars.len() || !is_word_char(line_chars[next_idx]);
853                        if prev_ok && next_ok {
854                            ranges.push((line_start_char + i, line_start_char + next_idx));
855                        }
856                    }
857                }
858            }
859        }
860
861        *cache = Some((self.cursor, ranges.clone()));
862        ranges
863    }
864
865    pub fn set_word_highlight_enabled(&mut self, enabled: bool) {
866        self.word_highlight_enabled = enabled;
867        if !enabled {
868            self.word_highlight_cache.borrow_mut().take();
869        }
870    }
871
872    pub fn word_highlight_enabled(&self) -> bool {
873        self.word_highlight_enabled
874    }
875
876    pub fn reset_highlight_cache(&mut self) {
877        self.highlights_cache.borrow_mut().clear();
878        self.line_diff_cache.borrow_mut().clear();
879        self.word_highlight_cache.borrow_mut().take();
880        self.rebuild_view();
881    }
882
883    pub fn get_line_diff(
884        &self,
885        orig_idx: usize,
886        curr_idx: usize,
887        is_ghost: bool,
888    ) -> Vec<(usize, usize)> {
889        let Some(orig_code) = &self.original_code else {
890            return Vec::new();
891        };
892
893        let mut cache = self.line_diff_cache.borrow_mut();
894        let key = (orig_idx, curr_idx);
895
896        let diff = cache.entry(key).or_insert_with(|| {
897            crate::diff::compute_line_diff(orig_code, orig_idx, &self.code, curr_idx)
898        });
899
900        if is_ghost {
901            diff.deletions.clone()
902        } else {
903            diff.additions.clone()
904        }
905    }
906}
907
908impl Editor {
909
910    fn clamp_offset_y(&mut self) {
911        self.offset_y = self.offset_y.min(self.visual_len_lines().saturating_sub(1));
912    }
913
914    pub(crate) fn prev_line(&self, line_idx: usize) -> Option<usize> {
915        self.view.prev_line(self.active_view_mode(), line_idx)
916    }
917
918    pub(crate) fn next_line(&self, line_idx: usize) -> Option<usize> {
919        self.view
920            .next_line(&self.code, self.active_view_mode(), line_idx)
921    }
922
923    pub(crate) fn is_diff_focus_active(&self) -> bool {
924        self.has_diff() && self.view_mode.is_diff_focus()
925    }
926
927    pub(crate) fn clamp_cursor_to_focus_rows(&mut self) {
928        let clear_selection = self.is_diff_focus_active();
929        let (cursor_line, cursor_char_col) = self.code.point(self.cursor);
930        if self.line_visible(cursor_line) {
931            return;
932        }
933
934        let current_visual_col = self.code.char_col_to_visual(cursor_line, cursor_char_col);
935        let Some(target_line) = self.nearest_focus_real_line(cursor_line) else {
936            return;
937        };
938        let target_start = self.code.line_to_char(target_line);
939        let target_len = self.code.line_len(target_line);
940        let target_col = self
941            .code
942            .visual_to_char_col(target_line, current_visual_col)
943            .min(target_len);
944
945        self.cursor = target_start + target_col;
946        if clear_selection {
947            self.clear_selection();
948        }
949    }
950
951    pub(crate) fn line_visible(&self, line_idx: usize) -> bool {
952        self.view.line_visible(self.active_view_mode(), line_idx)
953    }
954
955    fn nearest_focus_real_line(&self, line_idx: usize) -> Option<usize> {
956        self.view
957            .nearest_line(&self.code, self.active_view_mode(), line_idx)
958    }
959
960    /// calculates visible cursor position
961    pub fn get_visible_cursor(&self, area: &Rect) -> Option<(u16, u16)> {
962        let line_number_width = self.get_line_number_width();
963
964        let (cursor_line, cursor_char_col) = self.code.point(self.cursor);
965        let cursor_visual_line = self.visual_line_idx(cursor_line);
966
967        if cursor_visual_line >= self.offset_y
968            && cursor_visual_line < self.offset_y + area.height as usize
969        {
970            let line_start_char = self.code.line_to_char(cursor_line);
971            let line_len = self.code.line_len(cursor_line);
972
973            let max_x = (area.width as usize).saturating_sub(line_number_width);
974            let start_col = self.offset_x;
975
976            let cursor_visual_col: usize = {
977                let slice = self.code.char_slice(
978                    line_start_char,
979                    line_start_char + cursor_char_col.min(line_len),
980                );
981                RopeGraphemes::new(&slice).map(grapheme_width).sum()
982            };
983
984            let offset_visual_col: usize = {
985                let slice = self
986                    .code
987                    .char_slice(line_start_char, line_start_char + start_col.min(line_len));
988                RopeGraphemes::new(&slice).map(grapheme_width).sum()
989            };
990
991            let relative_visual_col = cursor_visual_col.saturating_sub(offset_visual_col);
992            let visible_x = relative_visual_col.min(max_x);
993
994            let cursor_x = area.left() + (line_number_width + visible_x) as u16;
995            let cursor_y = area.top() + (cursor_visual_line - self.offset_y) as u16;
996
997            if cursor_x < area.right() && cursor_y < area.bottom() {
998                return Some((cursor_x, cursor_y));
999            }
1000        }
1001
1002        return None;
1003    }
1004
1005    pub fn show_line_numbers(&mut self, show: bool) {
1006        self.show_line_numbers = show
1007    }
1008
1009    pub fn set_left_code_padding(&mut self, char_count: usize) {
1010        self.left_code_padding = char_count
1011    }
1012
1013    fn active_view_mode(&self) -> ViewMode {
1014        if self.original_code.is_some() {
1015            self.view_mode
1016        } else {
1017            ViewMode::Plain
1018        }
1019    }
1020
1021    pub(crate) fn rebuild_view(&mut self) {
1022        self.view.rebuild(
1023            &self.code,
1024            self.original_code.as_ref(),
1025            self.active_view_mode(),
1026        );
1027    }
1028}