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    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 fn char_to_line(&self, char_idx: usize) -> usize {
309        self.content.char_to_line(char_idx)
310    }
311
312    pub fn char_slice(&self, start: usize, end: usize) -> RopeSlice<'_> {
313        self.content.slice(start..end)
314    }
315
316    pub fn byte_slice(&self, start: usize, end: usize) -> RopeSlice<'_> {
317        self.content.byte_slice(start..end)
318    }
319
320    pub fn byte_to_line(&self, byte_idx: usize) -> usize {
321        self.content.byte_to_line(byte_idx)
322    }
323
324    pub fn byte_to_char(&self, byte_idx: usize) -> usize {
325        self.content.byte_to_char(byte_idx)
326    }
327
328    pub fn char_col_to_visual(&self, line_idx: usize, char_col: usize) -> usize {
329        let line_start = self.line_to_char(line_idx);
330        let line_len = self.line_len(line_idx);
331        let limit = char_col.min(line_len);
332        let slice = self.char_slice(line_start, line_start + limit);
333        RopeGraphemes::new(&slice)
334            .map(|g| grapheme_width_and_chars_len(g).0)
335            .sum()
336    }
337
338    pub fn visual_to_char_col(&self, line_idx: usize, visual_col: usize) -> usize {
339        let line_start = self.line_to_char(line_idx);
340        let line_len = self.line_len(line_idx);
341        let slice = self.char_slice(line_start, line_start + line_len);
342
343        let mut current_visual = 0;
344        let mut char_col = 0;
345        for g in RopeGraphemes::new(&slice) {
346            let (g_width, g_chars) = grapheme_width_and_chars_len(g);
347            if current_visual + g_width > visual_col {
348                break;
349            }
350            current_visual += g_width;
351            char_col += g_chars;
352        }
353        char_col
354    }
355
356    pub fn next_grapheme_boundary(&self, char_idx: usize) -> usize {
357        if char_idx >= self.len_chars() {
358            return self.len_chars();
359        }
360        let byte_idx = self.content.char_to_byte(char_idx);
361        let mut cursor = GraphemeCursor::new(byte_idx, self.content.len_bytes(), true);
362        let (mut cur_chunk, mut cur_chunk_start, _, _) = self.content.chunk_at_byte(byte_idx);
363
364        loop {
365            match cursor.next_boundary(cur_chunk, cur_chunk_start) {
366                Ok(None) => return self.len_chars(),
367                Ok(Some(b)) => return self.content.byte_to_char(b),
368                Err(GraphemeIncomplete::NextChunk) => {
369                    let next_byte = cur_chunk_start + cur_chunk.len();
370                    let (next_c, next_start, _, _) = self.content.chunk_at_byte(next_byte);
371                    cur_chunk = next_c;
372                    cur_chunk_start = next_start;
373                }
374                Err(GraphemeIncomplete::PreContext(idx)) => {
375                    let (chunk, chunk_byte_idx, _, _) =
376                        self.content.chunk_at_byte(idx.saturating_sub(1));
377                    cursor.provide_context(chunk, chunk_byte_idx);
378                }
379                _ => unreachable!(),
380            }
381        }
382    }
383
384    pub fn prev_grapheme_boundary(&self, char_idx: usize) -> usize {
385        if char_idx == 0 {
386            return 0;
387        }
388
389        let line = self.char_to_line(char_idx);
390        let mut start_search = self.line_to_char(line);
391
392        if char_idx == start_search && line > 0 {
393            start_search = self.line_to_char(line - 1);
394        }
395
396        let mut prev = start_search;
397        let mut cur = start_search;
398
399        while cur < char_idx {
400            prev = cur;
401            cur = self.next_grapheme_boundary(cur);
402            if cur == prev || cur >= char_idx {
403                break; // Break if no progression (safety) or if exceeded
404            }
405        }
406
407        prev
408    }
409
410    pub fn tx(&mut self) {
411        self.current_batch = EditBatch::new();
412    }
413
414    pub fn set_state_before(&mut self, offset: usize, selection: Option<Selection>) {
415        self.current_batch.state_before = Some(EditState { offset, selection });
416    }
417
418    pub fn set_state_after(&mut self, offset: usize, selection: Option<Selection>) {
419        self.current_batch.state_after = Some(EditState { offset, selection });
420    }
421
422    pub fn commit(&mut self) {
423        if !self.current_batch.edits.is_empty() {
424            self.notify_changes(&self.current_batch.edits);
425            self.history.push(self.current_batch.clone());
426            self.current_batch = EditBatch::new();
427        }
428    }
429
430    pub fn insert(&mut self, from: usize, text: &str) {
431        let byte_idx = self.content.char_to_byte(from);
432        let byte_len: usize = text.chars().map(|ch| ch.len_utf8()).sum();
433
434        self.content.insert(from, text);
435
436        if self.applying_history {
437            self.current_batch.edits.push(Edit {
438                start: from,
439                text: text.to_string(),
440                operation: Operation::Insert,
441            });
442        }
443
444        if self.tree.is_some() {
445            self.edit_tree(InputEdit {
446                start_byte: byte_idx,
447                old_end_byte: byte_idx,
448                new_end_byte: byte_idx + byte_len,
449                start_position: Point { row: 0, column: 0 },
450                old_end_position: Point { row: 0, column: 0 },
451                new_end_position: Point { row: 0, column: 0 },
452            });
453        }
454    }
455
456    pub fn remove(&mut self, from: usize, to: usize) {
457        let from_byte = self.content.char_to_byte(from);
458        let to_byte = self.content.char_to_byte(to);
459        let removed_text = self.content.slice(from..to).to_string();
460
461        self.content.remove(from..to);
462
463        if self.applying_history {
464            self.current_batch.edits.push(Edit {
465                start: from,
466                text: removed_text,
467                operation: Operation::Remove,
468            });
469        }
470
471        if self.tree.is_some() {
472            self.edit_tree(InputEdit {
473                start_byte: from_byte,
474                old_end_byte: to_byte,
475                new_end_byte: from_byte,
476                start_position: Point { row: 0, column: 0 },
477                old_end_position: Point { row: 0, column: 0 },
478                new_end_position: Point { row: 0, column: 0 },
479            });
480        }
481    }
482
483    fn edit_tree(&mut self, edit: InputEdit) {
484        if let Some(tree) = self.tree.as_mut() {
485            tree.edit(&edit);
486            self.reparse();
487        }
488    }
489
490    fn reparse(&mut self) {
491        if let Some(parser) = self.parser.as_mut() {
492            let rope = &self.content;
493            self.tree = parser.parse_with_options(
494                &mut |byte, _| {
495                    if byte <= rope.len_bytes() {
496                        let (chunk, start, _, _) = rope.chunk_at_byte(byte);
497                        &chunk.as_bytes()[byte - start..]
498                    } else {
499                        &[]
500                    }
501                },
502                self.tree.as_ref(),
503                None,
504            );
505            self.update_fold_ranges();
506        }
507    }
508
509    pub fn is_highlight(&self) -> bool {
510        self.query.is_some()
511    }
512
513    /// Highlights the interval between `start` and `end` char indices.
514    /// Returns a list of (start byte, end byte, token_name) for highlighting.
515    pub fn highlight_interval<T: Copy>(
516        &self,
517        start: usize,
518        end: usize,
519        theme: &HashMap<String, T>,
520    ) -> Vec<(usize, usize, T)> {
521        if start > end {
522            panic!("Invalid range")
523        }
524
525        let Some(query) = &self.query else {
526            return vec![];
527        };
528        let Some(tree) = &self.tree else {
529            return vec![];
530        };
531
532        let text = self.content.slice(..);
533        let root_node = tree.root_node();
534
535        let mut results = Self::highlight(
536            text,
537            start,
538            end,
539            query,
540            root_node,
541            theme,
542            self.injection_parsers.as_ref(),
543            self.injection_queries.as_ref(),
544        );
545
546        results.sort_by(|a, b| {
547            let len_a = a.1 - a.0;
548            let len_b = b.1 - b.0;
549            match len_b.cmp(&len_a) {
550                std::cmp::Ordering::Equal => b.2.cmp(&a.2),
551                other => other,
552            }
553        });
554
555        results
556            .into_iter()
557            .map(|(start, end, _, value)| (start, end, value))
558            .collect()
559    }
560
561    fn highlight<T: Copy>(
562        text: RopeSlice<'_>,
563        start_byte: usize,
564        end_byte: usize,
565        query: &Query,
566        root_node: Node,
567        theme: &HashMap<String, T>,
568        injection_parsers: Option<&HashMap<String, Rc<RefCell<Parser>>>>,
569        injection_queries: Option<&HashMap<String, Query>>,
570    ) -> Vec<(usize, usize, usize, T)> {
571        let mut cursor = QueryCursor::new();
572        cursor.set_byte_range(start_byte..end_byte);
573
574        let mut matches = cursor.matches(query, root_node, RopeProvider(text));
575
576        let mut results = Vec::new();
577        let capture_names = query.capture_names();
578
579        while let Some(m) = matches.next() {
580            for capture in m.captures {
581                let name = capture_names[capture.index as usize];
582                if let Some(value) = theme.get(name) {
583                    results.push((
584                        capture.node.start_byte(),
585                        capture.node.end_byte(),
586                        capture.index as usize,
587                        *value,
588                    ));
589                } else if let Some(lang) = name.strip_prefix("injection.content.") {
590                    let Some(injection_parsers) = injection_parsers else {
591                        continue;
592                    };
593                    let Some(injection_queries) = injection_queries else {
594                        continue;
595                    };
596                    let Some(parser) = injection_parsers.get(lang) else {
597                        continue;
598                    };
599                    let Some(injection_query) = injection_queries.get(lang) else {
600                        continue;
601                    };
602
603                    let start = capture.node.start_byte();
604                    let end = capture.node.end_byte();
605                    let slice = text.byte_slice(start..end);
606
607                    let mut parser = parser.borrow_mut();
608                    let Some(inj_tree) = parser.parse(slice.to_string(), None) else {
609                        continue;
610                    };
611
612                    let injection_results = Self::highlight(
613                        slice,
614                        0,
615                        end - start,
616                        injection_query,
617                        inj_tree.root_node(),
618                        theme,
619                        injection_parsers.into(),
620                        injection_queries.into(),
621                    );
622
623                    for (s, e, i, v) in injection_results {
624                        results.push((s + start, e + start, i, v));
625                    }
626                }
627            }
628        }
629
630        results
631    }
632
633    pub fn undo(&mut self) -> Option<EditBatch> {
634        let batch = self.history.undo()?;
635        self.applying_history = false;
636
637        for edit in batch.edits.iter().rev() {
638            match edit.operation {
639                Operation::Insert => {
640                    self.remove(edit.start, edit.start + edit.text.chars().count());
641                }
642                Operation::Remove => {
643                    self.insert(edit.start, &edit.text);
644                }
645            }
646        }
647
648        self.applying_history = true;
649        Some(batch)
650    }
651
652    pub fn redo(&mut self) -> Option<EditBatch> {
653        let batch = self.history.redo()?;
654        self.applying_history = false;
655
656        for edit in &batch.edits {
657            match edit.operation {
658                Operation::Insert => {
659                    self.insert(edit.start, &edit.text);
660                }
661                Operation::Remove => {
662                    self.remove(edit.start, edit.start + edit.text.chars().count());
663                }
664            }
665        }
666
667        self.applying_history = true;
668        Some(batch)
669    }
670
671    pub fn word_boundaries(&self, pos: usize) -> (usize, usize) {
672        let len = self.content.len_chars();
673        if pos >= len {
674            return (pos, pos);
675        }
676
677        let is_word_char = |c: char| c.is_alphanumeric() || c == '_';
678
679        let mut start = pos;
680        while start > 0 {
681            let c = self.content.char(start - 1);
682            if !is_word_char(c) {
683                break;
684            }
685            start -= 1;
686        }
687
688        let mut end = pos;
689        while end < len {
690            let c = self.content.char(end);
691            if !is_word_char(c) {
692                break;
693            }
694            end += 1;
695        }
696
697        (start, end)
698    }
699
700    pub fn line_boundaries(&self, pos: usize) -> (usize, usize) {
701        let total_chars = self.content.len_chars();
702        if pos >= total_chars {
703            return (pos, pos);
704        }
705
706        let line = self.content.char_to_line(pos);
707        let start = self.content.line_to_char(line);
708        let end = start + self.content.line(line).len_chars();
709
710        (start, end)
711    }
712
713    pub fn indent(&self) -> String {
714        indent(&self.lang)
715    }
716
717    pub fn comment(&self) -> String {
718        lang_comment(&self.lang).to_string()
719    }
720
721    pub fn indentation_level(&self, line: usize, col: usize) -> usize {
722        if self.lang == "unknown" || self.lang.is_empty() {
723            return 0;
724        }
725        let line_str = self.line(line);
726        count_indent_units(line_str, &self.indent(), Some(col))
727    }
728
729    pub fn is_only_indentation_before(&self, r: usize, c: usize) -> bool {
730        if self.lang == "unknown" || self.lang.is_empty() {
731            return false;
732        }
733        if r >= self.len_lines() || c == 0 {
734            return false;
735        }
736
737        let line = self.line(r);
738        let indent_unit = self.indent();
739
740        if indent_unit.is_empty() {
741            return line.chars().take(c).all(|ch| ch.is_whitespace());
742        }
743
744        let count_units = count_indent_units(line, &indent_unit, Some(c));
745        let only_indent = count_units * indent_unit.chars().count() >= c;
746        only_indent
747    }
748
749    pub fn find_indent_at_line_start(&self, line_idx: usize) -> Option<usize> {
750        if line_idx >= self.len_lines() {
751            return None;
752        }
753
754        let line = self.line(line_idx);
755        let indent_unit = self.indent();
756        if indent_unit.is_empty() {
757            return None;
758        }
759
760        let count_units = count_indent_units(line, &indent_unit, None);
761        let col = count_units * indent_unit.chars().count();
762        if col > 0 { Some(col) } else { None }
763    }
764
765    /// Paste text with **indentation awareness**.
766    ///
767    /// 1. Determine the indentation level at the cursor (`base_level`).
768    /// 2. The first line of the pasted block is inserted at the cursor level (trimmed).
769    /// 3. Subsequent lines adjust their indentation **relative to the previous non-empty line in the pasted block**:
770    ///    - Compute `diff` = change in indentation from the previous non-empty line in the source block (clamped ±1).
771    ///    - Apply `diff` to `prev_nonempty_level` to calculate the new insertion level.
772    /// 4. Empty lines are inserted as-is and do not affect subsequent indentation.
773    ///
774    /// This ensures that pasted blocks keep their relative structure while aligning to the cursor.
775
776    /// Inserts `text` with indentation-awareness at `offset`.
777    /// Returns number of characters inserted.
778    pub fn smart_paste(&mut self, offset: usize, text: &str) -> usize {
779        let (row, col) = self.point(offset);
780        let base_level = self.indentation_level(row, col);
781        let indent_unit = self.indent();
782
783        if indent_unit.is_empty() {
784            self.insert(offset, text);
785            return text.chars().count();
786        }
787
788        let lines: Vec<&str> = text.lines().collect();
789        if lines.is_empty() {
790            return 0;
791        }
792
793        // Compute indentation levels of all lines in the source block
794        let mut line_levels = Vec::with_capacity(lines.len());
795        for line in &lines {
796            let mut lvl = 0;
797            let mut rest = *line;
798            while rest.starts_with(&indent_unit) {
799                lvl += 1;
800                rest = &rest[indent_unit.len()..];
801            }
802            line_levels.push(lvl);
803        }
804
805        let mut result = Vec::with_capacity(lines.len());
806
807        let first_line_trimmed = lines[0].trim_start();
808        result.push(first_line_trimmed.to_string());
809
810        let mut prev_nonempty_level = base_level;
811        let mut prev_line_level_in_block = line_levels[0];
812
813        for i in 1..lines.len() {
814            let line = lines[i];
815
816            if line.trim().is_empty() {
817                result.push(line.to_string());
818                continue;
819            }
820
821            // diff relative to previous non-empty line in the source block
822            let diff = (line_levels[i] as isize - prev_line_level_in_block as isize).clamp(-1, 1);
823            let new_level = (prev_nonempty_level as isize + diff).max(0) as usize;
824            let indents = indent_unit.repeat(new_level);
825            let result_line = format!("{}{}", indents, line.trim_start());
826            result.push(result_line);
827
828            // update levels only for non-empty line
829            prev_nonempty_level = new_level;
830            prev_line_level_in_block = line_levels[i];
831        }
832
833        let to_insert = result.join("\n");
834        self.insert(offset, &to_insert);
835        to_insert.chars().count()
836    }
837
838    /// Set the change callback function for handling document changes
839    pub fn set_change_callback(
840        &mut self,
841        callback: Box<dyn Fn(Vec<(usize, usize, usize, usize, String)>)>,
842    ) {
843        self.change_callback = Some(callback);
844    }
845
846    /// Notify about document changes
847    fn notify_changes(&self, edits: &[Edit]) {
848        if let Some(callback) = &self.change_callback {
849            let mut changes = Vec::new();
850
851            for edit in edits {
852                match edit.operation {
853                    Operation::Insert => {
854                        let (start_row, start_col) = self.point(edit.start);
855                        changes.push((
856                            start_row,
857                            start_col,
858                            start_row,
859                            start_col,
860                            edit.text.clone(),
861                        ));
862                    }
863                    Operation::Remove => {
864                        let (start_row, start_col) = self.point(edit.start);
865                        let (end_row, end_col) =
866                            calculate_end_position(start_row, start_col, &edit.text);
867                        changes.push((start_row, start_col, end_row, end_col, String::new()));
868                    }
869                }
870            }
871
872            if !changes.is_empty() {
873                callback(changes);
874            }
875        }
876    }
877}
878
879/// An iterator over byte slices of Rope chunks.
880/// This is used to feed `tree-sitter` without allocating a full `String`.
881pub struct ChunksBytes<'a> {
882    chunks: ropey::iter::Chunks<'a>,
883}
884
885impl<'a> Iterator for ChunksBytes<'a> {
886    type Item = &'a [u8];
887
888    /// Returns the next chunk as a byte slice.
889    /// Internally converts a `&str` to a `&[u8]` without allocation.
890    #[inline]
891    fn next(&mut self) -> Option<Self::Item> {
892        self.chunks.next().map(str::as_bytes)
893    }
894}
895
896/// A lightweight wrapper around a `RopeSlice`
897/// that implements `tree_sitter::TextProvider`.
898/// This allows using `tree-sitter`'s `QueryCursor::matches`
899/// directly on a `Rope` without converting it to a `String`.
900pub struct RopeProvider<'a>(pub RopeSlice<'a>);
901
902impl<'a> tree_sitter::TextProvider<&'a [u8]> for RopeProvider<'a> {
903    type I = ChunksBytes<'a>;
904
905    /// Provides an iterator over chunks of text corresponding to the given node.
906    /// This avoids allocation by working directly with Rope slices.
907    #[inline]
908    fn text(&mut self, node: tree_sitter::Node) -> Self::I {
909        let fragment = self.0.byte_slice(node.start_byte()..node.end_byte());
910        ChunksBytes {
911            chunks: fragment.chunks(),
912        }
913    }
914}
915
916/// An implementation of a graphemes iterator, for iterating over the graphemes of a RopeSlice.
917pub struct RopeGraphemes<'a> {
918    text: ropey::RopeSlice<'a>,
919    chunks: ropey::iter::Chunks<'a>,
920    cur_chunk: &'a str,
921    cur_chunk_start: usize,
922    cursor: GraphemeCursor,
923}
924
925impl<'a> RopeGraphemes<'a> {
926    pub fn new<'b>(slice: &RopeSlice<'b>) -> RopeGraphemes<'b> {
927        let mut chunks = slice.chunks();
928        let first_chunk = chunks.next().unwrap_or("");
929        RopeGraphemes {
930            text: *slice,
931            chunks: chunks,
932            cur_chunk: first_chunk,
933            cur_chunk_start: 0,
934            cursor: GraphemeCursor::new(0, slice.len_bytes(), true),
935        }
936    }
937}
938
939impl<'a> Iterator for RopeGraphemes<'a> {
940    type Item = RopeSlice<'a>;
941
942    fn next(&mut self) -> Option<RopeSlice<'a>> {
943        let a = self.cursor.cur_cursor();
944        let b;
945        loop {
946            match self
947                .cursor
948                .next_boundary(self.cur_chunk, self.cur_chunk_start)
949            {
950                Ok(None) => {
951                    return None;
952                }
953                Ok(Some(n)) => {
954                    b = n;
955                    break;
956                }
957                Err(GraphemeIncomplete::NextChunk) => {
958                    self.cur_chunk_start += self.cur_chunk.len();
959                    self.cur_chunk = self.chunks.next().unwrap_or("");
960                }
961                Err(GraphemeIncomplete::PreContext(idx)) => {
962                    let (chunk, byte_idx, _, _) = self.text.chunk_at_byte(idx.saturating_sub(1));
963                    self.cursor.provide_context(chunk, byte_idx);
964                }
965                _ => unreachable!(),
966            }
967        }
968
969        if a < self.cur_chunk_start {
970            let a_char = self.text.byte_to_char(a);
971            let b_char = self.text.byte_to_char(b);
972
973            Some(self.text.slice(a_char..b_char))
974        } else {
975            let a2 = a - self.cur_chunk_start;
976            let b2 = b - self.cur_chunk_start;
977            Some((&self.cur_chunk[a2..b2]).into())
978        }
979    }
980}
981
982pub fn grapheme_width_and_chars_len(g: RopeSlice) -> (usize, usize) {
983    if let Some(g_str) = g.as_str() {
984        (UnicodeWidthStr::width(g_str), g_str.chars().count())
985    } else {
986        let g_string = g.to_string();
987        let g_str = g_string.as_str();
988        (UnicodeWidthStr::width(g_str), g_str.chars().count())
989    }
990}
991
992pub fn grapheme_width_and_bytes_len(g: RopeSlice) -> (usize, usize) {
993    if let Some(g_str) = g.as_str() {
994        (UnicodeWidthStr::width(g_str), g_str.len())
995    } else {
996        let g_string = g.to_string();
997        let g_str = g_string.as_str();
998        (UnicodeWidthStr::width(g_str), g_str.len())
999    }
1000}
1001
1002pub fn grapheme_width(g: RopeSlice) -> usize {
1003    if let Some(s) = g.as_str() {
1004        UnicodeWidthStr::width(s)
1005    } else {
1006        let s = g.to_string();
1007        UnicodeWidthStr::width(s.as_str())
1008    }
1009}
1010
1011#[cfg(test)]
1012mod tests {
1013    use super::*;
1014
1015    #[test]
1016    fn test_insert() {
1017        let mut code = Code::new("", "", None).unwrap();
1018        code.insert(0, "Hello ");
1019        code.insert(6, "World");
1020        assert_eq!(code.content.to_string(), "Hello World");
1021    }
1022
1023    #[test]
1024    fn test_remove() {
1025        let mut code = Code::new("Hello World", "", None).unwrap();
1026        code.remove(5, 11);
1027        assert_eq!(code.content.to_string(), "Hello");
1028    }
1029
1030    #[test]
1031    fn test_undo() {
1032        let mut code = Code::new("", "", None).unwrap();
1033
1034        code.tx();
1035        code.insert(0, "Hello ");
1036        code.commit();
1037
1038        code.tx();
1039        code.insert(6, "World");
1040        code.commit();
1041
1042        code.undo();
1043        assert_eq!(code.content.to_string(), "Hello ");
1044
1045        code.undo();
1046        assert_eq!(code.content.to_string(), "");
1047    }
1048
1049    #[test]
1050    fn test_redo() {
1051        let mut code = Code::new("", "", None).unwrap();
1052
1053        code.tx();
1054        code.insert(0, "Hello");
1055        code.commit();
1056
1057        code.undo();
1058        assert_eq!(code.content.to_string(), "");
1059
1060        code.redo();
1061        assert_eq!(code.content.to_string(), "Hello");
1062    }
1063
1064    #[test]
1065    fn test_indentation_level0() {
1066        let mut code = Code::new("", "unknown", None).unwrap();
1067        code.insert(0, "    hello world");
1068        assert_eq!(code.indentation_level(0, 10), 0);
1069    }
1070
1071    #[test]
1072    fn test_indentation_level() {
1073        let mut code = Code::new("", "python", None).unwrap();
1074        code.insert(0, "    print('Hello, World!')");
1075        assert_eq!(code.indentation_level(0, 10), 1);
1076    }
1077
1078    #[test]
1079    fn test_indentation_level2() {
1080        let mut code = Code::new("", "python", None).unwrap();
1081        code.insert(0, "        print('Hello, World!')");
1082        assert_eq!(code.indentation_level(0, 10), 2);
1083    }
1084
1085    #[test]
1086    fn test_is_only_indentation_before() {
1087        let mut code = Code::new("", "python", None).unwrap();
1088        code.insert(0, "    print('Hello, World!')");
1089        assert_eq!(code.is_only_indentation_before(0, 4), true);
1090        assert_eq!(code.is_only_indentation_before(0, 10), false);
1091    }
1092
1093    #[test]
1094    fn test_is_only_indentation_before2() {
1095        let mut code = Code::new("", "", None).unwrap();
1096        code.insert(0, "    Hello, World");
1097        assert_eq!(code.is_only_indentation_before(0, 4), false);
1098        assert_eq!(code.is_only_indentation_before(0, 10), false);
1099    }
1100
1101    #[test]
1102    fn test_smart_paste_1() {
1103        let initial = "fn foo() {\n    let x = 1;\n    \n}";
1104        let mut code = Code::new(initial, "rust", None).unwrap();
1105
1106        let offset = 30;
1107        let paste = "if start == end && start == self.code.len() {\n    return;\n}";
1108        code.smart_paste(offset, paste);
1109
1110        let expected = "fn foo() {\n    let x = 1;\n    if start == end && start == self.code.len() {\n        return;\n    }\n}";
1111        assert_eq!(code.get_content(), expected);
1112    }
1113
1114    #[test]
1115    fn test_smart_paste_2() {
1116        let initial = "fn foo() {\n    let x = 1;\n    \n}";
1117        let mut code = Code::new(initial, "rust", None).unwrap();
1118
1119        let offset = 30;
1120        let paste = "    if start == end && start == self.code.len() {\n        return;\n    }";
1121        code.smart_paste(offset, paste);
1122
1123        let expected = "fn foo() {\n    let x = 1;\n    if start == end && start == self.code.len() {\n        return;\n    }\n}";
1124        assert_eq!(code.get_content(), expected);
1125    }
1126}