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
use std::{cmp::Ordering, ops::ControlFlow};

use super::{
    tags::{self, RawTag, TextId},
    Part, Text,
};
use crate::position::Cursor;

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct ExactPos {
    real: usize,
    ghost: usize,
}

impl Ord for ExactPos {
    fn cmp(&self, other: &Self) -> Ordering {
        match self.real.cmp(&other.real) {
            Ordering::Less => Ordering::Less,
            Ordering::Greater => Ordering::Greater,
            Ordering::Equal => {
                if (self.ghost == 0 && other.ghost == usize::MAX)
                    || (self.ghost == usize::MAX && other.ghost == 0)
                {
                    Ordering::Equal
                } else {
                    self.ghost.cmp(&other.ghost)
                }
            }
        }
    }
}

impl PartialOrd for ExactPos {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl ExactPos {
    pub fn at_cursor_char(real: usize) -> Self {
        Self {
            real,
            ghost: usize::MAX,
        }
    }

    pub fn real(&self) -> usize {
        self.real
    }

    pub fn ghost(&self) -> usize {
        self.ghost
    }

    #[inline]
    pub(crate) fn new(real: usize, ghost: usize) -> Self {
        Self { real, ghost }
    }

    fn clamp(self, text: &Text) -> Self {
        ExactPos {
            real: self.real.min(text.len_chars()),
            ghost: self.ghost,
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub struct Item {
    pub pos: ExactPos,
    pub line: usize,
    pub part: Part,
}

impl Item {
    #[inline]
    fn new(pos: ExactPos, line: usize, part: Part) -> Self {
        Self { pos, line, part }
    }

    #[inline]
    pub fn real(&self) -> usize {
        self.pos.real()
    }

    #[inline]
    pub fn ghost(&self) -> usize {
        self.pos.ghost()
    }
}

/// An [`Iterator`] over the [`TextBit`]s of the [`Text`].
///
/// This is useful for both printing and measurement of [`Text`], and
/// can incorporate string replacements as part of its design.
#[derive(Clone)]
pub struct Iter<'a> {
    text: &'a Text,
    chars: ropey::iter::Chars<'a>,
    tags: tags::ForwardIter<'a>,
    pos: usize,
    line: usize,
    conceals: usize,

    // Things to deal with ghost text.
    backup_iter: Option<(usize, ropey::iter::Chars<'a>, tags::ForwardIter<'a>)>,
    ghosts_to_ignore: Vec<TextId>,
    ghost_shift: usize,

    // Configuration on how to iterate.
    print_ghosts: bool,
    _conceals: Conceal<'a>,
}

impl<'a> Iter<'a> {
    pub(super) fn new_at(text: &'a Text, pos: usize) -> Self {
        let pos = pos.min(text.len_chars());
        let tags_start = pos.saturating_sub(text.tags.back_check_amount());

        Self {
            text,
            chars: text.rope.chars_at(pos),
            tags: text.tags.iter_at(tags_start),
            pos,
            line: text.rope.char_to_line(pos),
            conceals: 0,

            backup_iter: None,
            ghosts_to_ignore: Vec::new(),
            ghost_shift: 0,

            print_ghosts: true,
            _conceals: Conceal::All,
        }
    }

    pub(super) fn new_exactly_at(text: &'a Text, exact_pos: ExactPos) -> Self {
        let ExactPos { real, mut ghost } = exact_pos.clamp(text);
        let mut ghosts_to_ignore = Vec::new();
        let mut ghost_shift = 0;

        let (chars, tags) = {
            let text = text.tags.on(real).find_map(|tag| match tag {
                RawTag::GhostText(_, id) => {
                    ghosts_to_ignore.push(id);
                    text.tags.texts.get(&id).and_then(|text| {
                        if ghost < text.len_chars() {
                            Some(text)
                        } else {
                            ghost_shift += text.len_chars();
                            ghost -= text.len_chars();
                            None
                        }
                    })
                }
                _ => None,
            });

            text.map(|text| {
                let tags_start = ghost.saturating_sub(text.tags.back_check_amount());

                let chars = text.rope.chars_at(ghost);
                let tags = text.tags.iter_at(tags_start);

                (chars, tags)
            })
            .unzip()
        };

        let tags_start = real.saturating_sub(text.tags.back_check_amount());
        let pos = if chars.is_some() { ghost } else { real };
        let backup_iter = chars.is_some().then(|| {
            let chars = text.rope.chars_at(real);
            let tags = text.tags.iter_at(tags_start);

            (real, chars, tags)
        });

        Self {
            text,
            chars: chars.unwrap_or_else(|| text.rope.chars_at(real)),
            tags: tags.unwrap_or_else(|| text.tags.iter_at(tags_start)),
            pos,
            line: text.rope.char_to_line(real),
            conceals: 0,

            backup_iter,
            ghosts_to_ignore,
            ghost_shift,

            print_ghosts: true,
            _conceals: Conceal::All,
        }
    }

    pub fn no_conceals(self) -> Self {
        Self {
            _conceals: Conceal::None,
            ..self
        }
    }

    pub fn dont_conceal_containing(self, list: &'a [Cursor]) -> Self {
        Self {
            _conceals: Conceal::Excluding(list),
            ..self
        }
    }

    pub fn no_ghosts(self) -> Self {
        Self {
            print_ghosts: false,
            ..self
        }
    }

    #[inline]
    fn process_meta_tags(&mut self, tag: &RawTag, pos: usize) -> ControlFlow<(), ()> {
        match tag {
            RawTag::GhostText(_, id) if self.print_ghosts => {
                if self.ghosts_to_ignore.contains(id) || pos < self.pos || self.conceals > 0 {
                    return ControlFlow::Continue(());
                }
                self.ghost_shift = 0;

                let Some(text) = self.text.tags.on(pos).find_map(|tag| match tag {
                    RawTag::GhostText(_, cmp) if cmp == *id => self.text.tags.texts.get(id),
                    RawTag::GhostText(_, id) => {
                        let text = self.text.tags.texts.get(&id);
                        self.ghost_shift += text.map(|t| t.len_chars()).unwrap_or(0);
                        None
                    }
                    _ => None,
                }) else {
                    return ControlFlow::Continue(());
                };

                let iter = text.iter();
                let pos = std::mem::replace(&mut self.pos, iter.pos);
                let chars = std::mem::replace(&mut self.chars, iter.chars);
                let tags = std::mem::replace(&mut self.tags, iter.tags);

                self.backup_iter = Some((pos, chars, tags));
                ControlFlow::Continue(())
            }
            RawTag::GhostText(..) => ControlFlow::Continue(()),

            RawTag::ConcealStart(_) => {
                self.conceals += 1;
                ControlFlow::Continue(())
            }
            RawTag::ConcealEnd(_) => {
                self.conceals = self.conceals.saturating_sub(1);
                if self.conceals == 0 {
                    self.pos = self.pos.max(pos);
                    self.line = self.text.rope.char_to_line(pos);
                    self.chars = self.text.rope.chars_at(self.pos);
                }

                ControlFlow::Continue(())
            }
            RawTag::Concealed(skip) => {
                let pos = pos.saturating_add(*skip);
                *self = Iter::new_at(self.text, pos);
                ControlFlow::Break(())
            }
            _ => ControlFlow::Break(()),
        }
    }
}

impl Iterator for Iter<'_> {
    /// In order:
    ///
    /// - The position of the [`Part`] in the [`Text`], it can be [`None`], when
    ///   iterating over ghost text.
    /// - The line the [`Part`] would be situated in, given a count of `'\n'`s
    ///   before it, iterating over the unconcealed text without any ghost texts
    ///   within.
    /// - The [`Part`] itself, giving either a [`char`] or a text modifier,
    ///   which should be used to change the way the [`Text`] is printed.
    type Item = Item;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        loop {
            let tag = self.tags.peek();

            if let Some(&(pos, tag)) = tag.filter(|(pos, _)| *pos <= self.pos || self.conceals > 0)
            {
                self.tags.next();

                if let ControlFlow::Break(_) = self.process_meta_tags(&tag, pos) {
                    let pos = if let Some((real, ..)) = self.backup_iter.as_ref() {
                        ExactPos::new(*real, self.ghost_shift + self.pos)
                    } else {
                        ExactPos::new(self.pos, self.ghost_shift)
                    };

                    break Some(Item::new(pos, self.line, Part::from_raw(tag)));
                }
            } else if let Some(char) = self.chars.next() {
                let prev_line = self.line;
                let pos = if let Some((real, ..)) = self.backup_iter.as_ref() {
                    ExactPos::new(*real, self.ghost_shift + self.pos)
                } else {
                    let ghost = self.ghost_shift;
                    self.ghost_shift = 0;
                    self.line += (char == '\n') as usize;
                    ExactPos::new(self.pos, ghost)
                };
                self.pos += 1;

                break Some(Item::new(pos, prev_line, Part::Char(char)));
            } else if let Some(backup) = self.backup_iter.take() {
                self.ghost_shift += self.pos;
                (self.pos, self.chars, self.tags) = backup;
            } else {
                break None;
            }
        }
    }
}

/// An [`Iterator`] over the [`Part`]s of the [`Text`].
///
/// This is useful for both printing and measurement of [`Text`], and
/// can incorporate string replacements as part of its design.
#[derive(Clone)]
pub struct RevIter<'a> {
    text: &'a Text,
    chars: ropey::iter::Chars<'a>,
    tags: tags::ReverseTags<'a>,
    pos: usize,
    line: usize,
    conceals: usize,

