ted 0.7.0

Core text editor functionality.
Documentation
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
//! Functions that compute new cursor positions.

use std::ops::Range;
use ropey::{Rope, RopeSlice};
use super::{Cursor, Position};
use unicode_segmentation::UnicodeSegmentation;

/// Go one char to the right.
pub fn right(text: &Rope, char_idx: usize) -> usize {
    (char_idx + 1).min(text.len_chars())
}

/// Go one char to the left.
pub fn left(char_idx: usize) -> usize {
    char_idx.saturating_sub(1)
}

/// Tries to keep the x position if possible.
pub fn vertical(text: &Rope, char_idx: usize, num_lines: isize) -> usize {
    // > If char_idx is one-past-the-end, then one-past-the-end line index is returned.
    // Circumvent this behavior by clipping to the last valid line index.
    let line_idx = text.char_to_line(char_idx)
        .min(text.len_lines().saturating_sub(1));
    if num_lines < 0 && line_idx > 0 || num_lines > 0 && line_idx < text.len_lines() - 1 {
        let x = char_idx - text.line_to_char(line_idx);
        let next_line_idx = (
            if num_lines > 0 {
                line_idx + num_lines as usize
            } else if let (value, false) = line_idx.overflowing_sub(num_lines.abs() as usize) {
                value
            } else { 0 }
        ).min(
            if text.len_lines() > 0 {
                text.len_lines() - 1
            } else { 0 }
        );
        let line = text.line(next_line_idx);
        let line_len = line.len_chars();

        text.line_to_char(next_line_idx) +
        x.min(line_len.saturating_sub(
            if line_len > 0 && line.char(line_len - 1) == '\n' { 1 } else { 0 }
        ))
    } else {
        char_idx
    }
}

/// Go to the first char on the line.
pub fn line_start(text: &Rope, char_idx: usize) -> usize {
    let line_idx = text.char_to_line(char_idx)
        .min(text.len_lines().saturating_sub(1));
    text.line_to_char(line_idx)
}

/// Go to the last char on the line.
pub fn line_end(text: &Rope, char_idx: usize) -> usize {
    let line_idx = text.char_to_line(char_idx);
    let len_lines = text.len_lines();

    text.line_to_char(line_idx) +
    if line_idx < len_lines {
        let line = text.line(line_idx);
        let line_len = line.len_chars();

        if line_len > 0 {
            line_len -
            if  line_idx == len_lines - 1               && // last line
                text.char(text.len_chars() - 1) != '\n'    // no trailing newline
            {
                0 // End of line is end of text, so we go one-past-the-end.
            } else {
                1 // Step onto the previous line break.
            }
        } else { 0 }
    } else { 0 }
}

/// Go to the previous word boundary.
pub fn word_left(text: &Rope, char_idx: usize) -> usize {
    word(text, char_idx, -1)
}

/// Go to the next word boundary.
pub fn word_right(text: &Rope, char_idx: usize) -> usize {
    word(text, char_idx, 1)
}

fn word(text: &Rope, char_idx: usize, direction: i8) -> usize {
    if  direction.is_negative() && char_idx == 0 ||
        direction.is_positive() && char_idx == text.len_chars()
    { return char_idx }

    enum Next {
        Whitespace,
        Word
    }

    impl Next {
        fn matches(&self, char: char) -> bool {
            match self {
                &Next::Whitespace => char.is_whitespace(),
                &Next::Word       => char.is_alphanumeric()
            }
        }

        fn next(self, char: char) -> Option<Self> {
            if self.matches(char) {
                Some(self)
            } else {
                match self {
                    Next::Whitespace => Some(Next::Word),
                    Next::Word       => None
                }
            }
        }
    }

    let len_chars = text.len_chars();
    let text = if direction.is_negative() {
        text.slice(..char_idx)
    } else if direction.is_positive() {
        text.slice(char_idx + 1..)
    } else {
        return char_idx
    };
    let mut next = Next::Whitespace;
    let mut current_idx = char_idx;
    /* We need to create both iterators for them to live long enough
     * even though we don't know whether we want to reverse yet.
     * XXX could overcome this by replacing the generalized for loop below with two specialized loops */
    let mut chars_enumerate = Chars::from_slice(text).enumerate();
    let mut chars_rev_enumerate = Chars::from_slice(text).rev().enumerate();
    let chars: &mut Iterator<Item=(usize, char)> = if direction.is_negative() {
        &mut chars_rev_enumerate
    } else {
        &mut chars_enumerate
    };
    let mut terminated = false;
    for (count, char) in chars {
        next = match next.next(char) {
            Some(next) => {
                current_idx = if direction.is_negative() {
                    char_idx - count - 1
                } else {
                    char_idx + count + 1
                };
                next
            },
            None => {
                if direction.is_positive() {
                    current_idx = char_idx + count + 1;
                }
                terminated = true;
                break
            }
        };
    }
    /* Go to first or one-past-the-end char index
     * if we just stopped because there was no char left to handle. */
    if !terminated {
        if current_idx == len_chars - 1 {
            current_idx = len_chars;
        } else if current_idx == 1 {
            current_idx = 0
        }
    }
    current_idx
}

