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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
#![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());
/// ```
#[must_use]
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();
}
}
/// Inserts an entry into the index cache and shifts the suffix by `extra`,
/// the extra bytes the new char contributes. `pos` is the char index.
fn index_insert(&mut self, pos: usize, extra: usize) {
let base = if pos > 0 { self.indices[pos - 1] } else { 0 };
self.indices.insert(pos, base + extra);
if extra > 0 {
for v in &mut self.indices[pos + 1..] {
*v += extra;
}
}
}
/// Removes the entry at `pos` from the index cache and shifts the suffix
/// back by `extra`, the extra bytes the removed char contributed.
fn index_remove(&mut self, pos: usize, extra: usize) {
self.indices.remove(pos);
if extra > 0 {
for v in &mut self.indices[pos..] {
*v -= extra;
}
}
}
/// Creates a text line from a `String`.
///
/// # Examples
///
/// ```
/// use text_editing::TextLine;
///
/// let line = TextLine::from_string("Hello, world!".into());
/// assert_eq!(line.as_str(), "Hello, world!");
/// ```
#[must_use]
pub fn from_string(text: String) -> Self {
let mut result = Self {
text,
..Self::default()
};
result.refresh_indices();
result
}
/// Clears the text line, removing all content.
///
/// # Examples
///
/// ```
/// use text_editing::TextLine;
///
/// let mut line = TextLine::from_string("Hello, world!".into());
/// line.clear();
/// assert!(line.is_empty());
/// ```
pub fn clear(&mut self) {
self.text.clear();
self.indices.clear();
}
/// Checks if the line is empty.
///
/// # Examples
///
/// ```
/// use text_editing::TextLine;
///
/// let line = TextLine::new();
/// assert!(line.is_empty());
/// ```
#[must_use]
pub const fn is_empty(&self) -> bool {
self.text.is_empty()
}
/// Returns the number of chars in the text line.
///
/// # Examples
///
/// ```
/// use text_editing::TextLine;
///
/// let line = TextLine::from_string("Hello, world!".into());
/// assert_eq!(line.len(), 13);
/// ```
#[must_use]
pub const 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.
///
/// # Examples
///
/// ```
/// use text_editing::TextLine;
///
/// let line = TextLine::from_string("Hello, world!".into());
/// assert_eq!(line.as_str(), "Hello, world!");
/// ```
#[must_use]
pub fn as_str(&self) -> &str {
&self.text
}
/// Converts the character index to the string index.
///
/// # Examples
///
/// ```
/// use text_editing::TextLine;
///
/// let line = TextLine::from_string("Hello, world!".into());
/// assert_eq!(line.string_index(7), 7);
/// ```
#[must_use]
pub fn string_index(&self, index: usize) -> usize {
if !self.indices.is_empty() && index > 0 {
self.indices[index - 1] + index
} else {
index
}
}
/// Converts the string index to the character index. The inverse of
/// [`string_index`](Self::string_index).
///
/// # Panics
///
/// Panics if `byte_index` is not on a char boundary or exceeds the text length.
///
/// # Examples
///
/// ```
/// use text_editing::TextLine;
///
/// let line = TextLine::from("aπb");
/// assert_eq!(line.char_index(5), 2);
/// assert_eq!(line.char_index(line.as_str().len()), 3);
/// ```
#[must_use]
pub fn char_index(&self, byte_index: usize) -> usize {
assert!(
self.text.is_char_boundary(byte_index),
"byte index {byte_index} is not a char boundary",
);
if self.indices.is_empty() {
return byte_index;
}
let mut low = 0;
let mut high = self.len();
while low < high {
let middle = low + (high - low) / 2;
if self.string_index(middle) < byte_index {
low = middle + 1;
} else {
high = middle;
}
}
low
}
/// Returns the text between two char positions.
///
/// # Panics
///
/// Panics if the range is out of bounds or reversed.
///
/// # Examples
///
/// ```
/// use text_editing::TextLine;
///
/// let line = TextLine::from("aπbπ¦c");
/// assert_eq!(line.slice(1..4), "πbπ¦");
/// ```
#[must_use]
pub fn slice(&self, range: Range<usize>) -> &str {
&self.text[self.string_index(range.start)..self.string_index(range.end)]
}
/// Returns the char at the specified position, or [`None`] if out of bounds.
///
/// # Examples
///
/// ```
/// use text_editing::TextLine;
///
/// let line = TextLine::from_string("Hello, world!".into());
/// assert_eq!(line.char_at_checked(7), Some('w'));
/// assert_eq!(line.char_at_checked(99), None);
/// ```
#[must_use]
pub fn char_at_checked(&self, at: usize) -> Option<char> {
if at >= self.len() {
return None;
}
self.text[self.string_index(at)..].chars().next()
}
/// Returns the char at the specified position.
///
/// # Panics
///
/// Panics if the position is out of bounds. Use [`char_at_checked`](Self::char_at_checked)
/// for a fallible variant.
///
/// # Examples
///
/// ```
/// use text_editing::TextLine;
///
/// let line = TextLine::from_string("Hello, world!".into());
/// assert_eq!(line.char_at(7), 'w');
/// ```
#[must_use]
pub fn char_at(&self, at: usize) -> char {
self.char_at_checked(at).unwrap()
}
/// Inserts a new char into the text line.
///
/// # Panics
///
/// Panics if `index` is greater than the number of chars.
///
/// # 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);
let extra = c.len_utf8() - 1;
if !self.indices.is_empty() {
self.index_insert(index, extra);
} else if extra > 0 {
self.enable_indices();
}
}
/// Removes a char from the text line and returns it.
///
/// # Panics
///
/// Panics if `index` is out of bounds.
///
/// # 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));
if !self.indices.is_empty() {
self.index_remove(index, result.len_utf8() - 1);
}
result
}
/// Removes the specified range from the text line.
///
/// # Panics
///
/// Panics if the range is out of bounds.
///
/// # 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),
"",
);
if !self.indices.is_empty() && !range.is_empty() {
let before = if range.start > 0 {
self.indices[range.start - 1]
} else {
0
};
let total_extra = self.indices[range.end - 1] - before;
let start = range.start;
self.indices.drain(range);
if total_extra > 0 {
for v in &mut self.indices[start..] {
*v -= total_extra;
}
}
}
}
/// Replaces the specified char range with `text`.
///
/// # Panics
///
/// Panics if the range is out of bounds.
///
/// # Examples
///
/// ```
/// use text_editing::TextLine;
///
/// let mut line = TextLine::from("Hello, world!");
/// line.replace_range(7..12, "π");
/// assert_eq!(line.as_str(), "Hello, π!");
/// ```
pub fn replace_range(&mut self, range: Range<usize>, text: &str) {
let mut cursor = range.start;
self.remove_range(range);
self.insert_str(&mut cursor, text);
}
/// Splits a text line into two.
///
/// # 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!");
/// ```
#[must_use]
pub fn split(&mut self, index: usize) -> Self {
let text = self.text.split_off(self.string_index(index));
let result_indices = if self.indices.is_empty() {
Vec::new()
} else {
let before = if index > 0 {
self.indices[index - 1]
} else {
0
};
let tail: Vec<usize> = self.indices[index..].iter().map(|&v| v - before).collect();
self.indices.truncate(index);
tail
};
Self {
text,
indices: result_indices,
}
}
/// Joins two text lines into one.
///
/// # 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);
if !self.indices.is_empty() {
let mut running = *self.indices.last().unwrap_or(&0);
for c in other.text.chars() {
running += c.len_utf8() - 1;
self.indices.push(running);
}
} else if !other.text.is_ascii() {
self.enable_indices();
}
}
}
impl FromStr for TextLine {
type Err = Infallible;
fn from_str(text: &str) -> Result<Self, Infallible> {
Ok(Self::from_string(text.into()))
}
}
impl Display for TextLine {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
impl From<String> for TextLine {
fn from(text: String) -> Self {
Self::from_string(text)
}
}
impl From<&str> for TextLine {
fn from(text: &str) -> Self {
Self::from_string(text.into())
}
}
impl From<TextLine> for String {
fn from(text_line: TextLine) -> Self {
text_line.text
}
}
mod cursor;
mod editing;
mod selection;
pub use cursor::Direction;
#[cfg(test)]
mod tests {
use super::TextLine;
/// Byte offset of each char boundary, reconstructed from the raw text.
fn expected_offsets(line: &TextLine) -> Vec<usize> {
let mut offsets = vec![0];
let mut last = 0;
for c in line.as_str().chars() {
last += c.len_utf8();
offsets.push(last);
}
offsets
}
/// Asserts the incremental index cache matches a from-scratch rebuild.
fn check(line: &TextLine) {
let expected = expected_offsets(line);
assert_eq!(line.len() + 1, expected.len());
for (i, &offset) in expected.iter().enumerate() {
assert_eq!(
line.string_index(i),
offset,
"string_index({i}) wrong for {:?}",
line.as_str(),
);
}
for (i, c) in line.as_str().chars().enumerate() {
assert_eq!(
line.char_at(i),
c,
"char_at({i}) wrong for {:?}",
line.as_str(),
);
}
}
#[test]
fn ascii_stays_cacheless() {
let mut line = TextLine::from_string("hello".into());
line.insert(5, ' ');
line.insert(6, 'w');
check(&line);
line.remove(0);
check(&line);
}
#[test]
fn insert_non_ascii_activates() {
let mut line = TextLine::from_string("ab".into());
line.insert(1, 'π');
check(&line);
assert_eq!(line.as_str(), "aπb");
}
#[test]
fn insert_ascii_into_non_ascii() {
let mut line = TextLine::from_string("aπb".into());
check(&line);
line.insert(2, 'X');
check(&line);
line.insert(0, 'Y');
check(&line);
line.insert(line.len(), 'Z');
check(&line);
assert_eq!(line.as_str(), "YaπXbZ");
}
#[test]
fn remove_non_ascii() {
let mut line = TextLine::from_string("aπb".into());
assert_eq!(line.remove(1), 'π');
check(&line);
assert_eq!(line.as_str(), "ab");
}
#[test]
fn remove_range_spanning_non_ascii() {
let mut line = TextLine::from_string("xπyπz".into());
line.remove_range(1..3);
check(&line);
assert_eq!(line.as_str(), "xπz");
line.remove_range(0..line.len());
check(&line);
assert!(line.is_empty());
}
#[test]
fn insert_str_non_ascii() {
let mut line = TextLine::from_string("aπb".into());
let mut cursor = 2;
line.insert_str(&mut cursor, "xπ¦y");
check(&line);
assert_eq!(cursor, 5);
assert_eq!(line.as_str(), "aπxπ¦yb");
}
#[test]
fn split_non_ascii() {
let mut line = TextLine::from_string("aπbπ¦c".into());
let second = line.split(3);
check(&line);
check(&second);
assert_eq!(line.as_str(), "aπb");
assert_eq!(second.as_str(), "π¦c");
}
#[test]
fn join_non_ascii() {
let mut line = TextLine::from_string("aπ".into());
line.join(&TextLine::from_string("bπ¦".into()));
check(&line);
assert_eq!(line.as_str(), "aπbπ¦");
}
#[test]
fn char_index_inverts_string_index() {
for text in ["", "hello", "aπbπ¦c", "π", "Àâü"] {
let line = TextLine::from(text);
for position in 0..=line.len() {
assert_eq!(line.char_index(line.string_index(position)), position);
}
}
}
#[test]
#[should_panic(expected = "not a char boundary")]
fn char_index_rejects_mid_char_offset() {
let _ = TextLine::from("aπb").char_index(2);
}
#[test]
fn slice_matches_chars() {
let line = TextLine::from("aπbπ¦c");
let chars: Vec<char> = line.as_str().chars().collect();
for start in 0..=chars.len() {
for end in start..=chars.len() {
let expected: String = chars[start..end].iter().collect();
assert_eq!(line.slice(start..end), expected);
}
}
}
#[test]
fn replace_range_keeps_cache_consistent() {
let mut line = TextLine::from("aπbπ¦c");
line.replace_range(1..4, "xy");
check(&line);
assert_eq!(line.as_str(), "axyc");
line.replace_range(1..3, "ππ¦π");
check(&line);
assert_eq!(line.as_str(), "aππ¦πc");
line.replace_range(0..line.len(), "");
check(&line);
assert!(line.is_empty());
line.replace_range(0..0, "Γ©");
check(&line);
}
#[test]
fn mixed_mutation_sequence() {
let mut line = TextLine::new();
for (i, c) in ['h', 'i', 'π', '!', 'π¦'].into_iter().enumerate() {
line.insert(i, c);
check(&line);
}
assert_eq!(line.remove(2), 'π');
check(&line);
assert_eq!(line.as_str(), "hi!π¦");
let mut cursor = line.len();
line.insert_str(&mut cursor, "π¦ end");
check(&line);
line.remove_range(1..4);
check(&line);
}
}