Skip to main content

glass_dev/development/
editor.rs

1use serde::{Deserialize, Serialize};
2
3#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
4#[serde(rename_all = "camelCase")]
5pub struct TextPosition {
6    pub line: u32,
7    pub column: u32,
8}
9
10#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
11#[serde(rename_all = "camelCase")]
12pub struct TextSelection {
13    pub anchor: TextPosition,
14    pub active: TextPosition,
15}
16
17#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
18#[serde(rename_all = "camelCase")]
19pub enum SyntaxKind {
20    Keyword,
21    String,
22    Comment,
23    Number,
24}
25
26#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
27#[serde(rename_all = "camelCase")]
28pub struct SyntaxSpan {
29    pub start: usize,
30    pub end: usize,
31    pub kind: SyntaxKind,
32}
33
34#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
35#[serde(rename_all = "camelCase")]
36pub struct FoldRegion {
37    pub start_line: u32,
38    pub end_line: u32,
39}
40
41pub fn syntax_spans(content: &str, extension: &str) -> Vec<SyntaxSpan> {
42    let keywords: &[&str] = match extension {
43        "rs" => &[
44            "fn", "let", "mut", "pub", "impl", "struct", "enum", "match", "use", "mod", "async",
45            "await", "return",
46        ],
47        "js" | "jsx" | "ts" | "tsx" => &[
48            "const",
49            "let",
50            "function",
51            "class",
52            "interface",
53            "type",
54            "import",
55            "export",
56            "return",
57            "async",
58            "await",
59        ],
60        "py" => &[
61            "def", "class", "import", "from", "return", "async", "await", "if", "else",
62        ],
63        "go" => &[
64            "func",
65            "package",
66            "import",
67            "type",
68            "struct",
69            "interface",
70            "return",
71            "go",
72            "defer",
73        ],
74        _ => &[],
75    };
76    let mut spans = Vec::new();
77    let mut offset = 0;
78    for line in content.split_inclusive('\n') {
79        let trimmed = line.trim_start();
80        if trimmed.starts_with("//") || trimmed.starts_with('#') {
81            let start = offset + line.len().saturating_sub(trimmed.len());
82            spans.push(SyntaxSpan {
83                start,
84                end: offset + line.trim_end_matches('\n').len(),
85                kind: SyntaxKind::Comment,
86            });
87            offset += line.len();
88            continue;
89        }
90        let mut token_start = None;
91        for (index, character) in line.char_indices() {
92            if character.is_ascii_alphanumeric() || character == '_' {
93                token_start.get_or_insert(index);
94            } else if let Some(start) = token_start.take() {
95                let token = &line[start..index];
96                if keywords.contains(&token) {
97                    spans.push(SyntaxSpan {
98                        start: offset + start,
99                        end: offset + index,
100                        kind: SyntaxKind::Keyword,
101                    });
102                } else if token.chars().all(|character| character.is_ascii_digit()) {
103                    spans.push(SyntaxSpan {
104                        start: offset + start,
105                        end: offset + index,
106                        kind: SyntaxKind::Number,
107                    });
108                }
109            }
110        }
111        offset += line.len();
112    }
113    spans.truncate(4096);
114    spans
115}
116
117pub fn matching_bracket(content: &str, character_index: usize) -> Option<usize> {
118    let characters = content.chars().collect::<Vec<_>>();
119    let bracket = *characters.get(character_index)?;
120    let (open, close, direction) = match bracket {
121        '(' => ('(', ')', 1_i32),
122        '[' => ('[', ']', 1),
123        '{' => ('{', '}', 1),
124        ')' => ('(', ')', -1),
125        ']' => ('[', ']', -1),
126        '}' => ('{', '}', -1),
127        _ => return None,
128    };
129    let mut depth = 0_i32;
130    let mut index = character_index as i32;
131    loop {
132        index += direction;
133        let current = *characters.get(index as usize)?;
134        if current == open {
135            depth += if direction > 0 { 1 } else { -1 };
136        } else if current == close {
137            depth += if direction > 0 { -1 } else { 1 };
138        }
139        if depth == -1 {
140            return Some(index as usize);
141        }
142    }
143}
144
145pub fn fold_regions(content: &str) -> Vec<FoldRegion> {
146    let mut stack = Vec::new();
147    let mut regions = Vec::new();
148    for (line_index, line) in content.lines().enumerate() {
149        for character in line.chars() {
150            if character == '{' {
151                stack.push(line_index as u32 + 1);
152            } else if character == '}'
153                && let Some(start_line) = stack.pop()
154                && line_index as u32 + 1 > start_line
155            {
156                regions.push(FoldRegion {
157                    start_line,
158                    end_line: line_index as u32 + 1,
159                });
160            }
161        }
162    }
163    regions.truncate(1024);
164    regions
165}
166
167#[cfg(test)]
168mod tests {
169    use super::*;
170
171    #[test]
172    fn editor_intelligence_finds_keywords_brackets_and_folds() {
173        let content = "pub fn main() {\n  let value = (1);\n}\n";
174        assert!(
175            syntax_spans(content, "rs")
176                .iter()
177                .any(|span| span.kind == SyntaxKind::Keyword)
178        );
179        let open = content
180            .chars()
181            .position(|character| character == '(')
182            .unwrap();
183        assert_eq!(
184            content
185                .chars()
186                .nth(matching_bracket(content, open).unwrap()),
187            Some(')')
188        );
189        assert_eq!(
190            fold_regions(content),
191            vec![FoldRegion {
192                start_line: 1,
193                end_line: 3
194            }]
195        );
196    }
197}