ratatui-code-editor 0.0.5

ratatui-code-editor is A code editor widget for ratatui, built with syntax highlighting powered by Tree-sitter.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
use crate::actions::*;
use crate::click::{ClickKind, ClickTracker};
use crate::code::Code;
use crate::code::{EditBatch, Operation};
use crate::code::{RopeGraphemes, grapheme_width, grapheme_width_and_chars_len};
use crate::selection::{Selection, SelectionSnap};
use crate::types::{CodeFoldingOptions, DiffOptions, HightlightCache, Theme, VisualRow};
use crate::utils;
use crate::view::{View, ViewMode};
use anyhow::{Result, anyhow};
use ratatui_core::layout::Rect;
use ratatui_core::style::{Color, Style};
use std::cell::RefCell;
use std::cmp::Ordering;
use std::collections::HashMap;
use std::time::Duration;
use unicode_width::UnicodeWidthStr;

/// Represents the text editor, which holds the code buffer, cursor, selection,
/// theme, scroll offsets, highlight cache, clipboard, and user mark intervals.
pub struct Editor {
    /// Code buffer and editing/highlighting logic for the current language
    pub(crate) code: Code,

    /// Current cursor position as a character index in the document
    pub(crate) cursor: usize,

    /// Vertical scroll offset: index of the first visible line
    pub(crate) offset_y: usize,

    /// Horizontal scroll offset in characters (visual columns)
    pub(crate) offset_x: usize,

    /// Syntax theme: mapping of token name to ratatui Style
    pub(crate) theme: Theme,

    /// Current text selection, if any
    pub(crate) selection: Option<Selection>,

    /// Click tracker to detect single/double/triple clicks
    pub(crate) clicks: ClickTracker,

    /// Selection snapping mode (to word, to line, or none)
    pub(crate) selection_snap: SelectionSnap,

    /// Fallback clipboard storage when the system clipboard is unavailable
    pub(crate) clipboard: Option<String>,

    /// User marks for intervals: (start, end, color)
    pub(crate) marks: Option<Vec<(usize, usize, Color)>>,

    /// Syntax highlight cache by intervals to speed up rendering
    pub(crate) highlights_cache: RefCell<HightlightCache>,

    /// Controls when to show the line numbers
    pub(crate) show_line_numbers: bool,

    /// Controls whether the code-fold gutter is shown and interactive.
    pub(crate) code_folding_options: CodeFoldingOptions,

    /// Controls the left padding before writing the code
    pub(crate) left_code_padding: usize,

    /// Current document-to-screen view mode.
    pub(crate) view_mode: ViewMode,

    /// Original code snapshot used for diff and ghost-line highlighting.
    pub(crate) original_code: Option<Code>,

    /// Options for diff and diff-focus modes.
    pub(crate) diff_options: DiffOptions,

    /// Derived view rows and line mappings used for scrolling, rendering, and navigation.
    pub(crate) view: View,
}

impl Editor {
    pub fn new(lang: &str, text: &str, theme: Vec<(&str, &str)>) -> Result<Self> {
        Self::new_with_highlights(lang, text, theme, None)
    }

    pub fn new_with_highlights(
        lang: &str,
        text: &str,
        theme: Vec<(&str, &str)>,
        custom_highlights: Option<HashMap<String, String>>,
    ) -> Result<Self> {
        let code = Code::new(text, lang, custom_highlights.clone())
            .or_else(|_| Code::new(text, "text", custom_highlights))?;

        let theme = Self::build_theme(&theme);
        let highlights_cache = RefCell::new(HashMap::new());
        let view = View::new(&code, ViewMode::Plain);

        Ok(Self {
            code,
            cursor: 0,
            offset_y: 0,
            offset_x: 0,
            theme,
            selection: None,
            clicks: ClickTracker::new(Duration::from_millis(700)),
            selection_snap: SelectionSnap::None,
            clipboard: None,
            marks: None,
            highlights_cache,
            show_line_numbers: true,
            code_folding_options: CodeFoldingOptions::default(),
            left_code_padding: 2,
            view_mode: ViewMode::Plain,
            original_code: None,
            diff_options: DiffOptions::default(),
            view,
        })
    }

