Skip to main content

text_editing/
lib.rs

1#![deny(missing_docs)]
2/*!
3Utilities to simplify text editing when implementing text editors.
4**/
5
6use std::{
7    convert::Infallible,
8    fmt::{Display, Formatter},
9    ops::Range,
10    str::FromStr,
11};
12
13/// The text line represents editable text lines.
14#[derive(Clone, Default)]
15pub struct TextLine {
16    text: String,
17    indices: Vec<usize>,
18}
19
20impl TextLine {
21    /// Creates a new empty text line.
22    ///
23    /// # Examples
24    ///
25    /// ```
26    /// use text_editing::TextLine;
27    ///
28    /// let line = TextLine::new();
29    /// assert!(line.is_empty());
30    /// ```
31    #[must_use]
32    pub fn new() -> Self {
33        Self::default()
34    }
35
36    fn enable_indices(&mut self) {
37        let mut index = 0;
38        for c in self.text.chars() {
39            index += c.len_utf8() - 1;
40            self.indices.push(index);
41        }
42    }
43
44    fn refresh_indices(&mut self) {
45        if !self.text.is_ascii() {
46            self.enable_indices();
47        }
48    }
49
50    /// Inserts an entry into the index cache and shifts the suffix by `extra`,
51    /// the extra bytes the new char contributes. `pos` is the char index.
52    fn index_insert(&mut self, pos: usize, extra: usize) {
53        let base = if pos > 0 { self.indices[pos - 1] } else { 0 };
54        self.indices.insert(pos, base + extra);
55        if extra > 0 {
56            for v in &mut self.indices[pos + 1..] {
57                *v += extra;
58            }
59        }
60    }
61
62    /// Removes the entry at `pos` from the index cache and shifts the suffix
63    /// back by `extra`, the extra bytes the removed char contributed.
64    fn index_remove(&mut self, pos: usize, extra: usize) {
65        self.indices.remove(pos);
66        if extra > 0 {
67            for v in &mut self.indices[pos..] {
68                *v -= extra;
69            }
70        }
71    }
72
73    /// Creates a text line from a `String`.
74    ///
75    /// # Examples
76    ///
77    /// ```
78    /// use text_editing::TextLine;
79    ///
80    /// let line = TextLine::from_string("Hello, world!".into());
81    /// assert_eq!(line.as_str(), "Hello, world!");
82    /// ```
83    #[must_use]
84    pub fn from_string(text: String) -> Self {
85        let mut result = Self {
86            text,
87            ..Self::default()
88        };
89        result.refresh_indices();
90        result
91    }
92
93    /// Clears the text line, removing all content.
94    ///
95    /// # Examples
96    ///
97    /// ```
98    /// use text_editing::TextLine;
99    ///
100    /// let mut line = TextLine::from_string("Hello, world!".into());
101    /// line.clear();
102    /// assert!(line.is_empty());
103    /// ```
104    pub fn clear(&mut self) {
105        self.text.clear();
106        self.indices.clear();
107    }
108
109    /// Checks if the line is empty.
110    ///
111    /// # Examples
112    ///
113    /// ```
114    /// use text_editing::TextLine;
115    ///
116    /// let line = TextLine::new();
117    /// assert!(line.is_empty());
118    /// ```
119    #[must_use]
120    pub const fn is_empty(&self) -> bool {
121        self.text.is_empty()
122    }
123
124    /// Returns the number of chars in the text line.
125    ///
126    /// # Examples
127    ///
128    /// ```
129    /// use text_editing::TextLine;
130    ///
131    /// let line = TextLine::from_string("Hello, world!".into());
132    /// assert_eq!(line.len(), 13);
133    /// ```
134    #[must_use]
135    pub const fn len(&self) -> usize {
136        if self.indices.is_empty() {
137            self.text.len()
138        } else {
139            self.indices.len()
140        }
141    }
142
143    /// Returns the text of the text line as a `str` reference.
144    ///
145    /// # Examples
146    ///
147    /// ```
148    /// use text_editing::TextLine;
149    ///
150    /// let line = TextLine::from_string("Hello, world!".into());
151    /// assert_eq!(line.as_str(), "Hello, world!");
152    /// ```
153    #[must_use]
154    pub fn as_str(&self) -> &str {
155        &self.text
156    }
157
158    /// Converts the character index to the string index.
159    ///
160    /// # Examples
161    ///
162    /// ```
163    /// use text_editing::TextLine;
164    ///
165    /// let line = TextLine::from_string("Hello, world!".into());
166    /// assert_eq!(line.string_index(7), 7);
167    /// ```
168    #[must_use]
169    pub fn string_index(&self, index: usize) -> usize {
170        if !self.indices.is_empty() && index > 0 {
171            self.indices[index - 1] + index
172        } else {
173            index
174        }
175    }
176
177    /// Converts the string index to the character index. The inverse of
178    /// [`string_index`](Self::string_index).
179    ///
180    /// # Panics
181    ///
182    /// Panics if `byte_index` is not on a char boundary or exceeds the text length.
183    ///
184    /// # Examples
185    ///
186    /// ```
187    /// use text_editing::TextLine;
188    ///
189    /// let line = TextLine::from("a🌍b");
190    /// assert_eq!(line.char_index(5), 2);
191    /// assert_eq!(line.char_index(line.as_str().len()), 3);
192    /// ```
193    #[must_use]
194    pub fn char_index(&self, byte_index: usize) -> usize {
195        assert!(
196            self.text.is_char_boundary(byte_index),
197            "byte index {byte_index} is not a char boundary",
198        );
199        if self.indices.is_empty() {
200            return byte_index;
201        }
202        let mut low = 0;
203        let mut high = self.len();
204        while low < high {
205            let middle = low + (high - low) / 2;
206            if self.string_index(middle) < byte_index {
207                low = middle + 1;
208            } else {
209                high = middle;
210            }
211        }
212        low
213    }
214
215    /// Returns the text between two char positions.
216    ///
217    /// # Panics
218    ///
219    /// Panics if the range is out of bounds or reversed.
220    ///
221    /// # Examples
222    ///
223    /// ```
224    /// use text_editing::TextLine;
225    ///
226    /// let line = TextLine::from("a🌍bπŸ¦€c");
227    /// assert_eq!(line.slice(1..4), "🌍bπŸ¦€");
228    /// ```
229    #[must_use]
230    pub fn slice(&self, range: Range<usize>) -> &str {
231        &self.text[self.string_index(range.start)..self.string_index(range.end)]
232    }
233
234    /// Returns the char at the specified position, or [`None`] if out of bounds.
235    ///
236    /// # Examples
237    ///
238    /// ```
239    /// use text_editing::TextLine;
240    ///
241    /// let line = TextLine::from_string("Hello, world!".into());
242    /// assert_eq!(line.char_at_checked(7), Some('w'));
243    /// assert_eq!(line.char_at_checked(99), None);
244    /// ```
245    #[must_use]
246    pub fn char_at_checked(&self, at: usize) -> Option<char> {
247        if at >= self.len() {
248            return None;
249        }
250        self.text[self.string_index(at)..].chars().next()
251    }
252
253    /// Returns the char at the specified position.
254    ///
255    /// # Panics
256    ///
257    /// Panics if the position is out of bounds. Use [`char_at_checked`](Self::char_at_checked)
258    /// for a fallible variant.
259    ///
260    /// # Examples
261    ///
262    /// ```
263    /// use text_editing::TextLine;
264    ///
265    /// let line = TextLine::from_string("Hello, world!".into());
266    /// assert_eq!(line.char_at(7), 'w');
267    /// ```
268    #[must_use]
269    pub fn char_at(&self, at: usize) -> char {
270        self.char_at_checked(at).unwrap()
271    }
272
273    /// Inserts a new char into the text line.
274    ///
275    /// # Panics
276    ///
277    /// Panics if `index` is greater than the number of chars.
278    ///
279    /// # Examples
280    ///
281    /// ```
282    /// use text_editing::TextLine;
283    ///
284    /// let mut line = TextLine::from_string("Hello, orld!".into());
285    /// line.insert(7, 'w');
286    /// assert_eq!(line.as_str(), "Hello, world!");
287    /// ```
288    pub fn insert(&mut self, index: usize, c: char) {
289        self.text.insert(self.string_index(index), c);
290        let extra = c.len_utf8() - 1;
291        if !self.indices.is_empty() {
292            self.index_insert(index, extra);
293        } else if extra > 0 {
294            self.enable_indices();
295        }
296    }
297
298    /// Removes a char from the text line and returns it.
299    ///
300    /// # Panics
301    ///
302    /// Panics if `index` is out of bounds.
303    ///
304    /// # Examples
305    ///
306    /// ```
307    /// use text_editing::TextLine;
308    ///
309    /// let mut line = TextLine::from_string("Hello, world!".into());
310    /// assert_eq!(line.remove(7), 'w');
311    /// assert_eq!(line.as_str(), "Hello, orld!");
312    /// ```
313    pub fn remove(&mut self, index: usize) -> char {
314        let result = self.text.remove(self.string_index(index));
315        if !self.indices.is_empty() {
316            self.index_remove(index, result.len_utf8() - 1);
317        }
318        result
319    }
320
321    /// Removes the specified range from the text line.
322    ///
323    /// # Panics
324    ///
325    /// Panics if the range is out of bounds.
326    ///
327    /// # Examples
328    ///
329    /// ```
330    /// use text_editing::TextLine;
331    ///
332    /// let mut line = TextLine::from_string("Hello, world!".into());
333    /// line.remove_range(7..12);
334    /// assert_eq!(line.as_str(), "Hello, !");
335    /// ```
336    pub fn remove_range(&mut self, range: Range<usize>) {
337        self.text.replace_range(
338            self.string_index(range.start)..self.string_index(range.end),
339            "",
340        );
341        if !self.indices.is_empty() && !range.is_empty() {
342            let before = if range.start > 0 {
343                self.indices[range.start - 1]
344            } else {
345                0
346            };
347            let total_extra = self.indices[range.end - 1] - before;
348            let start = range.start;
349            self.indices.drain(range);
350            if total_extra > 0 {
351                for v in &mut self.indices[start..] {
352                    *v -= total_extra;
353                }
354            }
355        }
356    }
357
358    /// Replaces the specified char range with `text`.
359    ///
360    /// # Panics
361    ///
362    /// Panics if the range is out of bounds.
363    ///
364    /// # Examples
365    ///
366    /// ```
367    /// use text_editing::TextLine;
368    ///
369    /// let mut line = TextLine::from("Hello, world!");
370    /// line.replace_range(7..12, "🌍");
371    /// assert_eq!(line.as_str(), "Hello, 🌍!");
372    /// ```
373    pub fn replace_range(&mut self, range: Range<usize>, text: &str) {
374        let mut cursor = range.start;
375        self.remove_range(range);
376        self.insert_str(&mut cursor, text);
377    }
378
379    /// Splits a text line into two.
380    ///
381    /// # Examples
382    ///
383    /// ```
384    /// use text_editing::TextLine;
385    ///
386    /// let mut line = TextLine::from_string("Hello, world!".into());
387    /// let second_half = line.split(7);
388    /// assert_eq!(line.as_str(), "Hello, ");
389    /// assert_eq!(second_half.as_str(), "world!");
390    /// ```
391    #[must_use]
392    pub fn split(&mut self, index: usize) -> Self {
393        let text = self.text.split_off(self.string_index(index));
394        let result_indices = if self.indices.is_empty() {
395            Vec::new()
396        } else {
397            let before = if index > 0 {
398                self.indices[index - 1]
399            } else {
400                0
401            };
402            let tail: Vec<usize> = self.indices[index..].iter().map(|&v| v - before).collect();
403            self.indices.truncate(index);
404            tail
405        };
406        Self {
407            text,
408            indices: result_indices,
409        }
410    }
411
412    /// Joins two text lines into one.
413    ///
414    /// # Examples
415    ///
416    /// ```
417    /// use text_editing::TextLine;
418    ///
419    /// let mut line1 = TextLine::from_string("Hello, ".into());
420    /// let line2 = TextLine::from_string("world!".into());
421    /// line1.join(&line2);
422    /// assert_eq!(line1.as_str(), "Hello, world!");
423    /// ```
424    pub fn join(&mut self, other: &Self) {
425        self.text.push_str(&other.text);
426        if !self.indices.is_empty() {
427            let mut running = *self.indices.last().unwrap_or(&0);
428            for c in other.text.chars() {
429                running += c.len_utf8() - 1;
430                self.indices.push(running);
431            }
432        } else if !other.text.is_ascii() {
433            self.enable_indices();
434        }
435    }
436}
437
438impl FromStr for TextLine {
439    type Err = Infallible;
440
441    fn from_str(text: &str) -> Result<Self, Infallible> {
442        Ok(Self::from_string(text.into()))
443    }
444}
445
446impl Display for TextLine {
447    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
448        f.write_str(self.as_str())
449    }
450}
451
452impl From<String> for TextLine {
453    fn from(text: String) -> Self {
454        Self::from_string(text)
455    }
456}
457
458impl From<&str> for TextLine {
459    fn from(text: &str) -> Self {
460        Self::from_string(text.into())
461    }
462}
463
464impl From<TextLine> for String {
465    fn from(text_line: TextLine) -> Self {
466        text_line.text
467    }
468}
469
470mod cursor;
471mod editing;
472mod selection;
473
474pub use cursor::Direction;
475
476#[cfg(test)]
477mod tests {
478    use super::TextLine;
479
480    /// Byte offset of each char boundary, reconstructed from the raw text.
481    fn expected_offsets(line: &TextLine) -> Vec<usize> {
482        let mut offsets = vec![0];
483        let mut last = 0;
484        for c in line.as_str().chars() {
485            last += c.len_utf8();
486            offsets.push(last);
487        }
488        offsets
489    }
490
491    /// Asserts the incremental index cache matches a from-scratch rebuild.
492    fn check(line: &TextLine) {
493        let expected = expected_offsets(line);
494        assert_eq!(line.len() + 1, expected.len());
495        for (i, &offset) in expected.iter().enumerate() {
496            assert_eq!(
497                line.string_index(i),
498                offset,
499                "string_index({i}) wrong for {:?}",
500                line.as_str(),
501            );
502        }
503        for (i, c) in line.as_str().chars().enumerate() {
504            assert_eq!(
505                line.char_at(i),
506                c,
507                "char_at({i}) wrong for {:?}",
508                line.as_str(),
509            );
510        }
511    }
512
513    #[test]
514    fn ascii_stays_cacheless() {
515        let mut line = TextLine::from_string("hello".into());
516        line.insert(5, ' ');
517        line.insert(6, 'w');
518        check(&line);
519        line.remove(0);
520        check(&line);
521    }
522
523    #[test]
524    fn insert_non_ascii_activates() {
525        let mut line = TextLine::from_string("ab".into());
526        line.insert(1, '🌍');
527        check(&line);
528        assert_eq!(line.as_str(), "a🌍b");
529    }
530
531    #[test]
532    fn insert_ascii_into_non_ascii() {
533        let mut line = TextLine::from_string("a🌍b".into());
534        check(&line);
535        line.insert(2, 'X');
536        check(&line);
537        line.insert(0, 'Y');
538        check(&line);
539        line.insert(line.len(), 'Z');
540        check(&line);
541        assert_eq!(line.as_str(), "Ya🌍XbZ");
542    }
543
544    #[test]
545    fn remove_non_ascii() {
546        let mut line = TextLine::from_string("a🌍b".into());
547        assert_eq!(line.remove(1), '🌍');
548        check(&line);
549        assert_eq!(line.as_str(), "ab");
550    }
551
552    #[test]
553    fn remove_range_spanning_non_ascii() {
554        let mut line = TextLine::from_string("x🌍y🌍z".into());
555        line.remove_range(1..3);
556        check(&line);
557        assert_eq!(line.as_str(), "x🌍z");
558        line.remove_range(0..line.len());
559        check(&line);
560        assert!(line.is_empty());
561    }
562
563    #[test]
564    fn insert_str_non_ascii() {
565        let mut line = TextLine::from_string("a🌍b".into());
566        let mut cursor = 2;
567        line.insert_str(&mut cursor, "xπŸ¦€y");
568        check(&line);
569        assert_eq!(cursor, 5);
570        assert_eq!(line.as_str(), "a🌍xπŸ¦€yb");
571    }
572
573    #[test]
574    fn split_non_ascii() {
575        let mut line = TextLine::from_string("a🌍bπŸ¦€c".into());
576        let second = line.split(3);
577        check(&line);
578        check(&second);
579        assert_eq!(line.as_str(), "a🌍b");
580        assert_eq!(second.as_str(), "πŸ¦€c");
581    }
582
583    #[test]
584    fn join_non_ascii() {
585        let mut line = TextLine::from_string("a🌍".into());
586        line.join(&TextLine::from_string("bπŸ¦€".into()));
587        check(&line);
588        assert_eq!(line.as_str(), "a🌍bπŸ¦€");
589    }
590
591    #[test]
592    fn char_index_inverts_string_index() {
593        for text in ["", "hello", "a🌍bπŸ¦€c", "🌍", "Àâü"] {
594            let line = TextLine::from(text);
595            for position in 0..=line.len() {
596                assert_eq!(line.char_index(line.string_index(position)), position);
597            }
598        }
599    }
600
601    #[test]
602    #[should_panic(expected = "not a char boundary")]
603    fn char_index_rejects_mid_char_offset() {
604        let _ = TextLine::from("a🌍b").char_index(2);
605    }
606
607    #[test]
608    fn slice_matches_chars() {
609        let line = TextLine::from("a🌍bπŸ¦€c");
610        let chars: Vec<char> = line.as_str().chars().collect();
611        for start in 0..=chars.len() {
612            for end in start..=chars.len() {
613                let expected: String = chars[start..end].iter().collect();
614                assert_eq!(line.slice(start..end), expected);
615            }
616        }
617    }
618
619    #[test]
620    fn replace_range_keeps_cache_consistent() {
621        let mut line = TextLine::from("a🌍bπŸ¦€c");
622        line.replace_range(1..4, "xy");
623        check(&line);
624        assert_eq!(line.as_str(), "axyc");
625        line.replace_range(1..3, "πŸŒπŸ¦€πŸŒ");
626        check(&line);
627        assert_eq!(line.as_str(), "aπŸŒπŸ¦€πŸŒc");
628        line.replace_range(0..line.len(), "");
629        check(&line);
630        assert!(line.is_empty());
631        line.replace_range(0..0, "Γ©");
632        check(&line);
633    }
634
635    #[test]
636    fn mixed_mutation_sequence() {
637        let mut line = TextLine::new();
638        for (i, c) in ['h', 'i', '🌍', '!', 'πŸ¦€'].into_iter().enumerate() {
639            line.insert(i, c);
640            check(&line);
641        }
642        assert_eq!(line.remove(2), '🌍');
643        check(&line);
644        assert_eq!(line.as_str(), "hi!πŸ¦€");
645        let mut cursor = line.len();
646        line.insert_str(&mut cursor, "πŸ¦€ end");
647        check(&line);
648        line.remove_range(1..4);
649        check(&line);
650    }
651}