ratatui_toolkit/widgets/code_diff/widget/methods/helpers/
render_line_number.rs

1use ratatui::buffer::Buffer;
2use ratatui::layout::Position;
3use ratatui::style::Style;
4
5use crate::widgets::code_diff::diff_config::DiffConfig;
6
7/// Renders a line number in the gutter.
8///
9/// # Arguments
10///
11/// * `line_num` - The line number to render (None for empty space)
12/// * `config` - Display configuration
13/// * `x` - Starting x position
14/// * `y` - Y position
15/// * `buf` - The buffer to render to
16/// * `bg_style` - Background style to apply
17///
18/// # Returns
19///
20/// The x position after rendering the line number
21pub fn render_line_number(
22    line_num: Option<usize>,
23    config: &DiffConfig,
24    x: u16,
25    y: u16,
26    buf: &mut Buffer,
27    bg_style: Style,
28) -> u16 {
29    if !config.show_line_numbers {
30        return x;
31    }
32
33    let width = config.line_number_width as usize;
34    let num_style = bg_style.fg(config.line_number_fg);
35
36    let num_str = match line_num {
37        Some(n) => format!("{:>width$}", n, width = width),
38        None => " ".repeat(width),
39    };
40
41    let mut current_x = x;
42    for ch in num_str.chars() {
43        if current_x < x + config.line_number_width {
44            if let Some(cell) = buf.cell_mut(Position::new(current_x, y)) {
45                cell.set_char(ch);
46                cell.set_style(num_style);
47            }
48            current_x += 1;
49        }
50    }
51
52    // Add separator space
53    if current_x < x + config.line_number_width + 1 {
54        if let Some(cell) = buf.cell_mut(Position::new(current_x, y)) {
55            cell.set_char(' ');
56            cell.set_style(bg_style);
57        }
58        current_x += 1;
59    }
60
61    current_x
62}