    pub(crate) fn get_line_number_width(&self) -> usize {
        let fold_gutter_width = self.fold_gutter_width();
        if self.show_line_numbers {
            let total_lines = self.code.len_lines();
            let max_line_number = total_lines.max(1);
            let line_number_digits = max_line_number.to_string().len().max(5);
            line_number_digits + self.left_code_padding + fold_gutter_width
        } else {
            self.left_code_padding + fold_gutter_width
        }
    }

    pub fn focus(&mut self, area: &Rect) {
        self.fit_cursor();
        if self.is_diff_focus_active() {
            self.clamp_cursor_to_focus_rows();
        }
        self.clamp_offset_y();

        let width = area.width as usize;
        let height = area.height as usize;
        let line_number_width = self.get_line_number_width();

        let line = self.code.char_to_line(self.cursor);
        let col = self.cursor - self.code.line_to_char(line);

        let visible_width = width.saturating_sub(line_number_width);
        let visible_height = height;

        let step_size = 10;
        if col < self.offset_x {
            self.offset_x = col.saturating_sub(step_size);
        } else if col >= self.offset_x + visible_width {
            self.offset_x = col.saturating_sub(visible_width.saturating_sub(step_size));
        }

        let visual_line = self.visual_line_idx(line);
        if visual_line == usize::MAX {
            return;
        }

        if visual_line < self.offset_y {
            self.offset_y = visual_line;
        } else if visual_line >= self.offset_y + visible_height {
            self.offset_y = visual_line.saturating_sub(visible_height.saturating_sub(1));
        }
    }

    /// Handles a mouse button press at the given cursor position, updating selection and click state.
    pub fn handle_mouse_down(&mut self, cursor: usize) {
        let kind = self.clicks.register(cursor);
        let (start, end, snap) = match kind {
            ClickKind::Triple => {
                let (line_start, line_end) = self.code.line_boundaries(cursor);
                (line_start, line_end, SelectionSnap::Line { anchor: cursor })
            }
            ClickKind::Double => {
                let (word_start, word_end) = self.code.word_boundaries(cursor);
                (word_start, word_end, SelectionSnap::Word { anchor: cursor })
            }
            ClickKind::Single => (cursor, cursor, SelectionSnap::None),
        };

        self.selection = Some(Selection::from_anchor_and_cursor(start, end));
        self.cursor = end;
        self.selection_snap = snap;
    }

    /// Handles a mouse drag event at the given cursor position, extending the selection.
    pub fn handle_mouse_drag(&mut self, cursor: usize) {
        match self.selection_snap {
            SelectionSnap::Line { anchor } => {
                let (anchor_start, anchor_end) = self.code.line_boundaries(anchor);
                let (cur_start, cur_end) = self.code.line_boundaries(cursor);

                let (sel_start, sel_end, new_cursor) = match cursor.cmp(&anchor) {
                    Ordering::Greater => (anchor_start, cur_end, cur_end), // forward
                    Ordering::Less => (cur_start, anchor_end, cur_start),  // backward
                    Ordering::Equal => (anchor_start, anchor_end, anchor_end),
                };

                self.selection = Some(Selection::from_anchor_and_cursor(sel_start, sel_end));
                self.cursor = new_cursor;
            }
            SelectionSnap::Word { anchor } => {
                let (anchor_start, anchor_end) = self.code.word_boundaries(anchor);
                let (cur_start, cur_end) = self.code.word_boundaries(cursor);

                let (sel_start, sel_end, new_cursor) = match cursor.cmp(&anchor) {
                    Ordering::Greater => (anchor_start, cur_end, cur_end), // forward
                    Ordering::Less => (cur_start, anchor_end, cur_start),  // backward
                    Ordering::Equal => (anchor_start, anchor_end, anchor_end),
                };

                self.selection = Some(Selection::from_anchor_and_cursor(sel_start, sel_end));
                self.cursor = new_cursor;
            }
            SelectionSnap::None => {
                let anchor = self.selection_anchor();
                self.selection = Some(Selection::from_anchor_and_cursor(anchor, cursor));
                self.cursor = cursor;
            }
        }
    }

