Skip to main content

ratatui_code_editor/
code.rs

1use crate::history::History;
2use crate::selection::Selection;
3use crate::utils::{calculate_end_position, comment as lang_comment, count_indent_units, indent};
4use anyhow::{Result, anyhow};
5use ropey::{Rope, RopeSlice};
6use rust_embed::RustEmbed;
7use std::cell::RefCell;
8use std::collections::HashMap;
9use std::rc::Rc;
10use streaming_iterator::StreamingIterator;
11use tree_sitter::{InputEdit, Point, QueryCursor};
12use tree_sitter::{Language, Node, Parser, Query, Tree};
13use unicode_segmentation::{GraphemeCursor, GraphemeIncomplete};
14use unicode_width::UnicodeWidthStr;
15
16#[derive(RustEmbed)]
17#[folder = ""]
18#[include = "langs/*/*"]
19struct LangAssets;
20
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub enum Operation {
23    Insert,
24    Remove,
25}
26
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct Edit {
29    pub start: usize,
30    pub text: String,
31    pub operation: Operation,
32}
33
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct EditBatch {
36    pub edits: Vec<Edit>,
37    pub state_before: Option<EditState>,
38    pub state_after: Option<EditState>,
39}
40
41impl EditBatch {
42    pub fn new() -> Self {
43        Self {
44            edits: Vec::new(),
45            state_before: None,
46            state_after: None,
47        }
48    }
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub struct EditState {
53    pub offset: usize,
54    pub selection: Option<Selection>,
55}
56
57/// A multi-line source range that can be collapsed by the editor.
58#[derive(Clone, Copy, Debug, Eq, PartialEq)]
59pub struct FoldRange {
60    pub start_line: usize,
61    pub end_line: usize,
62}
63
64pub struct Code {
65    pub(crate) content: ropey::Rope,
66    lang: String,
67    tree: Option<Tree>,
68    parser: Option<Parser>,
69    query: Option<Query>,
70    fold_query: Option<Query>,
71    fold_ranges: Vec<FoldRange>,
72    applying_history: bool,
73    history: History,
74    current_batch: EditBatch,
75    injection_parsers: Option<HashMap<String, Rc<RefCell<Parser>>>>,
76    injection_queries: Option<HashMap<String, Query>>,
77    change_callback: Option<Box<dyn Fn(Vec<(usize, usize, usize, usize, String)>)>>,
78    custom_highlights: Option<HashMap<String, String>>,
79}
80
81impl Code {
82    /// Create a new `Code` instance with the given text and language.
83    pub fn new(
84        text: &str,
85        lang: &str,
86        custom_highlights: Option<HashMap<String, String>>,
87    ) -> Result<Self> {
88        let mut code = Self {
89            content: Rope::from_str(text),
90            lang: lang.to_string(),
91            tree: None,
92            parser: None,
93            query: None,
94            fold_query: None,
95            fold_ranges: Vec::new(),
96            applying_history: true,
97            history: History::new(1000),
98            current_batch: EditBatch::new(),
99            injection_parsers: None,
100            injection_queries: None,
101            change_callback: None,
102            custom_highlights,
103        };
104
105        if let Some(language) = Self::get_language(lang) {
106            let highlights = code.get_highlights(lang)?;
107            let mut parser = Parser::new();
108            parser.set_language(&language)?;
109            let tree = parser.parse(text, None);
110            let query = Query::new(&language, &highlights)?;
111            let fold_query = code
112                .get_folds(lang)
113                .and_then(|source| Query::new(&language, &source).ok());
114            let (iparsers, iqueries) = code.init_injections(&query)?;
115            code.tree = tree;
116            code.parser = Some(parser);
117            code.query = Some(query);
118            code.fold_query = fold_query;
119            code.update_fold_ranges();
120            code.injection_parsers = Some(iparsers);
121            code.injection_queries = Some(iqueries);
122        }
123
124        Ok(code)
125    }
126
127    fn get_language(lang: &str) -> Option<Language> {
128        match lang {
129            "rust" => Some(tree_sitter_rust::LANGUAGE.into()),
130            "javascript" => Some(tree_sitter_javascript::LANGUAGE.into()),
131            "typescript" => Some(tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()),
132            "python" => Some(tree_sitter_python::LANGUAGE.into()),
133            "go" => Some(tree_sitter_go::LANGUAGE.into()),
134            "java" => Some(tree_sitter_java::LANGUAGE.into()),
135            "c_sharp" => Some(tree_sitter_c_sharp::LANGUAGE.into()),
136            "c" => Some(tree_sitter_c::LANGUAGE.into()),
137            "cpp" => Some(tree_sitter_cpp::LANGUAGE.into()),
138            "html" => Some(tree_sitter_html::LANGUAGE.into()),
139            "css" => Some(tree_sitter_css::LANGUAGE.into()),
140            "yaml" => Some(tree_sitter_yaml::LANGUAGE.into()),
141            "json" => Some(tree_sitter_json::LANGUAGE.into()),
142            "toml" => Some(tree_sitter_toml_ng::LANGUAGE.into()),
143            "shell" => Some(tree_sitter_bash::LANGUAGE.into()),
144            "markdown" => Some(tree_sitter_md::LANGUAGE.into()),
145            "markdown-inline" => Some(tree_sitter_md::INLINE_LANGUAGE.into()),
146            _ => None,
147        }
148    }
149
150    fn get_highlights(&self, lang: &str) -> anyhow::Result<String> {
151        if let Some(highlights_map) = &self.custom_highlights {
152            if let Some(highlights) = highlights_map.get(lang) {
153                return Ok(highlights.clone());
154            }
155        }
156        let p = format!("langs/{}/highlights.scm", lang);
157        let highlights_bytes =
158            LangAssets::get(&p).ok_or_else(|| anyhow!("No highlights found for {}", lang))?;
159        let highlights_bytes = highlights_bytes.data.as_ref();
160        let highlights = std::str::from_utf8(highlights_bytes)?;
161        Ok(highlights.to_string())
162    }
163
164    fn get_folds(&self, lang: &str) -> Option<String> {
165        let path = format!("langs/{lang}/folds.scm");
166        let source = LangAssets::get(&path)?;
167        std::str::from_utf8(source.data.as_ref())
168            .ok()
169            .map(str::to_owned)
170    }
171
172    fn init_injections(
173        &self,
174        query: &Query,
175    ) -> anyhow::Result<(HashMap<String, Rc<RefCell<Parser>>>, HashMap<String, Query>)> {
176        let mut injection_parsers = HashMap::new();
177        let mut injection_queries = HashMap::new();
178
179        for name in query.capture_names() {
180            if let Some(lang) = name.strip_prefix("injection.content.") {
181                if injection_parsers.contains_key(lang) {
182                    continue;
183                }
184                if let Some(language) = Self::get_language(lang) {
185                    let mut parser = Parser::new();
186                    parser.set_language(&language)?;
187                    let highlights = self.get_highlights(lang)?;
188                    let inj_query = Query::new(&language, &highlights)?;
189
190                    injection_parsers.insert(lang.to_string(), Rc::new(RefCell::new(parser)));
191                    injection_queries.insert(lang.to_string(), inj_query);
192                } else {
193                    eprintln!("Unknown injection language: {}", lang);
194                }
195            }
196        }
197
198        Ok((injection_parsers, injection_queries))
199    }
200
201    pub fn point(&self, offset: usize) -> (usize, usize) {
202        let row = self.content.char_to_line(offset);
203        let line_start = self.content.line_to_char(row);
204        let col = offset - line_start;
205        (row, col)
206    }
207
208    fn update_fold_ranges(&mut self) {
209        let (Some(tree), Some(query)) = (&self.tree, &self.fold_query) else {
210            self.fold_ranges.clear();
211            return;
212        };
213        let mut cursor = QueryCursor::new();
214        let mut matches = cursor.matches(
215            &query,
216            tree.root_node(),
217            RopeProvider(self.content.slice(..)),
218        );
219        let mut ranges = Vec::new();
220        while let Some(m) = matches.next() {
221            for capture in m.captures {
222                let start_line = capture.node.start_position().row;
223                let end_line = capture.node.end_position().row;
224                if end_line > start_line {
225                    ranges.push(FoldRange {
226                        start_line,
227                        end_line,
228                    });
229                }
230            }
231        }
232        ranges.sort_by_key(|range| (range.start_line, range.end_line));
233        ranges.dedup();
234        self.fold_ranges = ranges;
235    }
236
237    /// Returns cached Tree-sitter foldable ranges for the current syntax tree.
238    pub fn fold_ranges(&self) -> &[FoldRange] {
239        &self.fold_ranges
240    }
241
242    pub fn has_fold_range(&self, start_line: usize, end_line: usize) -> bool {
243        self.fold_ranges
244            .binary_search_by_key(&(start_line, end_line), |range| {
245                (range.start_line, range.end_line)
246            })
247            .is_ok()
248    }
249
250    pub fn fold_range_at_start(&self, line_idx: usize) -> Option<FoldRange> {
251        self.fold_ranges
252            .iter()
253            .copied()
254            .filter(|range| range.start_line == line_idx)
255            .max_by_key(|range| range.end_line)
256    }
257
258    pub fn offset(&self, row: usize, col: usize) -> usize {
259        let line_start = self.content.line_to_char(row);
260        line_start + col
261    }
262
263    pub fn get_content(&self) -> String {
264        self.content.to_string()
265    }
266
267    pub fn lang(&self) -> &str {
268        &self.lang
269    }
270
271    pub fn slice(&self, start: usize, end: usize) -> String {
272        self.content.slice(start..end).to_string()
273    }
274
275    pub fn len(&self) -> usize {
276        self.content.len_chars()
277    }
278
279    pub fn len_lines(&self) -> usize {
280        self.content.len_lines()
281    }
282
283    pub fn len_chars(&self) -> usize {
284        self.content.len_chars()
285    }
286
287    pub fn line_to_char(&self, line_idx: usize) -> usize {
288        self.content.line_to_char(line_idx)
289    }
290    pub fn char_to_byte(&self, char_idx: usize) -> usize {
291        self.content.char_to_byte(char_idx)
292    }
293
294    pub fn line_len(&self, idx: usize) -> usize {
295        let line = self.content.line(idx);
296        let len = line.len_chars();
297        if idx == self.content.len_lines() - 1 {
298            len
299        } else {
300            len.saturating_sub(1)
301        }
302    }
303
304    pub fn line(&self, line_idx: usize) -> RopeSlice<'_> {
305        self.content.line(line_idx)
306    }
307
308    pub(crate) fn tokenize_line(&self, line_idx: usize) -> Vec<(RopeSlice<'_>, usize, usize)> {
309        let text = self.line(line_idx);
310        let mut tokens = Vec::new();
311        let mut chars = text.chars().enumerate().peekable();
312
313        while let Some(&(start_char, c)) = chars.peek() {
314            if c.is_alphanumeric() || c == '_' {
315                chars.next();
316                while let Some(&(_, next_c)) = chars.peek() {
317                    if next_c.is_alphanumeric() || next_c == '_' {
318                        chars.next();
319                    } else {
320                        break;
321                    }
322                }
323                let end_char = chars.peek().map_or(text.len_chars(), |&(idx, _)| idx);
324                tokens.push((text.slice(start_char..end_char), start_char, end_char));
325            } else if c.is_whitespace() {
326                chars.next();
327                while let Some(&(_, next_c)) = chars.peek() {
328                    if next_c.is_whitespace() {
329                        chars.next();
330                    } else {
331                        break;
332                    }
333                }
334                let end_char = chars.peek().map_or(text.len_chars(), |&(idx, _)| idx);
335                tokens.push((text.slice(start_char..end_char), start_char, end_char));
336            } else {
337                chars.next();
338                let end_char = chars.peek().map_or(text.len_chars(), |&(idx, _)| idx);
339                tokens.push((text.slice(start_char..end_char), start_char, end_char));
340            }
341        }
342        tokens
343    }
344
345    pub fn char_to_line(&self, char_idx: usize) -> usize {
346        self.content.char_to_line(char_idx)
347    }
348
349    pub fn char_slice(&self, start: usize, end: usize) -> RopeSlice<'_> {
350        self.content.slice(start..end)
351    }
352
353    pub fn byte_slice(&self, start: usize, end: usize) -> RopeSlice<'_> {
354        self.content.byte_slice(start..end)
355    }
356
357    pub fn byte_to_line(&self, byte_idx: usize) -> usize {
358        self.content.byte_to_line(byte_idx)
359    }
360
361    pub fn byte_to_char(&self, byte_idx: usize) -> usize {
362        self.content.byte_to_char(byte_idx)
363    }
364
365    pub fn char_col_to_visual(&self, line_idx: usize, char_col: usize) -> usize {
366        let line_start = self.line_to_char(line_idx);
367        let line_len = self.line_len(line_idx);
368        let limit = char_col.min(line_len);
369        let slice = self.char_slice(line_start, line_start + limit);
370        RopeGraphemes::new(&slice)
371            .map(|g| grapheme_width_and_chars_len(g).0)
372            .sum()
373    }
374
375    pub fn visual_to_char_col(&self, line_idx: usize, visual_col: usize) -> usize {
376        let line_start = self.line_to_char(line_idx);
377        let line_len = self.line_len(line_idx);
378        let slice = self.char_slice(line_start, line_start + line_len);
379
380        let mut current_visual = 0;
381        let mut char_col = 0;
382        for g in RopeGraphemes::new(&slice) {
383            let (g_width, g_chars) = grapheme_width_and_chars_len(g);
384            if current_visual + g_width > visual_col {
385                break;
386            }
387            current_visual += g_width;
388            char_col += g_chars;
389        }
390        char_col
391    }
392
393    pub fn next_grapheme_boundary(&self, char_idx: usize) -> usize {
394        if char_idx >= self.len_chars() {
395            return self.len_chars();
396        }
397        let byte_idx = self.content.char_to_byte(char_idx);
398        let mut cursor = GraphemeCursor::new(byte_idx, self.content.len_bytes(), true);
399        let (mut cur_chunk, mut cur_chunk_start, _, _) = self.content.chunk_at_byte(byte_idx);
400
401        loop {
402            match cursor.next_boundary(cur_chunk, cur_chunk_start) {
403                Ok(None) => return self.len_chars(),
404                Ok(Some(b)) => return self.content.byte_to_char(b),
405                Err(GraphemeIncomplete::NextChunk) => {
406                    let next_byte = cur_chunk_start + cur_chunk.len();
407                    let (next_c, next_start, _, _) = self.content.chunk_at_byte(next_byte);
408                    cur_chunk = next_c;
409                    cur_chunk_start = next_start;
410                }
411                Err(GraphemeIncomplete::PreContext(idx)) => {
412                    let (chunk, chunk_byte_idx, _, _) =
413                        self.content.chunk_at_byte(idx.saturating_sub(1));
414                    cursor.provide_context(chunk, chunk_byte_idx);
415                }
416                _ => unreachable!(),
417            }
418        }
419    }
420
421    pub fn prev_grapheme_boundary(&self, char_idx: usize) -> usize {
422        if char_idx == 0 {
423            return 0;
424        }
425
426        let line = self.char_to_line(char_idx);
427        let mut start_search = self.line_to_char(line);
428
429        if char_idx == start_search && line > 0 {
430            start_search = self.line_to_char(line - 1);
431        }
432
433        let mut prev = start_search;
434        let mut cur = start_search;
435
436        while cur < char_idx {
437            prev = cur;
438            cur = self.next_grapheme_boundary(cur);
439            if cur == prev || cur >= char_idx {
440                break; // Break if no progression (safety) or if exceeded
441            }
442        }
443
444        prev
445    }
446
447    pub fn tx(&mut self) {
448        self.current_batch = EditBatch::new();
449    }
450
451    pub fn set_state_before(&mut self, offset: usize, selection: Option<Selection>) {
452        self.current_batch.state_before = Some(EditState { offset, selection });
453    }
454
455    pub fn set_state_after(&mut self, offset: usize, selection: Option<Selection>) {
456        self.current_batch.state_after = Some(EditState { offset, selection });
457    }
458
459    pub fn commit(&mut self) {
460        if !self.current_batch.edits.is_empty() {
461            self.notify_changes(&self.current_batch.edits);
462            self.history.push(self.current_batch.clone());
463            self.current_batch = EditBatch::new();
464        }
465    }
466
467    pub fn insert(&mut self, from: usize, text: &str) {
468        let byte_idx = self.content.char_to_byte(from);
469        let byte_len: usize = text.chars().map(|ch| ch.len_utf8()).sum();
470
471        self.content.insert(from, text);
472
473        if self.applying_history {
474            self.current_batch.edits.push(Edit {
475                start: from,
476                text: text.to_string(),
477                operation: Operation::Insert,
478            });
479        }
480
481        if self.tree.is_some() {
482            self.edit_tree(InputEdit {
483                start_byte: byte_idx,
484                old_end_byte: byte_idx,
485                new_end_byte: byte_idx + byte_len,
486                start_position: Point { row: 0, column: 0 },
487                old_end_position: Point { row: 0, column: 0 },
488                new_end_position: Point { row: 0, column: 0 },
489            });
490        }
491    }
492
493    pub fn remove(&mut self, from: usize, to: usize) {
494        let from_byte = self.content.char_to_byte(from);
495        let to_byte = self.content.char_to_byte(to);
496        let removed_text = self.content.slice(from..to).to_string();
497
498        self.content.remove(from..to);
499
500        if self.applying_history {
501            self.current_batch.edits.push(Edit {
502                start: from,
503                text: removed_text,
504                operation: Operation::Remove,
505            });
506        }
507
508        if self.tree.is_some() {
509            self.edit_tree(InputEdit {
510                start_byte: from_byte,
511                old_end_byte: to_byte,
512                new_end_byte: from_byte,
513                start_position: Point { row: 0, column: 0 },
514                old_end_position: Point { row: 0, column: 0 },
515                new_end_position: Point { row: 0, column: 0 },
516            });
517        }
518    }
519
520    fn edit_tree(&mut self, edit: InputEdit) {
521        if let Some(tree) = self.tree.as_mut() {
522            tree.edit(&edit);
523            self.reparse();
524        }
525    }
526
527    fn reparse(&mut self) {
528        if let Some(parser) = self.parser.as_mut() {
529            let rope = &self.content;
530            self.tree = parser.parse_with_options(
531                &mut |byte, _| {
532                    if byte <= rope.len_bytes() {
533                        let (chunk, start, _, _) = rope.chunk_at_byte(byte);
534                        &chunk.as_bytes()[byte - start..]
535                    } else {
536                        &[]
537                    }
538                },
539                self.tree.as_ref(),
540                None,
541            );
542            self.update_fold_ranges();
543        }
544    }
545
546    pub fn is_highlight(&self) -> bool {
547        self.query.is_some()
548    }
549
550    /// Highlights the interval between `start` and `end` char indices.
551    /// Returns a list of (start byte, end byte, token_name) for highlighting.
552    pub fn highlight_interval<T: Copy>(
553        &self,
554        start: usize,
555        end: usize,
556        theme: &HashMap<String, T>,
557    ) -> Vec<(usize, usize, T)> {
558        if start > end {
559            panic!("Invalid range")
560        }
561
562        let Some(query) = &self.query else {
563            return vec![];
564        };
565        let Some(tree) = &self.tree else {
566            return vec![];
567        };
568
569        let text = self.content.slice(..);
570        let root_node = tree.root_node();
571
572        let mut results = Self::highlight(
573            text,
574            start,
575            end,
576            query,
577            root_node,
578            theme,
579            self.injection_parsers.as_ref(),
580            self.injection_queries.as_ref(),
581        );
582
583        results.sort_by(|a, b| {
584            let len_a = a.1 - a.0;
585            let len_b = b.1 - b.0;
586            match len_b.cmp(&len_a) {
587                std::cmp::Ordering::Equal => b.2.cmp(&a.2),
588                other => other,
589            }
590        });
591
592        results
593            .into_iter()
594            .map(|(start, end, _, value)| (start, end, value))
595            .collect()
596    }
597
598    fn highlight<T: Copy>(
599        text: RopeSlice<'_>,
600        start_byte: usize,
601        end_byte: usize,
602        query: &Query,
603        root_node: Node,
604        theme: &HashMap<String, T>,
605        injection_parsers: Option<&HashMap<String, Rc<RefCell<Parser>>>>,
606        injection_queries: Option<&HashMap<String, Query>>,
607    ) -> Vec<(usize, usize, usize, T)> {
608        let mut cursor = QueryCursor::new();
609        cursor.set_byte_range(start_byte..end_byte);
610
611        let mut matches = cursor.matches(query, root_node, RopeProvider(text));
612
613        let mut results = Vec::new();
614        let capture_names = query.capture_names();
615
616        while let Some(m) = matches.next() {
617            for capture in m.captures {
618                let name = capture_names[capture.index as usize];
619                if let Some(value) = theme.get(name) {
620                    results.push((
621                        capture.node.start_byte(),
622                        capture.node.end_byte(),
623                        capture.index as usize,
624                        *value,
625                    ));
626                } else if let Some(lang) = name.strip_prefix("injection.content.") {
627                    let Some(injection_parsers) = injection_parsers else {
628                        continue;
629                    };
630                    let Some(injection_queries) = injection_queries else {
631                        continue;
632                    };
633                    let Some(parser) = injection_parsers.get(lang) else {
634                        continue;
635                    };
636                    let Some(injection_query) = injection_queries.get(lang) else {
637                        continue;
638                    };
639
640                    let start = capture.node.start_byte();
641                    let end = capture.node.end_byte();
642                    let slice = text.byte_slice(start..end);
643
644                    let mut parser = parser.borrow_mut();
645                    let Some(inj_tree) = parser.parse(slice.to_string(), None) else {
646                        continue;
647                    };
648
649                    let injection_results = Self::highlight(
650                        slice,
651                        0,
652                        end - start,
653                        injection_query,
654                        inj_tree.root_node(),
655                        theme,
656                        injection_parsers.into(),
657                        injection_queries.into(),
658                    );
659
660                    for (s, e, i, v) in injection_results {
661                        results.push((s + start, e + start, i, v));
662                    }
663                }
664            }
665        }
666
667        results
668    }
669
670    pub fn undo(&mut self) -> Option<EditBatch> {
671        let batch = self.history.undo()?;
672        self.applying_history = false;
673
674        for edit in batch.edits.iter().rev() {
675            match edit.operation {
676                Operation::Insert => {
677                    self.remove(edit.start, edit.start + edit.text.chars().count());
678                }
679                Operation::Remove => {
680                    self.insert(edit.start, &edit.text);
681                }
682            }
683        }
684
685        self.applying_history = true;
686        Some(batch)
687    }
688
689    pub fn redo(&mut self) -> Option<EditBatch> {
690        let batch = self.history.redo()?;
691        self.applying_history = false;
692
693        for edit in &batch.edits {
694            match edit.operation {
695                Operation::Insert => {
696                    self.insert(edit.start, &edit.text);
697                }
698                Operation::Remove => {
699                    self.remove(edit.start, edit.start + edit.text.chars().count());
700                }
701            }
702        }
703
704        self.applying_history = true;
705        Some(batch)
706    }
707
708    pub fn word_boundaries(&self, pos: usize) -> (usize, usize) {
709        let len = self.content.len_chars();
710        if pos >= len {
711            return (pos, pos);
712        }
713
714        let is_word_char = |c: char| c.is_alphanumeric() || c == '_';
715
716        let mut start = pos;
717        while start > 0 {
718            let c = self.content.char(start - 1);
719            if !is_word_char(c) {
720                break;
721            }
722            start -= 1;
723        }
724
725        let mut end = pos;
726        while end < len {
727            let c = self.content.char(end);
728            if !is_word_char(c) {
729                break;
730            }
731            end += 1;
732        }
733
734        (start, end)
735    }
736
737    pub fn line_boundaries(&self, pos: usize) -> (usize, usize) {
738        let total_chars = self.content.len_chars();
739        if pos >= total_chars {
740            return (pos, pos);
741        }
742
743        let line = self.content.char_to_line(pos);
744        let start = self.content.line_to_char(line);
745        let end = start + self.content.line(line).len_chars();
746
747        (start, end)
748    }
749
750    pub fn indent(&self) -> String {
751        indent(&self.lang)
752    }
753
754    pub fn comment(&self) -> String {
755        lang_comment(&self.lang).to_string()
756    }
757
758    pub fn indentation_level(&self, line: usize, col: usize) -> usize {
759        if self.lang == "unknown" || self.lang.is_empty() {
760            return 0;
761        }
762        let line_str = self.line(line);
763        count_indent_units(line_str, &self.indent(), Some(col))
764    }
765
766    pub fn is_only_indentation_before(&self, r: usize, c: usize) -> bool {
767        if self.lang == "unknown" || self.lang.is_empty() {
768            return false;
769        }
770        if r >= self.len_lines() || c == 0 {
771            return false;
772        }
773
774        let line = self.line(r);
775        let indent_unit = self.indent();
776
777        if indent_unit.is_empty() {
778            return line.chars().take(c).all(|ch| ch.is_whitespace());
779        }
780
781        let count_units = count_indent_units(line, &indent_unit, Some(c));
782        let only_indent = count_units * indent_unit.chars().count() >= c;
783        only_indent
784    }
785
786    pub fn find_indent_at_line_start(&self, line_idx: usize) -> Option<usize> {
787        if line_idx >= self.len_lines() {
788            return None;
789        }
790
791        let line = self.line(line_idx);
792        let indent_unit = self.indent();
793        if indent_unit.is_empty() {
794            return None;
795        }
796
797        let count_units = count_indent_units(line, &indent_unit, None);
798        let col = count_units * indent_unit.chars().count();
799        if col > 0 { Some(col) } else { None }
800    }
801
802    /// Paste text with **indentation awareness**.
803    ///
804    /// 1. Determine the indentation level at the cursor (`base_level`).
805    /// 2. The first line of the pasted block is inserted at the cursor level (trimmed).
806    /// 3. Subsequent lines adjust their indentation **relative to the previous non-empty line in the pasted block**:
807    ///    - Compute `diff` = change in indentation from the previous non-empty line in the source block (clamped ±1).
808    ///    - Apply `diff` to `prev_nonempty_level` to calculate the new insertion level.
809    /// 4. Empty lines are inserted as-is and do not affect subsequent indentation.
810    ///
811    /// This ensures that pasted blocks keep their relative structure while aligning to the cursor.
812
813    /// Inserts `text` with indentation-awareness at `offset`.
814    /// Returns number of characters inserted.
815    pub fn smart_paste(&mut self, offset: usize, text: &str) -> usize {
816        let (row, col) = self.point(offset);
817        let base_level = self.indentation_level(row, col);
818        let indent_unit = self.indent();
819
820        if indent_unit.is_empty() {
821            self.insert(offset, text);
822            return text.chars().count();
823        }
824
825        let lines: Vec<&str> = text.lines().collect();
826        if lines.is_empty() {
827            return 0;
828        }
829
830        // Compute indentation levels of all lines in the source block
831        let mut line_levels = Vec::with_capacity(lines.len());
832        for line in &lines {
833            let mut lvl = 0;
834            let mut rest = *line;
835            while rest.starts_with(&indent_unit) {
836                lvl += 1;
837                rest = &rest[indent_unit.len()..];
838            }
839            line_levels.push(lvl);
840        }
841
842        let mut result = Vec::with_capacity(lines.len());
843
844        let first_line_trimmed = lines[0].trim_start();
845        result.push(first_line_trimmed.to_string());
846
847        let mut prev_nonempty_level = base_level;
848        let mut prev_line_level_in_block = line_levels[0];
849
850        for i in 1..lines.len() {
851            let line = lines[i];
852
853            if line.trim().is_empty() {
854                result.push(line.to_string());
855                continue;
856            }
857
858            // diff relative to previous non-empty line in the source block
859            let diff = (line_levels[i] as isize - prev_line_level_in_block as isize).clamp(-1, 1);
860            let new_level = (prev_nonempty_level as isize + diff).max(0) as usize;
861            let indents = indent_unit.repeat(new_level);
862            let result_line = format!("{}{}", indents, line.trim_start());
863            result.push(result_line);
864
865            // update levels only for non-empty line
866            prev_nonempty_level = new_level;
867            prev_line_level_in_block = line_levels[i];
868        }
869
870        let to_insert = result.join("\n");
871        self.insert(offset, &to_insert);
872        to_insert.chars().count()
873    }
874
875    /// Set the change callback function for handling document changes
876    pub fn set_change_callback(
877        &mut self,
878        callback: Box<dyn Fn(Vec<(usize, usize, usize, usize, String)>)>,
879    ) {
880        self.change_callback = Some(callback);
881    }
882
883    /// Notify about document changes
884    fn notify_changes(&self, edits: &[Edit]) {
885        if let Some(callback) = &self.change_callback {
886            let mut changes = Vec::new();
887
888            for edit in edits {
889                match edit.operation {
890                    Operation::Insert => {
891                        let (start_row, start_col) = self.point(edit.start);
892                        changes.push((
893                            start_row,
894                            start_col,
895                            start_row,
896                            start_col,
897                            edit.text.clone(),
898                        ));
899                    }
900                    Operation::Remove => {
901                        let (start_row, start_col) = self.point(edit.start);
902                        let (end_row, end_col) =
903                            calculate_end_position(start_row, start_col, &edit.text);
904                        changes.push((start_row, start_col, end_row, end_col, String::new()));
905                    }
906                }
907            }
908
909            if !changes.is_empty() {
910                callback(changes);
911            }
912        }
913    }
914}
915
916/// An iterator over byte slices of Rope chunks.
917/// This is used to feed `tree-sitter` without allocating a full `String`.
918pub struct ChunksBytes<'a> {
919    chunks: ropey::iter::Chunks<'a>,
920}
921
922impl<'a> Iterator for ChunksBytes<'a> {
923    type Item = &'a [u8];
924
925    /// Returns the next chunk as a byte slice.
926    /// Internally converts a `&str` to a `&[u8]` without allocation.
927    #[inline]
928    fn next(&mut self) -> Option<Self::Item> {
929        self.chunks.next().map(str::as_bytes)
930    }
931}
932
933/// A lightweight wrapper around a `RopeSlice`
934/// that implements `tree_sitter::TextProvider`.
935/// This allows using `tree-sitter`'s `QueryCursor::matches`
936/// directly on a `Rope` without converting it to a `String`.
937pub struct RopeProvider<'a>(pub RopeSlice<'a>);
938
939impl<'a> tree_sitter::TextProvider<&'a [u8]> for RopeProvider<'a> {
940    type I = ChunksBytes<'a>;
941
942    /// Provides an iterator over chunks of text corresponding to the given node.
943    /// This avoids allocation by working directly with Rope slices.
944    #[inline]
945    fn text(&mut self, node: tree_sitter::Node) -> Self::I {
946        let fragment = self.0.byte_slice(node.start_byte()..node.end_byte());
947        ChunksBytes {
948            chunks: fragment.chunks(),
949        }
950    }
951}
952
953/// An implementation of a graphemes iterator, for iterating over the graphemes of a RopeSlice.
954pub struct RopeGraphemes<'a> {
955    text: ropey::RopeSlice<'a>,
956    chunks: ropey::iter::Chunks<'a>,
957    cur_chunk: &'a str,
958    cur_chunk_start: usize,
959    cursor: GraphemeCursor,
960}
961
962impl<'a> RopeGraphemes<'a> {
963    pub fn new<'b>(slice: &RopeSlice<'b>) -> RopeGraphemes<'b> {
964        let mut chunks = slice.chunks();
965        let first_chunk = chunks.next().unwrap_or("");
966        RopeGraphemes {
967            text: *slice,
968            chunks: chunks,
969            cur_chunk: first_chunk,
970            cur_chunk_start: 0,
971            cursor: GraphemeCursor::new(0, slice.len_bytes(), true),
972        }
973    }
974}
975
976impl<'a> Iterator for RopeGraphemes<'a> {
977    type Item = RopeSlice<'a>;
978
979    fn next(&mut self) -> Option<RopeSlice<'a>> {
980        let a = self.cursor.cur_cursor();
981        let b;
982        loop {
983            match self
984                .cursor
985                .next_boundary(self.cur_chunk, self.cur_chunk_start)
986            {
987                Ok(None) => {
988                    return None;
989                }
990                Ok(Some(n)) => {
991                    b = n;
992                    break;
993                }
994                Err(GraphemeIncomplete::NextChunk) => {
995                    self.cur_chunk_start += self.cur_chunk.len();
996                    self.cur_chunk = self.chunks.next().unwrap_or("");
997                }
998                Err(GraphemeIncomplete::PreContext(idx)) => {
999                    let (chunk, byte_idx, _, _) = self.text.chunk_at_byte(idx.saturating_sub(1));
1000                    self.cursor.provide_context(chunk, byte_idx);
1001                }
1002                _ => unreachable!(),
1003            }
1004        }
1005
1006        if a < self.cur_chunk_start {
1007            let a_char = self.text.byte_to_char(a);
1008            let b_char = self.text.byte_to_char(b);
1009
1010            Some(self.text.slice(a_char..b_char))
1011        } else {
1012            let a2 = a - self.cur_chunk_start;
1013            let b2 = b - self.cur_chunk_start;
1014            Some((&self.cur_chunk[a2..b2]).into())
1015        }
1016    }
1017}
1018
1019pub fn grapheme_width_and_chars_len(g: RopeSlice) -> (usize, usize) {
1020    if let Some(g_str) = g.as_str() {
1021        (UnicodeWidthStr::width(g_str), g_str.chars().count())
1022    } else {
1023        let g_string = g.to_string();
1024        let g_str = g_string.as_str();
1025        (UnicodeWidthStr::width(g_str), g_str.chars().count())
1026    }
1027}
1028
1029pub fn grapheme_width_and_bytes_len(g: RopeSlice) -> (usize, usize) {
1030    if let Some(g_str) = g.as_str() {
1031        (UnicodeWidthStr::width(g_str), g_str.len())
1032    } else {
1033        let g_string = g.to_string();
1034        let g_str = g_string.as_str();
1035        (UnicodeWidthStr::width(g_str), g_str.len())
1036    }
1037}
1038
1039pub fn grapheme_width(g: RopeSlice) -> usize {
1040    if let Some(s) = g.as_str() {
1041        UnicodeWidthStr::width(s)
1042    } else {
1043        let s = g.to_string();
1044        UnicodeWidthStr::width(s.as_str())
1045    }
1046}
1047
1048#[cfg(test)]
1049mod tests {
1050    use super::*;
1051
1052    #[test]
1053    fn test_insert() {
1054        let mut code = Code::new("", "", None).unwrap();
1055        code.insert(0, "Hello ");
1056        code.insert(6, "World");
1057        assert_eq!(code.content.to_string(), "Hello World");
1058    }
1059
1060    #[test]
1061    fn test_remove() {
1062        let mut code = Code::new("Hello World", "", None).unwrap();
1063        code.remove(5, 11);
1064        assert_eq!(code.content.to_string(), "Hello");
1065    }
1066
1067    #[test]
1068    fn test_undo() {
1069        let mut code = Code::new("", "", None).unwrap();
1070
1071        code.tx();
1072        code.insert(0, "Hello ");
1073        code.commit();
1074
1075        code.tx();
1076        code.insert(6, "World");
1077        code.commit();
1078
1079        code.undo();
1080        assert_eq!(code.content.to_string(), "Hello ");
1081
1082        code.undo();
1083        assert_eq!(code.content.to_string(), "");
1084    }
1085
1086    #[test]
1087    fn test_redo() {
1088        let mut code = Code::new("", "", None).unwrap();
1089
1090        code.tx();
1091        code.insert(0, "Hello");
1092        code.commit();
1093
1094        code.undo();
1095        assert_eq!(code.content.to_string(), "");
1096
1097        code.redo();
1098        assert_eq!(code.content.to_string(), "Hello");
1099    }
1100
1101    #[test]
1102    fn test_indentation_level0() {
1103        let mut code = Code::new("", "unknown", None).unwrap();
1104        code.insert(0, "    hello world");
1105        assert_eq!(code.indentation_level(0, 10), 0);
1106    }
1107
1108    #[test]
1109    fn test_indentation_level() {
1110        let mut code = Code::new("", "python", None).unwrap();
1111        code.insert(0, "    print('Hello, World!')");
1112        assert_eq!(code.indentation_level(0, 10), 1);
1113    }
1114
1115    #[test]
1116    fn test_indentation_level2() {
1117        let mut code = Code::new("", "python", None).unwrap();
1118        code.insert(0, "        print('Hello, World!')");
1119        assert_eq!(code.indentation_level(0, 10), 2);
1120    }
1121
1122    #[test]
1123    fn test_is_only_indentation_before() {
1124        let mut code = Code::new("", "python", None).unwrap();
1125        code.insert(0, "    print('Hello, World!')");
1126        assert_eq!(code.is_only_indentation_before(0, 4), true);
1127        assert_eq!(code.is_only_indentation_before(0, 10), false);
1128    }
1129
1130    #[test]
1131    fn test_is_only_indentation_before2() {
1132        let mut code = Code::new("", "", None).unwrap();
1133        code.insert(0, "    Hello, World");
1134        assert_eq!(code.is_only_indentation_before(0, 4), false);
1135        assert_eq!(code.is_only_indentation_before(0, 10), false);
1136    }
1137
1138    #[test]
1139    fn test_smart_paste_1() {
1140        let initial = "fn foo() {\n    let x = 1;\n    \n}";
1141        let mut code = Code::new(initial, "rust", None).unwrap();
1142
1143        let offset = 30;
1144        let paste = "if start == end && start == self.code.len() {\n    return;\n}";
1145        code.smart_paste(offset, paste);
1146
1147        let expected = "fn foo() {\n    let x = 1;\n    if start == end && start == self.code.len() {\n        return;\n    }\n}";
1148        assert_eq!(code.get_content(), expected);
1149    }
1150
1151    #[test]
1152    fn test_smart_paste_2() {
1153        let initial = "fn foo() {\n    let x = 1;\n    \n}";
1154        let mut code = Code::new(initial, "rust", None).unwrap();
1155
1156        let offset = 30;
1157        let paste = "    if start == end && start == self.code.len() {\n        return;\n    }";
1158        code.smart_paste(offset, paste);
1159
1160        let expected = "fn foo() {\n    let x = 1;\n    if start == end && start == self.code.len() {\n        return;\n    }\n}";
1161        assert_eq!(code.get_content(), expected);
1162    }
1163}