/// Returns the new positions if a cursor was spawned.
pub fn spawn(cur: &Cursor, text: &Rope) -> Option<Vec<Position>> {
    if let Some((end, Some(start))) = cur.positions().rev().next() {
        let found = {
            let mut found = None;

            let sel = super::select((start, end));
            let sel_text = text.slice(sel.clone());

            let mut sel_candidate_idx = 0; // expected char
            for (search_idx, char) in text.slice(sel.end..).chars().enumerate() {
                if sel_text.char(sel_candidate_idx) == char {
                    // Found match, expect the next char.
                    sel_candidate_idx += 1;
                } else {
                    // We expected another char, reset the progress.
                    sel_candidate_idx = 0;
                }

                if sel_candidate_idx == sel_text.len_chars() {
                    // We found all chars of the selection.
                    let found_start = sel.end + search_idx + 1 - sel_text.len_chars();
                    let found_end   = sel.end + search_idx + 1;
                    found = Some(
                        if end > start {(
                            found_start,
                            Some(found_end)
                        )} else {(
                            found_end,
                            Some(found_start)
                        )}
                    );
                    break;
                }
            }

            found
        };

        found.map(|found| {
            let found_iter = [found];
            let found_iter = found_iter.iter().map(|idx| *idx);
            cur.positions().chain(found_iter).collect::<Vec<_>>()
        })
    } else {
        None
    }
}

pub fn die(cur: &Cursor) -> Option<Vec<Position>> {
    if cur.positions().len() > 1 {
        let positions = {
            let mut positions = cur.positions();
            positions.next_back();
            positions.collect()
        };
        Some(positions)
    } else {
        None
    }
}

pub fn skip(cur: &Cursor, text: &Rope) -> Option<Vec<Position>> {
    spawn(cur, text).map(|mut positions| {
        let len = positions.len();
        positions.remove(len - 2);
        positions
    })
}

pub fn select_words(cur: &Cursor, text: &Rope) -> Vec<Position> {
    // XXX allocate each line only once for all cursors on it or avoid allocation altogether
    cur.positions()
        .map(|pos| match pos {
            (char_idx, None)            => select_word(text, char_idx),
            (_,        Some(sel_start)) => select_word(text, sel_start)
        })
        .map(|sel| (sel.end, Some(sel.start)))
        .collect()
}

fn select_word(text: &Rope, char_idx: usize) -> Range<usize> {
    let line_idx = text.char_to_line(char_idx);
    if line_idx == text.len_lines() {
        return char_idx..char_idx
    }

    let line_char_idx = text.line_to_char(line_idx);
    let line = text.line(line_idx);
    let line_string = line.to_string();
    let x = char_idx - line_char_idx;

    let mut sel = x..line.len_chars();
    for (idx, _) in line_string.split_word_bound_indices() {
        let idx = line_string[..idx].chars().count();
        if idx > x {
            sel.end = idx;
            break;
        } else {
            sel.start = idx;
        }
    }
    sel.start += line_char_idx;
    sel.end   += line_char_idx;
    sel
}

pub fn select_lines(cur: &Cursor, text: &Rope) -> Vec<Position> {
    cur.positions()
        .map(|(char_idx, _)| select_line(text, char_idx))
        .map(|sel| (sel.end, Some(sel.start)))
        .collect()
}

fn select_line(text: &Rope, char_idx: usize) -> Range<usize> {
    let line_idx = text.char_to_line(char_idx);
    if line_idx < text.len_lines() {
        text.line_to_char(line_idx)..text.line_to_char(line_idx + 1)
    } else {
        char_idx..char_idx
    }
}

struct Chars<'a> {
    text: RopeSlice<'a>,
    char_idx: usize,
    popped: usize
}

impl<'a> Chars<'a> {
    #[allow(dead_code)]
    pub fn from_rope(text: &'a Rope) -> Self {
        Self {
            text: text.slice(..),
            char_idx: 0,
            popped: 0
        }
    }

    pub fn from_slice(text: RopeSlice<'a>) -> Self {
        Self {
            text: text,
            char_idx: 0,
            popped: 0
        }
    }
}

impl<'a> Iterator for Chars<'a> {
    type Item = char;

    fn next(&mut self) -> Option<Self::Item> {
        let idx = self.char_idx;
        if idx < self.text.len_chars() - self.popped {
            let char = self.text.char(idx);
            self.char_idx += 1;
            Some(char)
        } else {
            None
        }
    }
}

impl<'a> DoubleEndedIterator for Chars<'a> {
    fn next_back(&mut self) -> Option<Self::Item> {
        let len_chars = self.text.len_chars();

        if self.popped < len_chars {
            let idx = len_chars - 1 - self.popped;
            if idx > self.char_idx {
                let char = self.text.char(idx);
                self.popped += 1;
                Some(char)
            } else {
                None
            }
        } else {
            None
        }
    }
}

