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