    /// Converts mouse coordinates to a cursor position within the editor area, returning `None` if outside.
    pub fn cursor_from_mouse(&self, mouse_x: u16, mouse_y: u16, area: &Rect) -> Option<usize> {
        let line_number_width = self.get_line_number_width() as u16;

        if mouse_y < area.top()
            || mouse_y >= area.bottom()
            || mouse_x < area.left() + line_number_width
        {
            return None;
        }

        let clicked_visual_row = (mouse_y - area.top()) as usize + self.offset_y;
        let clicked_row = self.line_for_visual_row(clicked_visual_row)?;
        if clicked_row >= self.code.len_lines() {
            return None;
        }

        let clicked_col = (mouse_x - area.left() - line_number_width) as usize;

        let line_start_char = self.code.line_to_char(clicked_row);
        let line_len = self.code.line_len(clicked_row);

        let start_col = self.offset_x.min(line_len);
        let end_col = line_len;

        let char_start = line_start_char + start_col;
        let char_end = line_start_char + end_col;

        let mut current_col = 0;
        let mut char_idx = start_col;
        let visible_chars = self.code.char_slice(char_start, char_end);
        for g in RopeGraphemes::new(&visible_chars) {
            let (g_width, g_chars) = grapheme_width_and_chars_len(g);
            if current_col + g_width > clicked_col {
                break;
            }
            current_col += g_width;
            char_idx += g_chars;
        }

        let line = self
            .code
            .char_slice(line_start_char, line_start_char + line_len);
        let visual_width: usize = RopeGraphemes::new(&line).map(grapheme_width).sum();

        if clicked_col + self.offset_x >= visual_width {
            let mut end_idx = line.len_chars();
            if end_idx > 0 && line.char(end_idx - 1) == '\n' {
                end_idx -= 1;
            }
            char_idx = end_idx;
        }

        Some(line_start_char + char_idx)
    }

    pub(crate) fn toggle_fold_at_mouse(&mut self, mouse_x: u16, mouse_y: u16, area: &Rect) -> bool {
        if !self.is_code_folding_enabled() {
            return false;
        }

        let line_number_width = self.get_line_number_width();
        let fold_gutter_width = self.fold_gutter_width();
        let Some(fold_gutter_start) = line_number_width.checked_sub(fold_gutter_width) else {
            return false;
        };

        if mouse_x < area.left() + fold_gutter_start as u16
            || mouse_x >= area.left() + line_number_width as u16
            || mouse_y < area.top()
            || mouse_y >= area.bottom()
        {
            return false;
        }

        let visual_row = self.offset_y + (mouse_y - area.top()) as usize;
        let Some(line) = self.line_for_visual_row(visual_row) else {
            return false;
        };

        self.toggle_fold_at_line(line)
    }

    pub fn expand_hidden_diff_at_mouse(&mut self, mouse_x: u16, mouse_y: u16, area: &Rect) -> bool {
        if !self.is_diff_focus_active() {
            return false;
        }

        let line_number_width = self.get_line_number_width() as u16;
        if mouse_y < area.top()
            || mouse_y >= area.bottom()
            || mouse_x < area.left() + line_number_width
        {
            return false;
        }

        let clicked_visual_row = (mouse_y - area.top()) as usize + self.offset_y;
        let text_x = area.left() + line_number_width;
        let clicked_col = mouse_x.saturating_sub(text_x) as usize;
        let visible_width = area.width.saturating_sub(line_number_width) as usize;

        let expanded = self.view.expand_hidden_at_visual_row(
            &self.code,
            self.original_code.as_ref(),
            self.active_view_mode(),
            clicked_visual_row,
            clicked_col,
            visible_width,
            self.diff_options.expand_amount,
        );

        if expanded {
            self.clamp_offset_y();
        }

        expanded
    }

    /// Clears any active selection.
    pub fn clear_selection(&mut self) {
        self.selection = None;
    }

