ratatui_toolkit/widgets/markdown_widget/extensions/theme/syntax_highlighter/methods/
highlight.rs

1//! Highlight method for SyntaxHighlighter.
2
3use ratatui::text::{Line, Text};
4
5use crate::widgets::markdown_widget::extensions::theme::syntax_highlighter::SyntaxHighlighter;
6
7#[cfg(feature = "markdown")]
8impl SyntaxHighlighter {
9    /// Highlight code content for a given language.
10    ///
11    /// # Arguments
12    ///
13    /// * `content` - The code content to highlight
14    /// * `language` - The language identifier (e.g., "rust", "python", "javascript")
15    ///
16    /// # Returns
17    ///
18    /// Syntax highlighted text, or `None` if language is not recognized
19    pub fn highlight(&self, content: &str, language: &str) -> Option<Text<'static>> {
20        let syntax = self.find_syntax(language)?;
21
22        let mut highlighter = syntect::easy::HighlightLines::new(&syntax, &self.theme);
23
24        let mut lines = Vec::new();
25
26        for line in content.lines() {
27            if let Ok(highlighted) = highlighter.highlight_line(line, &self.syntax_set) {
28                let spans: Vec<ratatui::text::Span<'static>> = highlighted
29                    .into_iter()
30                    .map(|(style, text)| {
31                        let ratatui_style = syntect_tui::translate_style(style)
32                            .unwrap_or_else(|_| ratatui::style::Style::default());
33                        ratatui::text::Span::styled(text.to_string(), ratatui_style)
34                    })
35                    .collect();
36
37                lines.push(Line::from(spans));
38            } else {
39                lines.push(Line::from(line.to_string()));
40            }
41        }
42
43        Some(Text::from(lines))
44    }
45}
46
47#[cfg(not(feature = "markdown"))]
48impl SyntaxHighlighter {
49    /// Highlight code content (always returns None when markdown feature is disabled).
50    pub fn highlight(&self, _content: &str, _language: &str) -> Option<Text<'static>> {
51        None
52    }
53}