1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
#![deny(missing_docs)]
/*!
Utilities to simplify text editing when implementing text editors.
**/

use std::{
    convert::Infallible,
    fmt::{Display, Formatter},
    ops::Range,
    str::FromStr,
};

/// The text line represents editable text lines.
#[derive(Clone, Default)]
pub struct TextLine {
    text: String,
    indices: Vec<usize>,
}

impl TextLine {
    /// Creates a new empty text line.
    ///
    /// # Examples
    /// ```
    /// use text_editing::TextLine;
    ///
    /// let line = TextLine::new();
    /// assert!(line.is_empty());
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    fn enable_indices(&mut self) {
        let mut index = 0;
        for c in self.text.chars() {
            index += c.len_utf8() - 1;
            self.indices.push(index);
        }
    }

    fn refresh_indices(&mut self) {
        if !self.text.is_ascii() {
            self.enable_indices();
        }
    }

    /// Creates a text line from a `String`.
    ///
    /// # Arguments
    /// * `text` - The string to create the text line from.
    ///
    /// # Examples
    /// ```
    /// use text_editing::TextLine;
    ///
    /// let line = TextLine::from_string("Hello, world!".into());
    /// assert_eq!(line.as_str(), "Hello, world!");
    /// ```
    pub fn from_string(text: String) -> Self {
        let mut result = Self {
            text,
            indices: Vec::new(),
        };
        result.refresh_indices();
        result
    }

    /// Checks if the line is empty.
    ///
    /// # Returns
    /// `true` if the line is empty, `false` otherwise.
    ///
    /// # Examples
    /// ```
    /// use text_editing::TextLine;
    ///
    /// let line = TextLine::new();
    /// assert!(line.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.text.is_empty()
    }

    /// Returns the length of the text line.
    ///
    /// # Returns
    /// The length of the text line.
    ///
    /// # Examples
    /// ```
    /// use text_editing::TextLine;
    ///
    /// let line = TextLine::from_string("Hello, world!".into());
    /// assert_eq!(line.len(), 13);
    /// ```
    pub fn len(&self) -> usize {
        if self.indices.is_empty() {
            self.text.len()
        } else {
            self.indices.len()
        }
    }

    /// Returns the text of the text line as a `str` reference.
    ///
    /// # Returns
    /// A `str` reference to the text of the text line.
    ///
    /// # Examples
    /// ```
    /// use text_editing::TextLine;
    ///
    /// let line = TextLine::from_string("Hello, world!".into());
    /// assert_eq!(line.as_str(), "Hello, world!");
    /// ```
    pub fn as_str(&self) -> &str {
        &self.text
    }

    /// Converts the character index to the string index.
    ///
    /// # Arguments
    /// * `index` - The character index to convert.
    ///
    /// # Returns
    /// The corresponding string index.
    ///
    /// # Examples
    /// ```
    /// use text_editing::TextLine;
    ///
    /// let line = TextLine::from_string("Hello, world!".into());
    /// assert_eq!(line.string_index(7), 7);
    /// ```
    pub fn string_index(&self, index: usize) -> usize {
        if !self.indices.is_empty() && index > 0 {
            self.indices[index - 1] + index
        } else {
            index
        }
    }

    /// Returns the char at the specified position.
    ///
    /// # Arguments
    /// * `at` - The position to retrieve the char from.
    ///
    /// # Panics
    /// Panics if the position is out of bounds.
    ///
    /// # Examples
    /// ```
    /// use text_editing::TextLine;
    ///
    /// let line = TextLine::from_string("Hello, world!".into());
    /// assert_eq!(line.char_at(7), 'w');
    /// ```
    pub fn char_at(&self, at: usize) -> char {
        self.char_at_checked(at).unwrap()
    }

    fn char_at_checked(&self, at: usize) -> Option<char> {
        self.text[self.string_index(at)..].chars().next()
    }

    /// Inserts a new char into the text line.
    ///
    /// # Arguments
    /// * `index` - The position to insert the char at.
    /// * `c` - The char to insert.
    ///
    /// # Examples
    /// ```
    /// use text_editing::TextLine;
    ///
    /// let mut line = TextLine::from_string("Hello, orld!".into());
    /// line.insert(7, 'w');
    /// assert_eq!(line.as_str(), "Hello, world!");
    /// ```
    pub fn insert(&mut self, index: usize, c: char) {
        self.text.insert(self.string_index(index), c);
        self.indices.clear();
        self.refresh_indices();
    }

    /// Removes a char from the text line.
    ///
    /// # Arguments
    /// * `index` - The position to remove the char from.
    ///
    /// # Returns
    /// The removed char.
    ///
    /// # Examples
    /// ```
    /// use text_editing::TextLine;
    ///
    /// let mut line = TextLine::from_string("Hello, world!".into());
    /// assert_eq!(line.remove(7), 'w');
    /// assert_eq!(line.as_str(), "Hello, orld!");
    /// ```
    pub fn remove(&mut self, index: usize) -> char {
        let result = self.text.remove(self.string_index(index));
        self.indices.clear();
        self.refresh_indices();
        result
    }

    /// Removes the specified range from the text line.
    ///
    /// # Arguments
    /// * `range` - The range to remove.
    ///
    /// # Examples
    /// ```
    /// use text_editing::TextLine;
    ///
    /// let mut line = TextLine::from_string("Hello, world!".into());
    /// line.remove_range(7..12);
    /// assert_eq!(line.as_str(), "Hello, !");
    /// ```
    pub fn remove_range(&mut self, range: Range<usize>) {
        self.text.replace_range(
            self.string_index(range.start)..self.string_index(range.end),
            "",
        );
        self.indices.clear();
        self.refresh_indices();
    }

    /// Splits a text line into two.
    ///
    /// # Arguments
    /// * `index` - The position to split the text line at.
    ///
    /// # Returns
    /// The new text line containing the text after the split position.
    ///
    /// # Examples
    /// ```
    /// use text_editing::TextLine;
    ///
    /// let mut line = TextLine::from_string("Hello, world!".into());
    /// let second_half = line.split(7);
    /// assert_eq!(line.as_str(), "Hello, ");
    /// assert_eq!(second_half.as_str(), "world!");
    /// ```
    pub fn split(&mut self, index: usize) -> Self {
        let mut result = Self {
            text: self.text.split_off(self.string_index(index)),
            indices: Vec::new(),
        };
        self.indices.clear();
        self.refresh_indices();
        result.refresh_indices();
        result
    }

    /// Joins two text lines into one.
    ///
    /// # Arguments
    /// * `other` - The text line to append to the current text line.
    ///
    /// # Examples
    /// ```
    /// use text_editing::TextLine;
    ///
    /// let mut line1 = TextLine::from_string("Hello, ".into());
    /// let line2 = TextLine::from_string("world!".into());
    /// line1.join(line2);
    /// assert_eq!(line1.as_str(), "Hello, world!");
    /// ```
    pub fn join(&mut self, other: Self) {
        self.text.push_str(&other.text);
        self.indices.clear();
        self.refresh_indices();
    }
}

impl FromStr for TextLine {
    type Err = Infallible;

    fn from_str(text: &str) -> Result<Self, Infallible> {
        Ok(Self::from_string(text.to_string()))
    }
}

impl Display for TextLine {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

impl From<String> for TextLine {
    fn from(text: String) -> Self {
        Self::from_string(text)
    }
}

impl From<TextLine> for String {
    fn from(text_line: TextLine) -> Self {
        text_line.text
    }
}

mod cursor;
mod editing;

pub use cursor::Direction;