    backup_iter: Option<(usize, ropey::iter::Chars<'a>, tags::ReverseTags<'a>)>,
    ghosts_to_ignore: Vec<TextId>,
    ghost_shift: usize,

    // Iteration options:
    print_ghosts: bool,
    _conceals: Conceal<'a>,
}

impl<'a> RevIter<'a> {
    pub(super) fn new_at(text: &'a Text, pos: usize) -> Self {
        let pos = pos.min(text.len_chars());
        let tags_start = pos + text.tags.back_check_amount();
        Self {
            text,
            chars: text.rope.chars_at(pos).reversed(),
            tags: text.tags.rev_iter_at(tags_start),
            pos,
            line: text.char_to_line(pos),
            conceals: 0,
            backup_iter: None,
            ghosts_to_ignore: Vec::new(),
            ghost_shift: 0,

            print_ghosts: true,
            _conceals: Conceal::All,
        }
    }

    pub(super) fn new_exactly_at(text: &'a Text, exact_pos: ExactPos) -> Self {
        let ExactPos { real, mut ghost } = exact_pos.clamp(text);
        let mut ghosts_to_ignore = Vec::new();
        let mut ghost_shift = 0;

        let (chars, tags) = {
            let mut text_ids = text.tags.on(real).filter_map(|tag| match tag {
                RawTag::GhostText(_, id) => Some(id),
                _ => None,
            });

            let text = text_ids.find_map(|id| {
                text.tags.texts.get(&id).and_then(|text| {
                    if ghost < text.len_chars() {
                        ghosts_to_ignore.push(id);
                        Some(text)
                    } else {
                        ghost_shift += text.len_chars();
                        ghost -= text.len_chars();
                        None
                    }
                })
            });

            ghosts_to_ignore.extend(text_ids);

            text.map(|text| {
                ghost = ghost.min(text.len_chars());
                let tags_start = ghost + text.tags.back_check_amount();

                let chars = text.rope.chars_at(ghost).reversed();
                let tags = text.tags.rev_iter_at(tags_start);

                (chars, tags)
            })
            .unzip()
        };

        let tags_start = real + text.tags.back_check_amount();

        let pos = if chars.is_some() { ghost } else { real };

        let backup_iter = chars.is_some().then(|| {
            let chars = text.rope.chars_at(real).reversed();
            let tags = text.tags.rev_iter_at(tags_start);

            (real, chars, tags)
        });

        Self {
            text,
            chars: chars.unwrap_or_else(|| text.rope.chars_at(real).reversed()),
            tags: tags.unwrap_or_else(|| text.tags.rev_iter_at(tags_start)),
            pos,
            line: text.rope.char_to_line(real),
            conceals: 0,

            backup_iter,
            ghosts_to_ignore,
            ghost_shift,

            print_ghosts: true,
            _conceals: Conceal::All,
        }
    }