    /// Extends or starts a selection from the current cursor to `new_cursor`.
    pub fn extend_selection(&mut self, new_cursor: usize) {
        // If there was already a selection, preserve the anchor (start point)
        // otherwise, use the current cursor as the anchor.
        let anchor = self.selection_anchor();
        self.selection = Some(Selection::from_anchor_and_cursor(anchor, new_cursor));
    }

    /// Returns the selection anchor position, or the cursor if no selection exists.
    pub fn selection_anchor(&self) -> usize {
        self.selection
            .as_ref()
            .map(|s| {
                if self.cursor == s.start {
                    s.end
                } else {
                    s.start
                }
            })
            .unwrap_or(self.cursor)
    }

    pub fn apply<A: Action>(&mut self, mut action: A) {
        action.apply(self);
    }

    pub fn set_content(&mut self, content: &str) {
        self.code.tx();
        self.code.set_state_before(self.cursor, self.selection);
        self.code.remove(0, self.code.len());
        self.code.insert(0, content);
        self.code.set_state_after(self.cursor, self.selection);
        self.code.commit();
        self.reset_highlight_cache();
    }

    pub fn set_original_code(&mut self, content: &str) -> Result<()> {
        let original = Code::new(content, self.code_ref().lang(), None)
            .or_else(|_| Code::new(content, "text", None))?;
        self.highlights_cache.borrow_mut().clear();
        self.original_code = Some(original);
        self.rebuild_view();
        Ok(())
    }

    pub fn clear_original_code(&mut self) {
        self.highlights_cache.borrow_mut().clear();
        self.original_code = None;
        self.rebuild_view();
        self.clamp_offset_y();
    }

    pub fn has_diff(&self) -> bool {
        self.view_mode.has_diff() && self.original_code.is_some()
    }

    pub fn set_diff_enabled(&mut self, enabled: bool) {
        if enabled {
            if self.view_mode == ViewMode::Plain {
                self.view_mode = ViewMode::Diff;
            }
        } else {
            self.view_mode = ViewMode::Plain;
        }
        self.rebuild_view();
        self.clamp_offset_y();
    }

    pub fn is_diff_enabled(&self) -> bool {
        self.view_mode.has_diff()
    }

    pub fn set_diff_focus_enabled(&mut self, enabled: bool) {
        self.view_mode = if enabled {
            ViewMode::DiffFocus {
                context_lines: self.diff_options.focus_context,
            }
        } else if self.view_mode.has_diff() {
            ViewMode::Diff
        } else {
            ViewMode::Plain
        };
        self.rebuild_view();
        self.clamp_cursor_to_focus_rows();
        self.clamp_offset_y();
    }

    pub fn toggle_diff_focus(&mut self) {
        self.set_diff_focus_enabled(!self.view_mode.is_diff_focus());
    }

    pub fn set_diff_focus_context(&mut self, context_lines: usize) {
        self.diff_options.focus_context = context_lines;
        if self.view_mode.is_diff_focus() {
            self.view_mode = ViewMode::DiffFocus { context_lines };
        }
        self.rebuild_view();
        self.clamp_cursor_to_focus_rows();
        self.clamp_offset_y();
    }

    pub fn set_diff_expand_amount(&mut self, amount: usize) {
        self.diff_options.expand_amount = amount;
        self.rebuild_view();
    }

    pub fn set_diff_options(&mut self, options: DiffOptions) {
        self.diff_options = options;
        if self.view_mode.is_diff_focus() {
            self.view_mode = ViewMode::DiffFocus {
                context_lines: options.focus_context,
            };
        }
        self.rebuild_view();
        self.clamp_cursor_to_focus_rows();
        self.clamp_offset_y();
    }

    pub fn diff_options(&self) -> DiffOptions {
        self.diff_options
    }

    pub fn apply_batch(&mut self, batch: &EditBatch) {
        self.code.tx();

        if let Some(state) = &batch.state_before {
            self.code.set_state_before(state.offset, state.selection);
        }
        if let Some(state) = &batch.state_after {
            self.code.set_state_after(state.offset, state.selection);
        }

        for edit in &batch.edits {
            match edit.operation {
                Operation::Insert => {
                    self.code.insert(edit.start, &edit.text);
                }
                Operation::Remove => {
                    self.code
                        .remove(edit.start, edit.start + edit.text.chars().count());
                }
            }
        }
        self.code.commit();
        self.reset_highlight_cache();
    }

