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
//!
//! Line numbers
//!

use crate::_private::NonExhaustive;
use crate::upos_type;
use format_num_pattern::NumberFormat;
use rat_event::util::MouseFlags;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::prelude::{BlockExt, StatefulWidget, Style};
use ratatui::text::Line;
use ratatui::widgets::{Block, Widget};

/// Renders line-numbers.
#[derive(Debug, Default, Clone)]
pub struct LineNumbers<'a> {
    start: upos_type,
    end: Option<upos_type>,
    cursor: upos_type,
    relative: bool,
    flags: Vec<Line<'a>>,

    flag_width: Option<u16>,
    margin: (u16, u16),

    format: Option<NumberFormat>,
    style: Style,
    cursor_style: Option<Style>,

    block: Option<Block<'a>>,
}

/// Styles as a package.
#[derive(Debug, Clone)]
pub struct LineNumberStyle {
    pub flag_width: Option<u16>,
    pub margin: Option<(u16, u16)>,
    pub format: Option<NumberFormat>,
    pub style: Style,
    pub cursor_style: Option<Style>,
    pub block: Option<Block<'static>>,

    pub non_exhaustive: NonExhaustive,
}

/// State
#[derive(Debug, Clone)]
pub struct LineNumberState {
    pub area: Rect,
    pub inner: Rect,

    pub start: upos_type,

    /// Helper for mouse.
    pub mouse: MouseFlags,

    pub non_exhaustive: NonExhaustive,
}

impl<'a> LineNumbers<'a> {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn start(mut self, start: upos_type) -> Self {
        self.start = start;
        self
    }

    pub fn end(mut self, end: upos_type) -> Self {
        self.end = Some(end);
        self
    }

    pub fn cursor(mut self, cursor: upos_type) -> Self {
        self.cursor = cursor;
        self
    }

    pub fn relative(mut self, relative: bool) -> Self {
        self.relative = relative;
        self
    }

    pub fn flags(mut self, flags: Vec<Line<'a>>) -> Self {
        self.flags = flags;
        self
    }

    pub fn flag_width(mut self, width: u16) -> Self {
        self.flag_width = Some(width);
        self
    }

    pub fn margin(mut self, margin: (u16, u16)) -> Self {
        self.margin = margin;
        self
    }

    pub fn format(mut self, format: NumberFormat) -> Self {
        self.format = Some(format);
        self
    }

    pub fn styles(mut self, styles: LineNumberStyle) -> Self {
        if let Some(flag_width) = styles.flag_width {
            self.flag_width = Some(flag_width);
        }
        if let Some(margin) = styles.margin {
            self.margin = margin;
        }
        if let Some(format) = styles.format {
            self.format = Some(format);
        }
        self.style = styles.style;
        if let Some(cursor_style) = styles.cursor_style {
            self.cursor_style = Some(cursor_style);
        }
        if let Some(block) = styles.block {
            self.block = Some(block);
        }
        self
    }

    pub fn style(mut self, style: Style) -> Self {
        self.style = style;
        self
    }

    pub fn cursor_style(mut self, style: Style) -> Self {
        self.cursor_style = Some(style);
        self
    }

    pub fn block(mut self, block: Block<'a>) -> Self {
        self.block = Some(block);
        self
    }

    pub fn width(&self) -> u16 {
        let nr_width = if let Some(end) = self.end {
            end.ilog10() as u16 + 1
        } else {
            (self.start + 100).ilog10() as u16 + 1
        };
        let flag_width = if let Some(flag_width) = self.flag_width {
            flag_width
        } else {
            self.flags
                .iter()
                .map(|v| v.width() as u16)
                .max()
                .unwrap_or_default()
        };
        let block_width = {
            let area = self.block.inner_if_some(Rect::new(0, 0, 2, 2));
            2 - area.width
        };

        nr_width + flag_width + self.margin.0 + self.margin.1 + block_width + 1
    }
}

impl Default for LineNumberStyle {
    fn default() -> Self {
        Self {
            flag_width: None,
            margin: None,
            format: None,
            style: Default::default(),
            cursor_style: None,
            block: None,
            non_exhaustive: NonExhaustive,
        }
    }
}

impl<'a> StatefulWidget for LineNumbers<'a> {
    type State = LineNumberState;

    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        state.area = area;
        state.inner = self.block.inner_if_some(area);
        let inner = state.inner;
        state.start = self.start;
        let end = self.end.unwrap_or(upos_type::MAX);

        let nr_width = if let Some(end) = self.end {
            end.ilog10() as u16 + 1
        } else {
            (self.start + 100).ilog10() as u16 + 1
        };
        let flag_width = if let Some(flag_width) = self.flag_width {
            flag_width
        } else {
            self.flags
                .iter()
                .map(|v| v.width() as u16)
                .max()
                .unwrap_or_default()
        };
        let format = if let Some(format) = self.format {
            format
        } else {
            let mut f = "#".repeat(nr_width.saturating_sub(1) as usize);
            f.push('0');
            NumberFormat::new(f).expect("valid")
        };

        let cursor_style = if let Some(cursor_style) = self.cursor_style {
            cursor_style
        } else {
            self.style
        };

        self.block.render(area, buf);
        // set base style
        for y in inner.top()..inner.bottom() {
            for x in inner.left()..inner.right() {
                if let Some(cell) = buf.cell_mut((x, y)) {
                    cell.reset();
                    cell.set_style(self.style);
                }
            }
        }

        let mut tmp = String::new();
        for y in inner.top()..inner.bottom() {
            let (nr, is_cursor) = if self.relative {
                let pos = self.start + (y - inner.y) as upos_type;
                (pos.abs_diff(self.cursor), pos == self.cursor)
            } else {
                let pos = self.start + (y - inner.y) as upos_type;
                (pos, pos == self.cursor)
            };

            tmp.clear();
            if nr < end {
                _ = format.fmt_to(nr, &mut tmp);
            }

            if is_cursor {
                for x in inner.x + self.margin.0..inner.x + self.margin.0 + nr_width {
                    if let Some(cell) = buf.cell_mut((x, y)) {
                        cell.reset();
                        cell.set_style(cursor_style);
                    }
                }
            }
            buf.set_string(inner.x + self.margin.0, y, &tmp, Style::default());
            if let Some(flags) = self.flags.get((y - inner.y) as usize) {
                flags.render(
                    Rect::new(inner.x + self.margin.0 + nr_width + 1, y, flag_width, 1),
                    buf,
                );
            }
        }
    }
}

impl Default for LineNumberState {
    fn default() -> Self {
        Self {
            area: Default::default(),
            inner: Default::default(),
            start: 0,
            mouse: Default::default(),
            non_exhaustive: NonExhaustive,
        }
    }
}

impl LineNumberState {
    pub fn new() -> Self {
        Self::default()
    }
}