sql_cli/ui/utils/
text_utils.rs

1/// Text processing utilities extracted from enhanced_tui
2/// Extract a partial word at the cursor position in a query string
3/// Used for completion and search functionality
4pub fn extract_partial_word_at_cursor(query: &str, cursor_pos: usize) -> Option<String> {
5    if cursor_pos == 0 || cursor_pos > query.len() {
6        return None;
7    }
8
9    let chars: Vec<char> = query.chars().collect();
10    let mut start = cursor_pos;
11    let end = cursor_pos;
12
13    // Check if we might be in a quoted identifier by scanning backwards
14    let mut in_quote = false;
15
16    // First, check if we're inside quotes by looking for an opening quote before cursor
17    for i in (0..cursor_pos).rev() {
18        if i < chars.len() {
19            if chars[i] == '"' {
20                // Found a potential opening quote
21                // Check if there's a closing quote after cursor or not
22                let mut found_closing = false;
23                for j in cursor_pos..chars.len() {
24                    if chars[j] == '"' {
25                        found_closing = true;
26                        break;
27                    }
28                }
29                // If no closing quote found, or cursor is before the closing quote, we're in a quoted identifier
30                if !found_closing || cursor_pos <= chars.len() {
31                    in_quote = true;
32                    start = i;
33                    break;
34                }
35            }
36        }
37    }
38
39    // If we found an opening quote, include everything up to cursor
40    if in_quote {
41        // Convert back to byte positions
42        let start_byte = chars[..start].iter().map(|c| c.len_utf8()).sum();
43        let end_byte = chars[..end].iter().map(|c| c.len_utf8()).sum();
44
45        if start_byte < end_byte {
46            return Some(query[start_byte..end_byte].to_string());
47        }
48    }
49
50    // Otherwise, find start of word normally (go backward)
51    while start > 0 {
52        let prev_char = chars[start - 1];
53        if prev_char.is_alphanumeric() || prev_char == '_' {
54            start -= 1;
55        } else {
56            break;
57        }
58    }
59
60    // Convert back to byte positions
61    let start_byte = chars[..start].iter().map(|c| c.len_utf8()).sum();
62    let end_byte = chars[..end].iter().map(|c| c.len_utf8()).sum();
63
64    if start_byte < end_byte {
65        Some(query[start_byte..end_byte].to_string())
66    } else {
67        None
68    }
69}
70
71/// Get the token at cursor position in SQL text
72pub fn get_token_at_cursor(sql_text: &str, cursor_pos: usize) -> Option<String> {
73    if sql_text.is_empty() || cursor_pos > sql_text.len() {
74        return None;
75    }
76
77    let chars: Vec<char> = sql_text.chars().collect();
78    if cursor_pos > chars.len() {
79        return None;
80    }
81
82    // Find word boundaries
83    let mut start = cursor_pos;
84    let mut end = cursor_pos;
85
86    // Move start backward to beginning of word
87    while start > 0 {
88        let idx = start - 1;
89        if idx < chars.len() && (chars[idx].is_alphanumeric() || chars[idx] == '_') {
90            start -= 1;
91        } else {
92            break;
93        }
94    }
95
96    // Move end forward to end of word
97    while end < chars.len() {
98        if chars[end].is_alphanumeric() || chars[end] == '_' {
99            end += 1;
100        } else {
101            break;
102        }
103    }
104
105    if start < end {
106        let token: String = chars[start..end].iter().collect();
107        Some(token)
108    } else {
109        None
110    }
111}
112
113/// Calculate the cursor position within a token for syntax highlighting
114pub fn get_cursor_token_position(sql_text: &str, cursor_pos: usize) -> (usize, usize) {
115    if let Some(token) = get_token_at_cursor(sql_text, cursor_pos) {
116        // Find where this token starts in the text
117        let before_cursor = &sql_text[..cursor_pos.min(sql_text.len())];
118        if let Some(rev_pos) = before_cursor.rfind(&token) {
119            let token_start = rev_pos;
120            let pos_in_token = cursor_pos.saturating_sub(token_start);
121            return (token_start, pos_in_token);
122        }
123    }
124    (cursor_pos, 0)
125}
126
127#[cfg(test)]
128mod tests {
129    use super::*;
130
131    #[test]
132    fn test_extract_partial_word() {
133        assert_eq!(
134            extract_partial_word_at_cursor("SELECT coun", 11),
135            Some("coun".to_string())
136        );
137
138        assert_eq!(
139            extract_partial_word_at_cursor("SELECT \"quoted col", 18),
140            Some("\"quoted col".to_string())
141        );
142
143        assert_eq!(extract_partial_word_at_cursor("", 0), None);
144    }
145
146    #[test]
147    fn test_get_token_at_cursor() {
148        assert_eq!(
149            get_token_at_cursor("SELECT column_name FROM", 10),
150            Some("column_name".to_string())
151        );
152
153        assert_eq!(
154            get_token_at_cursor("WHERE id = 123", 7),
155            Some("id".to_string())
156        );
157    }
158}