Skip to main content

ratatui_code_editor/
editor.rs

1use std::time::Duration;
2use crate::click::{ClickKind, ClickTracker};
3use crate::code::Code;
4use crate::code::{EditKind, EditBatch};
5use crate::code::{RopeGraphemes, grapheme_width_and_chars_len, grapheme_width};
6use crate::selection::{Selection, SelectionSnap};
7use crate::actions::*;
8use crate::utils;
9use std::collections::HashMap;
10use std::cell::RefCell;
11use std::cmp::Ordering;
12use anyhow::{Result, anyhow};
13use ratatui_core::layout::Rect;
14use ratatui_core::style::{Color, Style};
15
16// keyword and ratatui style
17type Theme = HashMap<String, Style>;
18// start byte, end byte, style
19type Hightlight = (usize, usize, Style);
20// start offset, end offset
21type HightlightCache = HashMap<(usize, usize), Vec<Hightlight>>;
22
23/// Represents the text editor, which holds the code buffer, cursor, selection,
24/// theme, scroll offsets, highlight cache, clipboard, and user mark intervals.
25pub struct Editor {
26    /// Code buffer and editing/highlighting logic for the current language
27    pub(crate) code: Code,
28    /// Current cursor position as a character index in the document
29    pub(crate) cursor: usize,
30
31    /// Vertical scroll offset: index of the first visible line
32    pub(crate) offset_y: usize,
33
34    /// Horizontal scroll offset in characters (visual columns)
35    pub(crate) offset_x: usize,
36
37    /// Syntax theme: mapping of token name to ratatui Style
38    pub(crate) theme: Theme,
39
40    /// Current text selection, if any
41    pub(crate) selection: Option<Selection>,
42
43    /// Click tracker to detect single/double/triple clicks
44    pub(crate) clicks: ClickTracker,
45
46    /// Selection snapping mode (to word, to line, or none)
47    pub(crate) selection_snap: SelectionSnap,
48
49    /// Fallback clipboard storage when the system clipboard is unavailable
50    pub(crate) clipboard: Option<String>,
51
52    /// User marks for intervals: (start, end, color)
53    pub(crate) marks: Option<Vec<(usize, usize, Color)>>,
54
55    /// Syntax highlight cache by intervals to speed up rendering
56    pub(crate) highlights_cache: RefCell<HightlightCache>,
57
58    /// Controls when to show the line numbers
59    pub(crate) show_line_numbers: bool,
60
61    /// Controls the left padding before writing the code
62    pub(crate) left_code_padding: usize,
63}
64
65impl Editor {
66    pub fn new(lang: &str, text: &str, theme: Vec<(&str, &str)>) -> Result<Self> {
67        Self::new_with_highlights(lang, text, theme, None)
68    }
69
70    pub fn new_with_highlights(
71        lang: &str,
72        text: &str,
73        theme: Vec<(&str, &str)>,
74        custom_highlights: Option<HashMap<String, String>>,
75    ) -> Result<Self> {
76        let code = Code::new(text, lang, custom_highlights.clone())
77            .or_else(|_| Code::new(text, "text", custom_highlights))?;
78
79        let theme = Self::build_theme(&theme);
80        let highlights_cache = RefCell::new(HashMap::new());
81
82        Ok(Self {
83            code,
84            cursor: 0,
85            offset_y: 0,
86            offset_x: 0,
87            theme,
88            selection: None,
89            clicks: ClickTracker::new(Duration::from_millis(700)),
90            selection_snap: SelectionSnap::None,
91            clipboard: None,
92            marks: None,
93            highlights_cache,
94            show_line_numbers: true,
95            left_code_padding: 2,
96        })
97    }
98
99    pub(crate) fn get_line_number_width(&self) -> usize {
100        if self.show_line_numbers {
101            let total_lines = self.code.len_lines();
102            let max_line_number = total_lines.max(1);
103            let line_number_digits = max_line_number.to_string().len().max(5);
104            (line_number_digits + self.left_code_padding) as usize
105        } else {
106            self.left_code_padding
107        }
108    } 
109
110    pub fn focus(&mut self, area: &Rect) {
111        let width = area.width as usize;
112        let height = area.height as usize;
113        let line_number_width = self.get_line_number_width();
114
115        let line = self.code.char_to_line(self.cursor);
116        let col = self.cursor - self.code.line_to_char(line);
117    
118        let visible_width = width.saturating_sub(line_number_width);
119        let visible_height = height;
120    
121        let step_size = 10;
122        if col < self.offset_x {
123            self.offset_x = col.saturating_sub(step_size);
124        } else if col >= self.offset_x + visible_width {
125            self.offset_x = col.saturating_sub(visible_width - step_size);
126        }
127    
128        if line < self.offset_y {
129            self.offset_y = line;
130        } else if line >= self.offset_y + visible_height {
131            self.offset_y = line.saturating_sub(visible_height - 1);
132        }
133    }
134
135    /// Handles a mouse button press at the given cursor position, updating selection and click state.
136    pub fn handle_mouse_down(&mut self, cursor: usize) {
137        let kind = self.clicks.register(cursor);
138        let (start, end, snap) = match kind {
139            ClickKind::Triple => {
140                let (line_start, line_end) = self.code.line_boundaries(cursor);
141                (line_start, line_end, SelectionSnap::Line { anchor: cursor })
142            }
143            ClickKind::Double => {
144                let (word_start, word_end) = self.code.word_boundaries(cursor);
145                (word_start, word_end, SelectionSnap::Word { anchor: cursor })
146            }
147            ClickKind::Single => (cursor, cursor, SelectionSnap::None),
148        };
149
150        self.selection = Some(Selection::from_anchor_and_cursor(start, end));
151        self.cursor = end;
152        self.selection_snap = snap;
153    }
154
155    /// Handles a mouse drag event at the given cursor position, extending the selection.
156    pub fn handle_mouse_drag(&mut self, cursor: usize) {
157        match self.selection_snap {
158            SelectionSnap::Line { anchor } => {
159                let (anchor_start, anchor_end) = self.code.line_boundaries(anchor);
160                let (cur_start, cur_end) = self.code.line_boundaries(cursor);
161        
162                let (sel_start, sel_end, new_cursor) = match cursor.cmp(&anchor) {
163                    Ordering::Greater => (anchor_start, cur_end, cur_end),   // forward
164                    Ordering::Less => (cur_start, anchor_end, cur_start),    // backward
165                    Ordering::Equal => (anchor_start, anchor_end, anchor_end), 
166                };
167        
168                self.selection = Some(Selection::from_anchor_and_cursor(sel_start, sel_end));
169                self.cursor = new_cursor;
170            }
171            SelectionSnap::Word { anchor } => {
172                let (anchor_start, anchor_end) = self.code.word_boundaries(anchor);
173                let (cur_start, cur_end) = self.code.word_boundaries(cursor);
174        
175                let (sel_start, sel_end, new_cursor) = match cursor.cmp(&anchor) {
176                    Ordering::Greater => (anchor_start, cur_end, cur_end),   // forward
177                    Ordering::Less => (cur_start, anchor_end, cur_start),    // backward
178                    Ordering::Equal => (anchor_start, anchor_end, anchor_end),
179                };
180        
181                self.selection = Some(Selection::from_anchor_and_cursor(sel_start, sel_end));
182                self.cursor = new_cursor;
183            }
184            SelectionSnap::None => {
185                let anchor = self.selection_anchor();
186                self.selection = Some(Selection::from_anchor_and_cursor(anchor, cursor));
187                self.cursor = cursor;
188            }
189        }
190    }
191
192    /// Converts mouse coordinates to a cursor position within the editor area, returning `None` if outside.
193    pub fn cursor_from_mouse(
194        &self, mouse_x: u16, mouse_y: u16, area: &Rect
195    ) -> Option<usize> {
196        let line_number_width = self.get_line_number_width() as u16;
197    
198        if mouse_y < area.top()
199            || mouse_y >= area.bottom()
200            || mouse_x < area.left() + line_number_width
201        {
202            return None;
203        }
204    
205        let clicked_row = (mouse_y - area.top()) as usize + self.offset_y;
206        if clicked_row >= self.code.len_lines() {
207            return None;
208        }
209    
210        let clicked_col = (mouse_x - area.left() - line_number_width) as usize;
211    
212        let line_start_char = self.code.line_to_char(clicked_row);
213        let line_len = self.code.line_len(clicked_row);
214    
215        let start_col = self.offset_x.min(line_len);
216        let end_col = line_len;
217    
218        let char_start = line_start_char + start_col;
219        let char_end = line_start_char + end_col;
220    
221        let mut current_col = 0;
222        let mut char_idx = start_col;        
223        let visible_chars = self.code.char_slice(char_start, char_end);
224        for g in RopeGraphemes::new(&visible_chars) {
225            let (g_width, g_chars) = grapheme_width_and_chars_len(g);        
226            if current_col + g_width > clicked_col { break; }
227            current_col += g_width;
228            char_idx += g_chars;
229        }
230    
231        let line = self.code.char_slice(line_start_char, line_start_char + line_len);
232        let visual_width: usize = RopeGraphemes::new(&line).map(grapheme_width).sum();
233    
234        if clicked_col + self.offset_x >= visual_width {
235            let mut end_idx = line.len_chars();
236            if end_idx > 0 && line.char(end_idx - 1) == '\n' {
237                end_idx -= 1;
238            }
239            char_idx = end_idx;
240        }
241    
242        Some(line_start_char + char_idx)
243    }
244
245    /// Clears any active selection.
246    pub fn clear_selection(&mut self) {
247        self.selection = None;
248    }
249
250    /// Extends or starts a selection from the current cursor to `new_cursor`.
251    pub fn extend_selection(&mut self, new_cursor: usize) {
252        // If there was already a selection, preserve the anchor (start point)
253        // otherwise, use the current cursor as the anchor.
254        let anchor = self.selection_anchor();
255        self.selection = Some(Selection::from_anchor_and_cursor(anchor, new_cursor));
256    }
257    
258    /// Returns the selection anchor position, or the cursor if no selection exists.
259    pub fn selection_anchor(&self) -> usize {
260        self.selection
261            .as_ref()
262            .map(|s| if self.cursor == s.start { s.end } else { s.start })
263            .unwrap_or(self.cursor)
264    }
265
266    pub fn apply<A: Action>(&mut self, mut action: A) {
267        action.apply(self);
268    }
269
270    pub fn set_content(&mut self, content: &str) {
271        self.code.tx();
272        self.code.set_state_before(self.cursor, self.selection);
273        self.code.remove(0, self.code.len());
274        self.code.insert(0, content);
275        self.code.set_state_after(self.cursor, self.selection);
276        self.code.commit();
277        self.reset_highlight_cache();
278    }
279
280    pub fn apply_batch(&mut self, batch: &EditBatch) {
281        self.code.tx();
282
283        if let Some(state) = &batch.state_before {
284            self.code.set_state_before(state.offset, state.selection);
285        }
286        if let Some(state) = &batch.state_after {
287            self.code.set_state_after(state.offset, state.selection);
288        }
289        
290        for edit in &batch.edits {
291            match &edit.kind {
292                EditKind::Insert { offset, text } => {
293                    self.code.insert(*offset, text);
294                }
295                EditKind::Remove { offset, text } => {
296                    self.code.remove(*offset, *offset + text.chars().count());
297                }
298            }
299        }
300        self.code.commit();
301        self.reset_highlight_cache();
302    }
303
304    pub fn set_cursor(&mut self, cursor: usize) {
305        self.cursor = cursor;
306        self.fit_cursor();
307    }
308
309    pub fn fit_cursor(&mut self) {
310        // make sure cursor is not out of bounds 
311        let len = self.code.len_chars();
312        self.cursor = self.cursor.min(len);
313
314        // make sure cursor is not out of bounds on the line
315        let (row, col) = self.code.point(self.cursor);
316        if col > self.code.line_len(row) {
317            self.cursor = self.code.line_to_char(row) + self.code.line_len(row);
318        }
319    }
320
321    pub fn scroll_up(&mut self) {
322        if self.offset_y > 0 {
323            self.offset_y -= 1;
324        }
325    }
326
327    pub fn scroll_down(&mut self, area_height: usize) {
328        let len_lines = self.code.len_lines();
329        if self.offset_y < len_lines.saturating_sub(area_height) {
330            self.offset_y += 1;
331        }
332    }
333
334    fn build_theme(theme: &Vec<(&str, &str)>) -> Theme {
335        theme.into_iter()
336            .map(|(name, hex)| {
337                let (r, g, b) = utils::rgb(hex);
338                (name.to_string(), Style::default().fg(Color::Rgb(r, g, b)))
339            })
340            .collect()
341    }
342
343    pub fn get_content(&self) -> String {
344        self.code.get_content()
345    }
346
347    pub fn get_content_slice(&self, start: usize, end: usize) -> String {
348        self.code.slice(start, end)
349    }
350
351    pub fn get_cursor(&self) -> usize {
352        self.cursor
353    }
354
355    pub fn set_clipboard(&mut self, text: &str) -> Result<()> {
356        arboard::Clipboard::new()
357            .and_then(|mut c| c.set_text(text.to_string()))
358            .unwrap_or_else(|_| self.clipboard = Some(text.to_string()));
359        Ok(())
360    }
361
362    pub fn get_clipboard(&self) -> Result<String> {
363        arboard::Clipboard::new()
364            .and_then(|mut c| c.get_text())
365            .ok()
366            .or_else(|| self.clipboard.clone())
367            .ok_or_else(|| anyhow!("cant get clipboard"))
368    }
369
370    pub fn set_marks(&mut self, marks: Vec<(usize, usize, &str)>) {
371        self.marks = Some(
372            marks.into_iter()
373                .map(|(start, end, color)| {
374                    let (r, g, b) = utils::rgb(color);
375                    (start, end, Color::Rgb(r, g, b))
376                })
377                .collect()
378        );
379    }
380
381    pub fn remove_marks(&mut self) {
382        self.marks = None;
383    }
384
385    pub fn has_marks(&self) -> bool {
386        self.marks.is_some()
387    }
388
389    pub fn get_marks(&self) -> Option<&Vec<(usize, usize, Color)>> {
390        self.marks.as_ref()
391    }
392
393    pub fn get_selection_text(&mut self) -> Option<String> {
394        if let Some(selection) = &self.selection && !selection.is_empty() {
395            let text = self.code.slice(selection.start, selection.end);
396            return Some(text);
397        }
398        None
399    }
400
401    pub fn get_selection(&mut self) -> Option<Selection> {
402       return self.selection;
403    }
404
405    pub fn set_selection(&mut self, selection: Option<Selection>) {
406        self.selection = selection;
407    }
408
409    pub fn set_offset_y(&mut self, offset_y: usize) {
410        self.offset_y = offset_y;
411    }
412
413    pub fn set_offset_x(&mut self, offset_x: usize) {
414        self.offset_x = offset_x;
415    }
416    
417    pub fn get_offset_y(&self) -> usize {
418        self.offset_y
419    }
420
421    pub fn get_offset_x(&self) -> usize {
422        self.offset_x
423    }
424
425    pub fn code_mut(&mut self) -> &mut Code {
426        &mut self.code
427    }
428
429    pub fn code_ref(&self) -> &Code {
430        &self.code
431    }
432
433    /// Set the change callback function for handling document changes
434    pub fn set_change_callback(
435        &mut self, callback: Box<dyn Fn(Vec<(usize, usize, usize, usize, String)>)>
436    ) {
437        self.code.set_change_callback(callback);
438    }
439
440    pub fn highlight_interval(
441        &self, start: usize, end: usize, theme: &Theme
442    ) -> Vec<(usize, usize, Style)> {
443        let mut cache = self.highlights_cache.borrow_mut();
444        let key = (start, end);
445        if let Some(v) = cache.get(&key) {
446            return v.clone();
447        }
448
449        let highlights = self.code.highlight_interval(start, end, theme);
450        cache.insert(key, highlights.clone());
451        highlights
452    }
453
454    pub fn reset_highlight_cache(&self) {
455        self.highlights_cache.borrow_mut().clear();
456    }
457    
458    /// calculates visible cursor position 
459    pub fn get_visible_cursor(
460        &self, area: &Rect
461    ) -> Option<(u16, u16)> {
462        let line_number_width = self.get_line_number_width();
463
464        let (cursor_line, cursor_char_col) = self.code.point(self.cursor);
465        
466        if cursor_line >= self.offset_y && cursor_line < self.offset_y + area.height as usize {
467            let line_start_char = self.code.line_to_char(cursor_line);
468            let line_len = self.code.line_len(cursor_line);
469        
470            let max_x = (area.width as usize).saturating_sub(line_number_width);
471            let start_col = self.offset_x;
472                
473            let cursor_visual_col: usize = {
474                let slice = self.code.char_slice(line_start_char, line_start_char + cursor_char_col.min(line_len));
475                RopeGraphemes::new(&slice).map(grapheme_width).sum()
476            };
477            
478            let offset_visual_col: usize = {
479                let slice = self.code.char_slice(line_start_char, line_start_char + start_col.min(line_len));
480                RopeGraphemes::new(&slice).map(grapheme_width).sum()
481            };
482        
483            let relative_visual_col = cursor_visual_col.saturating_sub(offset_visual_col);
484            let visible_x = relative_visual_col.min(max_x);
485        
486            let cursor_x = area.left() + (line_number_width + visible_x) as u16;
487            let cursor_y = area.top() + (cursor_line - self.offset_y) as u16;
488        
489            if cursor_x < area.right() && cursor_y < area.bottom() {
490                return Some((cursor_x, cursor_y));
491            }
492        }
493        
494        return None;
495    }
496
497    pub fn show_line_numbers(&mut self, show: bool) {
498        self.show_line_numbers = show
499    }
500
501    pub fn set_left_code_padding(&mut self, char_count: usize) {
502        self.left_code_padding = char_count
503    }
504}