Skip to main content

glass_dev/development/
editor.rs

1use serde::{Deserialize, Serialize};
2
3/// One-based line and character-column position in editor text.
4#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
5#[serde(rename_all = "camelCase")]
6pub struct TextPosition {
7    /// One-based line number.
8    pub line: u32,
9    /// One-based character column within the line; one is before its first character.
10    pub column: u32,
11}
12
13/// A selection represented by its fixed anchor and active cursor positions.
14#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
15#[serde(rename_all = "camelCase")]
16pub struct TextSelection {
17    /// Position where the selection began.
18    pub anchor: TextPosition,
19    /// Current cursor position; may be before or after `anchor`.
20    pub active: TextPosition,
21}
22/// Lifecycle of an anchored editor comment.
23#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
24#[serde(rename_all = "camelCase")]
25pub enum EditorCommentState {
26    Open,
27    Resolved,
28}
29
30/// A durable human or agent comment anchored to a source range.
31#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
32#[serde(rename_all = "camelCase")]
33pub struct EditorComment {
34    pub id: String,
35    pub path: String,
36    pub start_line: u32,
37    pub end_line: u32,
38    pub text: String,
39    pub actor: super::Actor,
40    pub state: EditorCommentState,
41    pub created_revision: u64,
42    pub updated_revision: u64,
43}
44
45/// Lifecycle of a proposed editor change.
46#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
47#[serde(rename_all = "camelCase")]
48pub enum EditorProposalState {
49    Pending,
50    Accepted,
51    Rejected,
52    Stale,
53}
54
55/// An unsaved, reviewable replacement produced by an agent or human.
56#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
57#[serde(rename_all = "camelCase")]
58pub struct EditorProposal {
59    pub id: String,
60    pub path: String,
61    pub summary: String,
62    pub actor: super::Actor,
63    pub base_hash: String,
64    pub base_revision: u64,
65    pub original: String,
66    pub proposed: String,
67    pub state: EditorProposalState,
68    pub created_revision: u64,
69    pub updated_revision: u64,
70}
71
72/// A named in-memory checkpoint of open editor buffers.
73#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
74#[serde(rename_all = "camelCase")]
75pub struct EditorCheckpoint {
76    pub id: String,
77    pub name: String,
78    pub actor: super::Actor,
79    pub revision: u64,
80    pub buffers: Vec<super::EditorBuffer>,
81}
82
83impl TextSelection {
84    pub fn collapsed(position: TextPosition) -> Self {
85        Self {
86            anchor: position,
87            active: position,
88        }
89    }
90
91    pub fn is_empty(&self) -> bool {
92        self.anchor == self.active
93    }
94
95    pub fn ordered(&self) -> (TextPosition, TextPosition) {
96        if (self.anchor.line, self.anchor.column) <= (self.active.line, self.active.column) {
97            (self.anchor, self.active)
98        } else {
99            (self.active, self.anchor)
100        }
101    }
102}
103
104/// Convert a one-based editor position to a UTF-8 byte offset.
105///
106/// Columns address character boundaries, not bytes. The position immediately
107/// after the final character on a line is valid, including on an empty line.
108pub(crate) fn text_position_offset(content: &str, position: TextPosition) -> Option<usize> {
109    if position.line == 0 || position.column == 0 {
110        return None;
111    }
112
113    let mut line_start = 0;
114    for (index, line) in content.split('\n').enumerate() {
115        if index + 1 == position.line as usize {
116            let character_index = position.column.saturating_sub(1) as usize;
117            let character_count = line.chars().count();
118            if character_index > character_count {
119                return None;
120            }
121            let byte_offset = line
122                .char_indices()
123                .nth(character_index)
124                .map(|(offset, _)| offset)
125                .unwrap_or(line.len());
126            return Some(line_start + byte_offset);
127        }
128        line_start = line_start.saturating_add(line.len() + 1);
129    }
130    None
131}
132
133/// Convert a UTF-8 byte offset to the nearest one-based editor position.
134pub(crate) fn text_position_at_offset(content: &str, offset: usize) -> Option<TextPosition> {
135    if offset > content.len() || !content.is_char_boundary(offset) {
136        return None;
137    }
138    let prefix = &content[..offset];
139    let line = prefix.bytes().filter(|byte| *byte == b'\n').count() as u32 + 1;
140    let column = prefix
141        .rsplit_once('\n')
142        .map(|(_, current_line)| current_line.chars().count())
143        .unwrap_or_else(|| prefix.chars().count()) as u32
144        + 1;
145    Some(TextPosition { line, column })
146}
147
148/// Return ordered UTF-8 byte offsets for a selection.
149pub(crate) fn selection_offsets(
150    content: &str,
151    selection: &TextSelection,
152) -> Option<(usize, usize)> {
153    let (start, end) = selection.ordered();
154    let start_offset = text_position_offset(content, start)?;
155    let end_offset = text_position_offset(content, end)?;
156    (start_offset <= end_offset).then_some((start_offset, end_offset))
157}
158/// Coarse syntax categories emitted by [`syntax_spans`].
159#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
160#[serde(rename_all = "camelCase")]
161pub enum SyntaxKind {
162    /// Recognized language keyword.
163    Keyword,
164    /// Reserved for string-token spans.
165    String,
166    /// A line comment.
167    Comment,
168    /// An ASCII decimal number token.
169    Number,
170}
171
172/// Half-open byte range and category for one syntax span.
173#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
174#[serde(rename_all = "camelCase")]
175pub struct SyntaxSpan {
176    /// Inclusive start byte offset.
177    pub start: usize,
178    /// Exclusive end byte offset.
179    pub end: usize,
180    /// Category assigned to the span.
181    pub kind: SyntaxKind,
182}
183
184/// One-based inclusive line range that can be folded.
185#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
186#[serde(rename_all = "camelCase")]
187pub struct FoldRegion {
188    /// Line containing the opening brace.
189    pub start_line: u32,
190    /// Line containing the matching closing brace.
191    pub end_line: u32,
192}
193
194/// Find coarse keyword, comment, and number spans in source text.
195///
196/// `extension` is a bare lowercase suffix. Supported keyword tables are
197/// `rs`, `js`, `jsx`, `ts`, `tsx`, `py`, and `go`; unknown suffixes produce
198/// no keyword spans. Returned offsets are UTF-8 byte offsets and output is
199/// capped at 4,096 spans. This low-level helper is independent of the
200/// private syntect-based TUI renderer.
201pub fn syntax_spans(content: &str, extension: &str) -> Vec<SyntaxSpan> {
202    let keywords: &[&str] = match extension {
203        "rs" => &[
204            "fn", "let", "mut", "pub", "impl", "struct", "enum", "match", "use", "mod", "async",
205            "await", "return",
206        ],
207        "js" | "jsx" | "ts" | "tsx" => &[
208            "const",
209            "let",
210            "function",
211            "class",
212            "interface",
213            "type",
214            "import",
215            "export",
216            "return",
217            "async",
218            "await",
219        ],
220        "py" => &[
221            "def", "class", "import", "from", "return", "async", "await", "if", "else",
222        ],
223        "go" => &[
224            "func",
225            "package",
226            "import",
227            "type",
228            "struct",
229            "interface",
230            "return",
231            "go",
232            "defer",
233        ],
234        _ => &[],
235    };
236    let mut spans = Vec::new();
237    let mut offset = 0;
238    for line in content.split_inclusive('\n') {
239        let trimmed = line.trim_start();
240        if trimmed.starts_with("//") || trimmed.starts_with('#') {
241            let start = offset + line.len().saturating_sub(trimmed.len());
242            spans.push(SyntaxSpan {
243                start,
244                end: offset + line.trim_end_matches('\n').len(),
245                kind: SyntaxKind::Comment,
246            });
247            offset += line.len();
248            continue;
249        }
250        let mut token_start = None;
251        for (index, character) in line.char_indices() {
252            if character.is_ascii_alphanumeric() || character == '_' {
253                token_start.get_or_insert(index);
254            } else if let Some(start) = token_start.take() {
255                let token = &line[start..index];
256                if keywords.contains(&token) {
257                    spans.push(SyntaxSpan {
258                        start: offset + start,
259                        end: offset + index,
260                        kind: SyntaxKind::Keyword,
261                    });
262                } else if token.chars().all(|character| character.is_ascii_digit()) {
263                    spans.push(SyntaxSpan {
264                        start: offset + start,
265                        end: offset + index,
266                        kind: SyntaxKind::Number,
267                    });
268                }
269            }
270        }
271        offset += line.len();
272    }
273    spans.truncate(4096);
274    spans
275}
276
277/// Return the matching bracket's character index, if `character_index` points
278/// to `(`, `[`, `{`, `)`, `]`, or `}` and a balanced partner exists.
279pub fn matching_bracket(content: &str, character_index: usize) -> Option<usize> {
280    let characters = content.chars().collect::<Vec<_>>();
281    let bracket = *characters.get(character_index)?;
282    let (open, close, direction) = match bracket {
283        '(' => ('(', ')', 1_i32),
284        '[' => ('[', ']', 1),
285        '{' => ('{', '}', 1),
286        ')' => ('(', ')', -1),
287        ']' => ('[', ']', -1),
288        '}' => ('{', '}', -1),
289        _ => return None,
290    };
291    let mut depth = 0_i32;
292    let mut index = character_index as i32;
293    loop {
294        index += direction;
295        let current = *characters.get(index as usize)?;
296        if current == open {
297            depth += if direction > 0 { 1 } else { -1 };
298        } else if current == close {
299            depth += if direction > 0 { -1 } else { 1 };
300        }
301        if depth == -1 {
302            return Some(index as usize);
303        }
304    }
305}
306
307/// Collect brace-delimited fold regions using one-based inclusive line numbers.
308///
309/// The scan is intentionally lexical and returns at most 1,024 regions.
310pub fn fold_regions(content: &str) -> Vec<FoldRegion> {
311    let mut stack = Vec::new();
312    let mut regions = Vec::new();
313    for (line_index, line) in content.lines().enumerate() {
314        for character in line.chars() {
315            if character == '{' {
316                stack.push(line_index as u32 + 1);
317            } else if character == '}'
318                && let Some(start_line) = stack.pop()
319                && line_index as u32 + 1 > start_line
320            {
321                regions.push(FoldRegion {
322                    start_line,
323                    end_line: line_index as u32 + 1,
324                });
325            }
326        }
327    }
328    regions.truncate(1024);
329    regions
330}
331
332#[cfg(test)]
333mod tests {
334    use super::*;
335
336    #[test]
337    fn editor_intelligence_finds_keywords_brackets_and_folds() {
338        let content = "pub fn main() {\n  let value = (1);\n}\n";
339        assert!(
340            syntax_spans(content, "rs")
341                .iter()
342                .any(|span| span.kind == SyntaxKind::Keyword)
343        );
344        let open = content
345            .chars()
346            .position(|character| character == '(')
347            .unwrap();
348        assert_eq!(
349            content
350                .chars()
351                .nth(matching_bracket(content, open).unwrap()),
352            Some(')')
353        );
354        assert_eq!(
355            fold_regions(content),
356            vec![FoldRegion {
357                start_line: 1,
358                end_line: 3
359            }]
360        );
361    }
362}