    pub fn set_cursor(&mut self, cursor: usize) {
        self.cursor = cursor;
        self.fit_cursor();
    }

    /// Toggles the Rust Tree-sitter fold that begins on `line_idx`.
    pub fn toggle_fold_at_line(&mut self, line_idx: usize) -> bool {
        if !self.code_folding_options.enabled {
            return false;
        }
        let top_line = self.line_for_visual_row(self.offset_y);
        let toggled = self.view.toggle_code_fold(
            &self.code,
            self.original_code.as_ref(),
            self.active_view_mode(),
            line_idx,
        );
        if toggled {
            if let Some(top_line) = top_line {
                let visual_line = self.visual_line_idx(top_line);
                if visual_line != usize::MAX {
                    self.offset_y = visual_line;
                }
            }
            self.clamp_offset_y();
        }
        toggled
    }

    pub fn toggle_fold_at_cursor(&mut self) -> bool {
        let line_idx = self.code.char_to_line(self.cursor);
        self.toggle_fold_at_line(line_idx)
    }

    pub fn set_code_folding_enabled(&mut self, enabled: bool) {
        self.code_folding_options.enabled = enabled;
        if !enabled {
            self.view.clear_code_folds();
        }
        self.rebuild_view();
    }

    pub fn is_code_folding_enabled(&self) -> bool {
        self.code_folding_options.enabled
    }

    pub fn set_code_folding_options(&mut self, options: CodeFoldingOptions) {
        let enabled = options.enabled;
        self.code_folding_options = options;
        if !enabled {
            self.view.clear_code_folds();
        }
        self.rebuild_view();
    }

    pub fn code_folding_options(&self) -> CodeFoldingOptions {
        self.code_folding_options.clone()
    }

    pub(crate) fn fold_gutter_width(&self) -> usize {
        if !self.code_folding_options.enabled {
            return 0;
        }
        self.code_folding_options
            .indicators
            .expanded
            .width()
            .max(self.code_folding_options.indicators.collapsed.width())
            + 1
    }

    pub(crate) fn code_fold_indicator(&self, line_idx: usize) -> Option<bool> {
        self.code_folding_options
            .enabled
            .then(|| self.view.code_fold_indicator(&self.code, line_idx))
            .flatten()
    }

    pub fn fit_cursor(&mut self) {
        // make sure cursor is not out of bounds
        let len = self.code.len_chars();
        self.cursor = self.cursor.min(len);

        // make sure cursor is not out of bounds on the line
        let (row, col) = self.code.point(self.cursor);
        if col > self.code.line_len(row) {
            self.cursor = self.code.line_to_char(row) + self.code.line_len(row);
        }
    }

    pub fn scroll_up(&mut self) {
        if self.offset_y > 0 {
            self.offset_y -= 1;
        }
    }

    pub fn scroll_down(&mut self, area_height: usize) {
        let len_lines = self.visual_len_lines();
        if self.offset_y < len_lines.saturating_sub(area_height) {
            self.offset_y += 1;
        }
    }

    fn build_theme(theme: &Vec<(&str, &str)>) -> Theme {
        theme
            .into_iter()
            .map(|(name, hex)| {
                let (r, g, b) = utils::rgb(hex);
                (name.to_string(), Style::default().fg(Color::Rgb(r, g, b)))
            })
            .collect()
    }

    pub fn get_content(&self) -> String {
        self.code.get_content()
    }

    pub fn get_content_slice(&self, start: usize, end: usize) -> String {
        self.code.slice(start, end)
    }

    pub fn get_cursor(&self) -> usize {
        self.cursor
    }

    pub fn set_clipboard(&mut self, text: &str) -> Result<()> {
        arboard::Clipboard::new()
            .and_then(|mut c| c.set_text(text.to_string()))
            .unwrap_or_else(|_| self.clipboard = Some(text.to_string()));
        Ok(())
    }

