oak_ruby/highlighter/
mod.rs

1//! Ruby 语法高亮器
2//!
3//! 这个模块提供了 Ruby 源代码的语法高亮功能。
4
5/// Ruby 语法高亮器
6pub struct RubyHighlighter {
7    /// 是否使用基于解析器的高亮以提高准确性
8    pub use_parser: bool,
9}
10
11impl Default for RubyHighlighter {
12    fn default() -> Self {
13        Self { use_parser: false }
14    }
15}
16
17impl RubyHighlighter {
18    /// 创建一个新的 Ruby 高亮器实例
19    pub fn new() -> Self {
20        Self::default()
21    }
22
23    /// 高亮 Ruby 关键字
24    pub fn highlight(&self, text: &str) -> Vec<(usize, usize, String)> {
25        let mut highlights = Vec::new();
26        let keywords = [
27            "if", "unless", "elsif", "else", "case", "when", "then", "for", "while", "until", "break", "next", "redo", "retry", "return", "yield", "def", "class", "module", "end", "lambda", "proc", "begin", "rescue", "ensure", "raise", "require", "load",
28            "include", "extend", "prepend", "and", "or", "not", "in", "true", "false", "nil", "super", "self", "alias", "undef", "defined", "do",
29        ];
30
31        for keyword in &keywords {
32            let mut start = 0;
33            while let Some(pos) = text[start..].find(keyword) {
34                let absolute_pos = start + pos;
35                let end_pos = absolute_pos + keyword.len();
36
37                let is_word_boundary_before = absolute_pos == 0 || !text.chars().nth(absolute_pos - 1).unwrap_or(' ').is_alphanumeric();
38                let is_word_boundary_after = end_pos >= text.len() || !text.chars().nth(end_pos).unwrap_or(' ').is_alphanumeric();
39
40                if is_word_boundary_before && is_word_boundary_after {
41                    highlights.push((absolute_pos, end_pos, "keyword".to_string()));
42                }
43                start = absolute_pos + 1;
44            }
45        }
46        highlights
47    }
48}