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.theme_style("diff_added").bg
37            .or(self.theme_style("diff_added").fg)
38            .unwrap_or(Color::Rgb(1, 125, 78));
39        let diff_added_word_bg = self.theme_style("diff_added_word").bg
40            .or(self.theme_style("diff_added_word").fg)
41            .unwrap_or(Color::Rgb(19, 163, 111));
42        let diff_deleted_bg = self.theme_style("diff_deleted").bg
43            .or(self.theme_style("diff_deleted").fg)
44            .unwrap_or(Color::Rgb(217, 75, 75));
45        let diff_deleted_word_bg = self.theme_style("diff_deleted_word").bg
46            .or(self.theme_style("diff_deleted_word").fg)
47            .unwrap_or(Color::Rgb(248, 99, 99));
48
49        let word_highlights = self.word_highlight_ranges();
50        let word_highlight_bg = self.theme_style("word_highlight").bg
51            .or(self.theme_style("word_highlight").fg)
52            .unwrap_or(Color::Rgb(48, 54, 64));
53
54        let fold_separator_style = Style::default().fg(Color::DarkGray);
55
56        // draw lines, syntax highlighting, selection and marks in a single unified loop
57        for visual_row_idx in self.offset_y..total_visual_lines {
58            if draw_y >= area.bottom() {
59                break;
60            }
61
62            let row = match self.visual_row(visual_row_idx) {
63                Some(row) => row,
64                None => break,
65            };
66
67            if let VisualRow::FoldSeparator { hidden_lines, .. } = &row {
68                if self.show_line_numbers {
69                    buf.set_string(
70                        area.left(),
71                        draw_y,
72                        &format!("{:>width$}", "...", width = line_number_digits),
73                        line_number_style,
74                    );
75                }
76                let text_x = area.left() + line_number_width as u16;
77                let text =
78                    View::fold_separator_text(*hidden_lines, self.diff_options.expand_amount);
79                let width = (area.width as usize).saturating_sub(line_number_width);
80                let visible_text = text.chars().take(width).collect::<String>();
81                if text_x < area.right() {
82                    buf.set_string(text_x, draw_y, &visible_text, fold_separator_style);
83                }
84            } else {
85                let (line_idx, is_added, is_ghost, partner_line_idx) = match &row {
86                    VisualRow::Real { line_idx, is_added, orig_line_idx } => (*line_idx, *is_added, false, *orig_line_idx),
87                    VisualRow::GhostDeleted {
88                        original_line_idx, curr_line_idx, ..
89                    } => (*original_line_idx, false, true, *curr_line_idx),
90                    _ => unreachable!(),
91                };
92                let source_code = if is_ghost {
93                    self.original_code.as_ref().unwrap_or(code)
94                } else {
95                    code
96                };
97
98                // 1. Draw line numbers
99                if self.show_line_numbers {
100                    let line_number = if is_ghost {
101                        format!("{:>width$}", " ", width = line_number_digits)
102                    } else {
103                        format!("{:>width$}", line_idx + 1, width = line_number_digits)
104                    };
105                    buf.set_string(area.left(), draw_y, &line_number, line_number_style);
106                }
107                if !is_ghost {
108                    if let Some(collapsed) = self.code_fold_indicator(line_idx) {
109                        let indicator = if collapsed {
110                            &self.code_folding_options.indicators.collapsed
111                        } else {
112                            &self.code_folding_options.indicators.expanded
113                        };
114                        buf.set_string(
115                            area.left() + (line_number_width - fold_gutter_width) as u16,
116                            draw_y,
117                            indicator,
118                            line_number_style,
119                        );
120                    }
121                }
122
123                let text_x = area.left() + line_number_width as u16;
124                let width = (area.width as usize).saturating_sub(line_number_width);
125
126                let line_len = source_code.line_len(line_idx);
127                let start_col = self.offset_x.min(line_len);
128                let end_col = (start_col + width).min(line_len);
129
130                let line_start_char = source_code.line_to_char(line_idx);
131                let char_slice_start = line_start_char + start_col;
132                let char_slice_end = line_start_char + end_col;
133                let visible_chars = source_code.char_slice(char_slice_start, char_slice_end);
134
135                let start_byte = source_code.char_to_byte(char_slice_start);
136                let end_byte = source_code.char_to_byte(char_slice_end);
137
138                let line_end_char = line_start_char + line_len;
139                let line_word_highlights: Vec<(usize, usize)> = if is_ghost {
140                    Vec::new()
141                } else {
142                    word_highlights
143                        .iter()
144                        .filter(|&&(start, end)| start < line_end_char && end > line_start_char)
145                        .cloned()
146                        .collect()
147                };
148
149                // Fetch highlights
150                let highlights = if code.is_highlight() {
151                    if is_ghost {
152                        self.highlight_interval_original(start_byte, end_byte, &self.theme)
153                    } else {
154                        self.highlight_interval(start_byte, end_byte, &self.theme)
155                    }
156                } else {
157                    Vec::new()
158                };
159
160                // Fetch intra-line diff highlights on the fly from cache
161                let intra_highlights = partner_line_idx.map(|partner_idx| {
162                    if is_ghost {
163                        self.get_line_diff(line_idx, partner_idx, true)
164                    } else {
165                        self.get_line_diff(partner_idx, line_idx, false)
166                    }
167                });
168
169                // Base style background color
170                let base_bg = match is_ghost {
171                    true => Some(diff_deleted_bg),
172                    false if is_added => Some(diff_added_bg),
173                    false => None,
174                };
175
176                let mut x = 0;
177                let mut byte_idx_in_rope = start_byte;
178                let mut char_col = start_col;
179
180                // 3. Single loop over the graphemes of the line
181                for g in RopeGraphemes::new(&visible_chars) {
182                    let (g_width, g_bytes) = grapheme_width_and_bytes_len(g);
183                    let (_, g_chars) = grapheme_width_and_chars_len(g);
184
185                    if x >= width {
186                        break;
187                    }
188
189                    let start_x = text_x + x as u16;
190
191                    // Check if current character falls within an intra-line highlight range
192                    let is_word_highlight = intra_highlights.as_ref().map_or(false, |ranges| {
193                        ranges.iter().any(|&(start, end)| char_col >= start && char_col < end)
194                    });
195
196                    let active_bg = if is_word_highlight {
197                        if is_ghost { Some(diff_deleted_word_bg) } else { Some(diff_added_word_bg) }
198                    } else {
199                        base_bg
200                    };
201
202                    // Compose style
203                    let mut style = if let Some(bg) = active_bg {
204                        Style::default().bg(bg)
205                    } else {
206                        default_text_style
207                    };
208
209                    // Layer A: Syntax highlights
210                    for &(start, end, s) in &highlights {
211                        if start <= byte_idx_in_rope && byte_idx_in_rope < end {
212                            style = style.patch(s);
213                            if let Some(bg) = active_bg {
214                                style = style.bg(bg); // Keep active diff background
215                            }
216                            break;
217                        }
218                    }
219
220                    let global_char_idx = line_start_char + char_col;
221
222                    if !is_ghost {
223                        // Layer D: Word Highlight
224                        let is_in_word_highlight = line_word_highlights.iter().any(|&(start, end)| {
225                            global_char_idx >= start && global_char_idx < end
226                        });
227                        if is_in_word_highlight {
228                            style = style.bg(word_highlight_bg);
229                        }
230
231                        // Layer B: Selection
232                        if let Some(selection) = self.selection
233                            && !selection.is_empty()
234                        {
235                            let start = selection.start.min(selection.end);
236                            let end = selection.start.max(selection.end);
237                            if global_char_idx >= start && global_char_idx < end {
238                                style = style.bg(Color::DarkGray);
239                            }
240                        }
241
242                        // Layer C: Marks
243                        if let Some(ref marks) = self.marks {
244                            for &(m_start, m_end, m_color) in marks {
245                                if global_char_idx >= m_start && global_char_idx < m_end {
246                                    style = style.bg(m_color);
247                                }
248                            }
249                        }
250                    }
251
252                    // Draw character
253                    let display_g = g.to_string().replace('\t', " ");
254                    if start_x < area.right() {
255                        buf.set_string(start_x, draw_y, &display_g, style);
256                    }
257
258                    x = x.saturating_add(g_width);
259                    byte_idx_in_rope += g_bytes;
260                    char_col += g_chars;
261                }
262
263                // 4. Fill remaining width with background if needed
264                if let Some(bg) = base_bg
265                    && x < width
266                    && text_x + (x as u16) < area.right()
267                {
268                    let fill_x = text_x + (x as u16);
269                    let fill_width = width - x;
270                    buf.set_string(
271                        fill_x,
272                        draw_y,
273                        &" ".repeat(fill_width),
274                        Style::default().bg(bg),
275                    );
276                }
277            }
278            draw_y += 1;
279        }
280    }
281}