Skip to main content

comb/widgets/
code.rs

1//! A scrollable syntax-highlighted code block with a draggable custom scrollbar.
2
3use crate::core::buffer::Buffer;
4use crate::core::geom::Rect;
5use crate::core::style::Style;
6use crate::core::text::Line;
7use crate::draw::highlight::{self, HighlightTheme, Lang};
8use crate::term::event::MouseKind;
9use crate::widgets::scrollbar::Scrollbar;
10
11/// Renders highlighted source in a panel. Rebuilds its cache when source or
12/// language changes.
13pub struct CodeBlock {
14    pub lang: Lang,
15    pub theme: HighlightTheme,
16    pub scrollbar: Scrollbar,
17    pub offset: usize,
18    pub show_line_numbers: bool,
19    source: String,
20    lines: Vec<Line>,
21}
22
23impl CodeBlock {
24    pub fn new(source: impl Into<String>, lang: Lang) -> Self {
25        let mut block = CodeBlock {
26            lang,
27            theme: HighlightTheme::dark(),
28            scrollbar: Scrollbar::default(),
29            offset: 0,
30            show_line_numbers: true,
31            source: String::new(),
32            lines: Vec::new(),
33        };
34        block.set_source(source);
35        block
36    }
37
38    pub fn set_source(&mut self, source: impl Into<String>) {
39        self.source = source.into();
40        self.rebuild();
41        self.offset = 0;
42    }
43
44    pub fn set_lang(&mut self, lang: Lang) {
45        self.lang = lang;
46        self.rebuild();
47    }
48
49    fn rebuild(&mut self) {
50        let mut lines = highlight::highlight(&self.source, self.lang, &self.theme);
51        if self.show_line_numbers {
52            lines = highlight::with_line_numbers(&lines, &self.theme);
53        }
54        self.lines = lines;
55    }
56
57    pub fn line_count(&self) -> usize {
58        self.lines.len()
59    }
60
61    pub fn scroll_by(&mut self, delta: isize) {
62        let last = self.lines.len().saturating_sub(1) as isize;
63        self.offset = (self.offset as isize + delta).clamp(0, last.max(0)) as usize;
64    }
65
66    /// Render highlighted source into `area`.
67    ///
68    /// - `Some(bg)` — fill the panel and keep that background under every
69    ///   token (avoids jagged strips from fg-only highlight styles).
70    /// - `None` — draw on the terminal background with no panel fill.
71    pub fn render(&mut self, buf: &mut Buffer, area: Rect, bg: Option<Style>) {
72        if area.is_empty() {
73            return;
74        }
75        if let Some(bg) = bg {
76            buf.paint(area, bg);
77        }
78        let h = area.height as usize;
79        let overflow = self.lines.len() > h;
80        let content = self.scrollbar.content_area(area, overflow);
81        self.offset = self.offset.min(self.lines.len().saturating_sub(h));
82        match bg {
83            Some(bg) => buf.set_lines_on(content, &self.lines, self.offset, bg),
84            None => buf.set_lines(content, &self.lines, self.offset),
85        }
86        if overflow {
87            let bar = self.scrollbar.area(area);
88            self.scrollbar
89                .render(buf, bar, self.lines.len(), h, self.offset);
90        }
91    }
92
93    /// Mouse over the code panel (content + scrollbar). Returns `true` if handled.
94    pub fn handle_mouse(&mut self, area: Rect, kind: MouseKind, col: u16, row: u16) -> bool {
95        let h = area.height as usize;
96        let overflow = self.lines.len() > h;
97        if !overflow {
98            return false;
99        }
100        let bar_area = self.scrollbar.area(area);
101        if self.scrollbar.is_dragging() || bar_area.contains(col, row) {
102            return self.scrollbar.on_mouse(
103                bar_area,
104                self.lines.len(),
105                h,
106                &mut self.offset,
107                kind,
108                col,
109                row,
110            );
111        }
112        let content = self.scrollbar.content_area(area, true);
113        if !content.contains(col, row) {
114            return false;
115        }
116        match kind {
117            MouseKind::ScrollUp => {
118                self.scroll_by(-3);
119                true
120            }
121            MouseKind::ScrollDown => {
122                self.scroll_by(3);
123                true
124            }
125            _ => false,
126        }
127    }
128
129    /// End an in-progress thumb drag (call on mouse up anywhere if needed).
130    pub fn end_drag(&mut self) {
131        self.scrollbar.end_drag();
132    }
133}