Skip to main content

ratatui_code_editor/
render.rs

1use crate::code::{RopeGraphemes, grapheme_width_and_bytes_len, grapheme_width_and_chars_len};
2use crate::editor::Editor;
3use crate::types::VisualRow;
4use crate::view::View;
5use ratatui_core::buffer::Buffer;
6use ratatui_core::layout::Rect;
7use ratatui_core::style::{Color, Style};
8use ratatui_core::widgets::Widget;
9
10/// Draws the main editor view in the provided area using the ratatui rendering buffer.
11///
12/// Renders visible [`VisualRow`]s, including fold separators and deleted diff rows.
13/// Added and deleted rows receive a diff background before syntax highlighting is
14/// applied. Selections and user marks are then drawn over real editor rows.
15///
16/// # Arguments
17///
18/// * `self` - The `Editor` instance (as reference) to render.
19/// * `area` - The rectangular area on the terminal to draw within.
20/// * `buf` - The ratatui `Buffer` that represents the screen cells to draw to.
21///
22impl Widget for &Editor {
23    fn render(self, area: Rect, buf: &mut Buffer) {
24        let code = self.code_ref();
25        let total_lines = code.len_lines();
26        let max_line_number = total_lines.max(1);
27        let line_number_digits = max_line_number.to_string().len().max(5);
28        let line_number_width = self.get_line_number_width();
29        let fold_gutter_width = self.fold_gutter_width();
30        let total_visual_lines = self.visual_len_lines();
31        let mut draw_y = area.top();
32
33        let line_number_style = Style::default().fg(Color::DarkGray);
34        let default_text_style = Style::default().fg(Color::White);
35
36        let diff_added_bg = self
37            .theme
38            .get("diff_added")
39            .and_then(|s| s.fg)
40            .unwrap_or(Color::Rgb(30, 90, 55));
41        let diff_deleted_bg = self
42            .theme
43            .get("diff_deleted")
44            .and_then(|s| s.fg)
45            .unwrap_or(Color::Rgb(217, 75, 75));
46
47        let fold_separator_style = Style::default().fg(Color::DarkGray);
48
49        // draw lines, syntax highlighting, selection and marks in a single unified loop
50        for visual_row_idx in self.offset_y..total_visual_lines {
51            if draw_y >= area.bottom() {
52                break;
53            }
54
55            let row = match self.visual_row(visual_row_idx) {
56                Some(row) => row,
57                None => break,
58            };
59
60            if let VisualRow::FoldSeparator { hidden_lines, .. } = &row {
61                if self.show_line_numbers {
62                    buf.set_string(
63                        area.left(),
64                        draw_y,
65                        &format!("{:>width$}", "...", width = line_number_digits),
66                        line_number_style,
67                    );
68                }
69                let text_x = area.left() + line_number_width as u16;
70                let text =
71                    View::fold_separator_text(*hidden_lines, self.diff_options.expand_amount);
72                let width = (area.width as usize).saturating_sub(line_number_width);
73                let visible_text = text.chars().take(width).collect::<String>();
74                if text_x < area.right() {
75                    buf.set_string(text_x, draw_y, &visible_text, fold_separator_style);
76                }
77            } else {
78                let (line_idx, is_added, is_ghost) = match &row {
79                    VisualRow::Real { line_idx, is_added } => (*line_idx, *is_added, false),
80                    VisualRow::GhostDeleted {
81                        original_line_idx, ..
82                    } => (*original_line_idx, false, true),
83                    _ => unreachable!(),
84                };
85                let source_code = if is_ghost {
86                    self.original_code.as_ref().unwrap_or(code)
87                } else {
88                    code
89                };
90
91                // 1. Draw line numbers
92                if self.show_line_numbers {
93                    let line_number = if is_ghost {
94                        format!("{:>width$}", " ", width = line_number_digits)
95                    } else {
96                        format!("{:>width$}", line_idx + 1, width = line_number_digits)
97                    };
98                    buf.set_string(area.left(), draw_y, &line_number, line_number_style);
99                }
100                if !is_ghost {
101                    if let Some(collapsed) = self.code_fold_indicator(line_idx) {
102                        let indicator = if collapsed {
103                            &self.code_folding_options.indicators.collapsed
104                        } else {
105                            &self.code_folding_options.indicators.expanded
106                        };
107                        buf.set_string(
108                            area.left() + (line_number_width - fold_gutter_width) as u16,
109                            draw_y,
110                            indicator,
111                            line_number_style,
112                        );
113                    }
114                }
115
116                let text_x = area.left() + line_number_width as u16;
117                let width = (area.width as usize).saturating_sub(line_number_width);
118
119                let line_len = source_code.line_len(line_idx);
120                let start_col = self.offset_x.min(line_len);
121                let end_col = (start_col + width).min(line_len);
122
123                let line_start_char = source_code.line_to_char(line_idx);
124                let char_slice_start = line_start_char + start_col;
125                let char_slice_end = line_start_char + end_col;
126                let visible_chars = source_code.char_slice(char_slice_start, char_slice_end);
127
128                let start_byte = source_code.char_to_byte(char_slice_start);
129                let end_byte = source_code.char_to_byte(char_slice_end);
130
131                // Fetch highlights
132                let highlights = if code.is_highlight() {
133                    if is_ghost {
134                        self.highlight_interval_original(start_byte, end_byte, &self.theme)
135                    } else {
136                        self.highlight_interval(start_byte, end_byte, &self.theme)
137                    }
138                } else {
139                    Vec::new()
140                };
141
142                // Base style background color
143                let base_bg = match is_ghost {
144                    true => Some(diff_deleted_bg),
145                    false if is_added => Some(diff_added_bg),
146                    false => None,
147                };
148
149                let mut x = 0;
150                let mut byte_idx_in_rope = start_byte;
151                let mut char_col = start_col;
152
153                // 3. Single loop over the graphemes of the line
154                for g in RopeGraphemes::new(&visible_chars) {
155                    let (g_width, g_bytes) = grapheme_width_and_bytes_len(g);
156                    let (_, g_chars) = grapheme_width_and_chars_len(g);
157
158                    if x >= width {
159                        break;
160                    }
161
162                    let start_x = text_x + x as u16;
163
164                    // Compose style
165                    let mut style = if let Some(bg) = base_bg {
166                        Style::default().bg(bg)
167                    } else {
168                        default_text_style
169                    };
170
171                    // Layer A: Syntax highlights
172                    for &(start, end, s) in &highlights {
173                        if start <= byte_idx_in_rope && byte_idx_in_rope < end {
174                            style = style.patch(s);
175                            if let Some(bg) = base_bg {
176                                style = style.bg(bg); // Keep diff background
177                            }
178                            break;
179                        }
180                    }
181
182                    let global_char_idx = line_start_char + char_col;
183
184                    if !is_ghost {
185                        // Layer B: Selection
186                        if let Some(selection) = self.selection
187                            && !selection.is_empty()
188                        {
189                            let start = selection.start.min(selection.end);
190                            let end = selection.start.max(selection.end);
191                            if global_char_idx >= start && global_char_idx < end {
192                                style = style.bg(Color::DarkGray);
193                            }
194                        }
195
196                        // Layer C: Marks
197                        if let Some(ref marks) = self.marks {
198                            for &(m_start, m_end, m_color) in marks {
199                                if global_char_idx >= m_start && global_char_idx < m_end {
200                                    style = style.bg(m_color);
201                                }
202                            }
203                        }
204                    }
205
206                    // Draw character
207                    let display_g = g.to_string().replace('\t', " ");
208                    if start_x < area.right() {
209                        buf.set_string(start_x, draw_y, &display_g, style);
210                    }
211
212                    x = x.saturating_add(g_width);
213                    byte_idx_in_rope += g_bytes;
214                    char_col += g_chars;
215                }
216
217                // 4. Fill remaining width with background if needed
218                if let Some(bg) = base_bg
219                    && x < width
220                    && text_x + (x as u16) < area.right()
221                {
222                    let fill_x = text_x + (x as u16);
223                    let fill_width = width - x;
224                    buf.set_string(
225                        fill_x,
226                        draw_y,
227                        &" ".repeat(fill_width),
228                        Style::default().bg(bg),
229                    );
230                }
231            }
232            draw_y += 1;
233        }
234    }
235}