    pub(super) fn new_following(text: &'a Text, exact_pos: ExactPos) -> Self {
        let mut ghost = exact_pos.ghost();
        let exact_pos = if text.tags.on(exact_pos.real()).any(|tag| {
            if let RawTag::GhostText(_, id) = tag {
                text.tags.texts.get(&id).is_some_and(|text| {
                    if ghost < text.len_chars() {
                        true
                    } else {
                        ghost -= text.len_chars();
                        false
                    }
                })
            } else {
                false
            }
        }) {
            ExactPos::new(exact_pos.real(), exact_pos.ghost() + 1)
        } else {
            ExactPos::new(exact_pos.real() + 1, 0)
        };

        Self::new_exactly_at(text, exact_pos)
    }

    pub fn no_conceals(self) -> Self {
        Self {
            _conceals: Conceal::None,
            ..self
        }
    }

    pub fn dont_conceal_containing(self, list: &'a [Cursor]) -> Self {
        Self {
            _conceals: Conceal::Excluding(list),
            ..self
        }
    }

    pub fn dont_conceal_on_lines(self, list: &'a [Cursor]) -> Self {
        Self {
            _conceals: Conceal::NotOnLineOf(list),
            ..self
        }
    }

    pub fn no_ghosts(self) -> Self {
        Self {
            print_ghosts: false,
            ..self
        }
    }