    pub fn get_clipboard(&self) -> Result<String> {
        arboard::Clipboard::new()
            .and_then(|mut c| c.get_text())
            .ok()
            .or_else(|| self.clipboard.clone())
            .ok_or_else(|| anyhow!("cant get clipboard"))
    }

    pub fn set_marks(&mut self, marks: Vec<(usize, usize, &str)>) {
        self.marks = Some(
            marks
                .into_iter()
                .map(|(start, end, color)| {
                    let (r, g, b) = utils::rgb(color);
                    (start, end, Color::Rgb(r, g, b))
                })
                .collect(),
        );
    }

    pub fn remove_marks(&mut self) {
        self.marks = None;
    }

    pub fn has_marks(&self) -> bool {
        self.marks.is_some()
    }

    pub fn get_marks(&self) -> Option<&Vec<(usize, usize, Color)>> {
        self.marks.as_ref()
    }

    pub fn get_selection_text(&mut self) -> Option<String> {
        if let Some(selection) = &self.selection
            && !selection.is_empty()
        {
            let text = self.code.slice(selection.start, selection.end);
            return Some(text);
        }
        None
    }

    pub fn get_selection(&mut self) -> Option<Selection> {
        return self.selection;
    }

    pub fn set_selection(&mut self, selection: Option<Selection>) {
        self.selection = selection;
    }

    pub fn set_offset_y(&mut self, offset_y: usize) {
        self.offset_y = offset_y.min(self.visual_len_lines().saturating_sub(1));
    }

    pub fn set_offset_x(&mut self, offset_x: usize) {
        self.offset_x = offset_x;
    }

    pub fn get_offset_y(&self) -> usize {
        self.offset_y
    }

    pub fn get_offset_x(&self) -> usize {
        self.offset_x
    }

    pub(crate) fn visual_len_lines(&self) -> usize {
        self.view
            .visual_len_lines(&self.code, self.active_view_mode())
    }

    pub(crate) fn line_for_visual_row(&self, visual_row: usize) -> Option<usize> {
        self.view
            .line_for_visual_row(&self.code, self.active_view_mode(), visual_row)
    }

    pub(crate) fn visual_row(&self, visual_row: usize) -> Option<VisualRow> {
        if self.has_diff() || !self.view.rows().is_empty() {
            self.view.rows().get(visual_row).cloned()
        } else if visual_row < self.code.len_lines() {
            Some(VisualRow::Real {
                line_idx: visual_row,
                is_added: false,
            })
        } else {
            None
        }
    }

    pub(crate) fn visual_line_idx(&self, line_idx: usize) -> usize {
        self.view
            .visual_row_for_line(self.active_view_mode(), line_idx)
            .unwrap_or(usize::MAX)
    }

    pub fn code_mut(&mut self) -> &mut Code {
        &mut self.code
    }

    pub fn code_ref(&self) -> &Code {
        &self.code
    }

    /// Set the change callback function for handling document changes
    pub fn set_change_callback(
        &mut self,
        callback: Box<dyn Fn(Vec<(usize, usize, usize, usize, String)>)>,
    ) {
        self.code.set_change_callback(callback);
    }

    pub fn highlight_interval(
        &self,
        start: usize,
        end: usize,
        theme: &Theme,
    ) -> Vec<(usize, usize, Style)> {
        let mut cache = self.highlights_cache.borrow_mut();
        let key = (0, start, end);
        if let Some(v) = cache.get(&key) {
            return v.clone();
        }

        let highlights = self.code.highlight_interval(start, end, theme);
        cache.insert(key, highlights.clone());
        highlights
    }

    pub fn highlight_interval_original(
        &self,
        start: usize,
        end: usize,
        theme: &Theme,
    ) -> Vec<(usize, usize, Style)> {
        let Some(original) = &self.original_code else {
            return Vec::new();
        };
        let mut cache = self.highlights_cache.borrow_mut();
        let key = (1, start, end);
        if let Some(v) = cache.get(&key) {
            return v.clone();
        }

        let highlights = original.highlight_interval(start, end, theme);
        cache.insert(key, highlights.clone());
        highlights
    }