impl<'a> ExactSizeIterator for Chars<'a> {
    fn len(&self) -> usize {
        self.text.len_chars()
    }
}

#[cfg(test)]
mod tests {
    use ropey::Rope;

    const TEXT: &str = concat!(
        "1st\n",
        "2nd line\n",
        "3rd line"
    );

    #[test]
    fn right() {{
        let text = Rope::from_str(TEXT);
        let len_chars = text.len_chars();
        assert_eq!(1,             super::right(&text, 0));
        assert_eq!(len_chars - 1, super::right(&text, len_chars - 2));
        assert_eq!(len_chars,     super::right(&text, len_chars - 1));
        assert_eq!(len_chars,     super::right(&text, len_chars));
    } {
        let text = Rope::from_str("");
        assert_eq!(0, super::right(&text, 0));
    }}

    #[test]
    fn left() {
        assert_eq!(0, super::left(0));
        assert_eq!(0, super::left(1));
        assert_eq!(1, super::left(2));
    }

    #[test]
    fn down() {{
        let text = Rope::from_str(TEXT);
        assert_eq!(text.line_to_char(1),     super::vertical(&text, text.line_to_char(0),     1));
        assert_eq!(text.line_to_char(2),     super::vertical(&text, text.line_to_char(1),     1));
        assert_eq!(text.line_to_char(2),     super::vertical(&text, text.line_to_char(2),     1));
        assert_eq!(text.line_to_char(2) + 3, super::vertical(&text, text.line_to_char(1) + 3, 1));
        assert_eq!(text.len_chars(),         super::vertical(&text, text.line_to_char(2) - 1, 1));
    } {
        let text = Rope::from_str("");
        assert_eq!(0, super::vertical(&text, 0, 1));
    }}

    #[test]
    fn up() {{
        let text = Rope::from_str(TEXT);
        assert_eq!(text.line_to_char(1),     super::vertical(&text, text.line_to_char(2),     -1));
        assert_eq!(text.line_to_char(0),     super::vertical(&text, text.line_to_char(1),     -1));
        assert_eq!(text.line_to_char(0),     super::vertical(&text, text.line_to_char(0),     -1));
        assert_eq!(text.line_to_char(0) + 3, super::vertical(&text, text.line_to_char(1) + 3, -1));
        assert_eq!(text.line_to_char(1) - 1, super::vertical(&text, text.line_to_char(2) - 2, -1));
    } {
        let text = Rope::from_str("");
        assert_eq!(0, super::vertical(&text, 0, -1));
    }}

    #[test]
    fn line_start() {{
        let text = Rope::from_str(TEXT);
        assert_eq!(text.line_to_char(1), super::line_start(&text, 12));
        assert_eq!(text.line_to_char(1), super::line_start(&text, text.line_to_char(1)));
    } {
        let text = Rope::from_str("");
        assert_eq!(0, super::line_start(&text, 0));
    }}

    #[test]
    fn line_end() {{
        let text = Rope::from_str(TEXT);
        assert_eq!(text.line_to_char(2) - 1, super::line_end(&text, 12));
        assert_eq!(text.line_to_char(2) - 1, super::line_end(&text, text.line_to_char(2) - 1));
    } {
        let text = Rope::from_str("");
        assert_eq!(0, super::line_end(&text, 0));
    }}

    #[test]
    fn word_left() {{
        let text = Rope::from_str(TEXT);
        let len_chars = text.len_chars();
        assert_eq!(len_chars - 4, super::word_left(&text, len_chars));
        assert_eq!(len_chars - 8, super::word_left(&text, len_chars - 4));
    } {
        let text = Rope::from_str("");
        assert_eq!(0, super::word_left(&text, 0));
    }}

    #[test]
    fn word_right() {{
        let text = Rope::from_str(TEXT);
        let len_chars = text.len_chars();
        assert_eq!(len_chars - 5, super::word_right(&text, len_chars - 8));
        assert_eq!(len_chars,     super::word_right(&text, len_chars - 5));
    } {
        let text = Rope::from_str("");
        assert_eq!(0, super::word_right(&text, 0));
    }}

    #[test]
    fn select_word() {{
        let text = Rope::from_str("\none two three");
        assert_eq!(5..8,  super::select_word(&text,  5));
        assert_eq!(5..8,  super::select_word(&text,  6));
        assert_eq!(5..8,  super::select_word(&text,  7));
        assert_ne!(5..8,  super::select_word(&text,  8));
        assert_eq!(9..14, super::select_word(&text,  9));
        assert_eq!(9..14, super::select_word(&text, 10));
        assert_eq!(9..14, super::select_word(&text, 11));
        assert_eq!(9..14, super::select_word(&text, 12));
        assert_eq!(9..14, super::select_word(&text, 13));
        assert_ne!(9..14, super::select_word(&text, 14));
    } {
        let text = Rope::from_str("");
        assert_eq!(0..0, super::select_word(&text, 0));
    }}
}