    #[inline]
    fn process_meta_tags(&mut self, tag: &RawTag, pos: usize) -> ControlFlow<()> {
        match tag {
            RawTag::GhostText(_, id) if self.print_ghosts => {
                if self.ghosts_to_ignore.contains(id) || pos > self.pos || self.conceals > 0 {
                    return ControlFlow::Continue(());
                }
                self.ghost_shift = 0;

                let Some(text) = self.text.tags.on(pos).find_map(|tag| match tag {
                    RawTag::GhostText(_, cmp) if cmp == *id => self.text.tags.texts.get(id),
                    RawTag::GhostText(_, id) => {
                        let text = self.text.tags.texts.get(&id);
                        self.ghost_shift += text.map(|t| t.len_chars()).unwrap_or(0);
                        None
                    }
                    _ => None,
                }) else {
                    return ControlFlow::Continue(());
                };

                let iter = text.rev_iter();
                let pos = std::mem::replace(&mut self.pos, iter.pos);
                let chars = std::mem::replace(&mut self.chars, iter.chars);
                let tags = std::mem::replace(&mut self.tags, iter.tags);

                self.backup_iter = Some((pos, chars, tags));

                ControlFlow::Continue(())
            }
            RawTag::GhostText(..) => ControlFlow::Continue(()),

            RawTag::ConcealStart(_) => {
                self.conceals = self.conceals.saturating_sub(1);
                if self.conceals == 0 {
                    self.pos = self.pos.min(pos);
                    self.line = self.text.rope.char_to_line(self.pos);
                    self.chars = self.text.rope.chars_at(self.pos).reversed();
                }

                ControlFlow::Continue(())
            }
            RawTag::ConcealEnd(_) => {
                self.conceals += 1;

                ControlFlow::Continue(())
            }
            RawTag::Concealed(skip) => {
                self.pos = pos.saturating_sub(*skip);
                self.line = self.text.rope.char_to_line(self.pos);
                self.chars = self.text.rope.chars_at(self.pos).reversed();
                self.tags = self.text.tags.rev_iter_at(self.pos);
                self.conceals = 0;

                ControlFlow::Break(())
            }
            _ => ControlFlow::Break(()),
        }
    }
}

impl Iterator for RevIter<'_> {
    type Item = Item;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        loop {
            let tag = self.tags.peek();

            if let Some(&(pos, tag)) = tag.filter(|(pos, _)| *pos >= self.pos || self.conceals > 0)
            {
                self.tags.next();

                if let ControlFlow::Break(_) = self.process_meta_tags(&tag, pos) {
                    let pos = if let Some((real, ..)) = self.backup_iter.as_ref() {
                        ExactPos::new(*real, self.ghost_shift + self.pos)
                    } else {
                        ExactPos::new(self.pos, self.ghost_shift)
                    };

                    break Some(Item::new(pos, self.line, Part::from_raw(tag)));
                }
            } else if let Some(char) = self.chars.next() {
                self.pos -= 1;
                let pos = if let Some((real, ..)) = self.backup_iter.as_ref() {
                    ExactPos::new(*real, self.ghost_shift + self.pos)
                } else {
                    let ghost = self.ghost_shift;
                    self.ghost_shift = usize::MAX;
                    self.line -= (char == '\n') as usize;
                    ExactPos::new(self.pos, ghost)
                };

                break Some(Item::new(pos, self.line, Part::Char(char)));
            } else if let Some(last_iter) = self.backup_iter.take() {
                (self.pos, self.chars, self.tags) = last_iter;
            } else {
                break None;
            }
        }
    }
}

#[derive(Debug, Default, Clone)]
enum Conceal<'a> {
    #[default]
    All,
    None,
    Excluding(&'a [Cursor]),
    NotOnLineOf(&'a [Cursor]),
}