    pub fn reset_highlight_cache(&mut self) {
        self.highlights_cache.borrow_mut().clear();
        self.rebuild_view();
    }

    fn clamp_offset_y(&mut self) {
        self.offset_y = self.offset_y.min(self.visual_len_lines().saturating_sub(1));
    }

    pub(crate) fn prev_line(&self, line_idx: usize) -> Option<usize> {
        self.view.prev_line(self.active_view_mode(), line_idx)
    }

    pub(crate) fn next_line(&self, line_idx: usize) -> Option<usize> {
        self.view
            .next_line(&self.code, self.active_view_mode(), line_idx)
    }

    pub(crate) fn is_diff_focus_active(&self) -> bool {
        self.has_diff() && self.view_mode.is_diff_focus()
    }

    pub(crate) fn clamp_cursor_to_focus_rows(&mut self) {
        let clear_selection = self.is_diff_focus_active();
        let (cursor_line, cursor_char_col) = self.code.point(self.cursor);
        if self.line_visible(cursor_line) {
            return;
        }

        let current_visual_col = self.code.char_col_to_visual(cursor_line, cursor_char_col);
        let Some(target_line) = self.nearest_focus_real_line(cursor_line) else {
            return;
        };
        let target_start = self.code.line_to_char(target_line);
        let target_len = self.code.line_len(target_line);
        let target_col = self
            .code
            .visual_to_char_col(target_line, current_visual_col)
            .min(target_len);

        self.cursor = target_start + target_col;
        if clear_selection {
            self.clear_selection();
        }
    }

    pub(crate) fn line_visible(&self, line_idx: usize) -> bool {
        self.view.line_visible(self.active_view_mode(), line_idx)
    }

    fn nearest_focus_real_line(&self, line_idx: usize) -> Option<usize> {
        self.view
            .nearest_line(&self.code, self.active_view_mode(), line_idx)
    }

    /// calculates visible cursor position
    pub fn get_visible_cursor(&self, area: &Rect) -> Option<(u16, u16)> {
        let line_number_width = self.get_line_number_width();

        let (cursor_line, cursor_char_col) = self.code.point(self.cursor);
        let cursor_visual_line = self.visual_line_idx(cursor_line);

        if cursor_visual_line >= self.offset_y
            && cursor_visual_line < self.offset_y + area.height as usize
        {
            let line_start_char = self.code.line_to_char(cursor_line);
            let line_len = self.code.line_len(cursor_line);

            let max_x = (area.width as usize).saturating_sub(line_number_width);
            let start_col = self.offset_x;

            let cursor_visual_col: usize = {
                let slice = self.code.char_slice(
                    line_start_char,
                    line_start_char + cursor_char_col.min(line_len),
                );
                RopeGraphemes::new(&slice).map(grapheme_width).sum()
            };

            let offset_visual_col: usize = {
                let slice = self
                    .code
                    .char_slice(line_start_char, line_start_char + start_col.min(line_len));
                RopeGraphemes::new(&slice).map(grapheme_width).sum()
            };

            let relative_visual_col = cursor_visual_col.saturating_sub(offset_visual_col);
            let visible_x = relative_visual_col.min(max_x);

            let cursor_x = area.left() + (line_number_width + visible_x) as u16;
            let cursor_y = area.top() + (cursor_visual_line - self.offset_y) as u16;

            if cursor_x < area.right() && cursor_y < area.bottom() {
                return Some((cursor_x, cursor_y));
            }
        }

        return None;
    }

    pub fn show_line_numbers(&mut self, show: bool) {
        self.show_line_numbers = show
    }

    pub fn set_left_code_padding(&mut self, char_count: usize) {
        self.left_code_padding = char_count
    }

    fn active_view_mode(&self) -> ViewMode {
        if self.original_code.is_some() {
            self.view_mode
        } else {
            ViewMode::Plain
        }
    }

    pub(crate) fn rebuild_view(&mut self) {
        self.view.rebuild(
            &self.code,
            self.original_code.as_ref(),
            self.active_view_mode(),
        );
    }
}