duat-core 0.10.0

The core of Duat, a highly customizable text editor.
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
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
//! The functions for iteration of [`Text`]s.
//!
//! These functions will iterate over the text, reverse or forwards,
//! keeping track of characters and [`Tag`]s, sending them in order,
//! while also hiding the existance of certain "meta" tags, namely the
//! [ghost] and [concealment] tags. This allows for a seemless
//! iteration which is especially useful for printing, as the printer
//! only needs to care about [`char`]s and `Tag`s, most of which are
//! just [`Form`] changing `Tag`s
//!
//! [`Tag`]: super::Tag
//! [ghost]: super::Inlay
//! [concealment]: super::Conceal
//! [`Form`]: crate::form::Form
use std::{
    iter::{Chain, Rev},
    str::Chars,
};

use super::{
    Point, SpawnId, Text,
    tags::{self, RawTag},
};
use crate::{
    form::MaskId,
    text::{TwoPoints, tags::InnerTags},
};

/// An [`Iterator`] over the [`TextPart`]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 FwdIter<'t> {
    text: &'t Text,
    point: Point,
    init_point: Point,
    chars: FwdChars<'t>,
    tags: tags::FwdTags<'t>,
    conceals: u32,

    // Things to deal with ghost text.
    main_iter: Option<MainIter<FwdChars<'t>, tags::FwdTags<'t>>>,
    ghost: Option<(Point, usize)>,
}

impl<'t> FwdIter<'t> {
    /// Returns a new forward [`Iterator`] over the [`TextPlace`]s in
    /// the [`Text`].
    #[track_caller]
    pub(super) fn new_at(text: &'t Text, points: TwoPoints, is_ghost: bool) -> Self {
        let TwoPoints { real, ghost } = points;
        let point = real.min(if is_ghost {
            text.last_point()
        } else {
            text.end_point()
        });

        // The second usize argument of ghost is the "distance traversed".
        // When iterating over this starting point, the Tags iterator will
        // still iterate over prior Inlays in the same byte, even if they were
        // supposed to be skipped.
        // The "distance traversed" serves the purpose of skipping those
        // ghosts until the correct one is reached, hence why it starts at 0.
        let ghost = if let Some(offset) = ghost {
            let points = text.ghost_max_points_at(real.byte());
            points.ghost.map(|max| (max.min(offset), 0))
        } else {
            let points = text.ghost_max_points_at(real.byte());
            points.ghost.zip(Some(0))
        };

        Self {
            text,
            point,
            init_point: point,
            chars: buf_chars_fwd(text, point.byte(), is_ghost),
            tags: text.tags_fwd(point.byte(), None),
            conceals: 0,

            main_iter: None,
            ghost,
        }
    }

    ////////// Querying functions

    /// Wether the [`Iterator`] is on a [`Inlay`].
    ///
    /// [`Inlay`]: super::Inlay
    #[inline(always)]
    pub fn is_on_ghost(&self) -> bool {
        self.main_iter.is_some()
    }

    /// Returns the current real and ghost [`Point`]s of the
    /// [`Iterator`].
    #[inline(always)]
    pub fn points(&self) -> TwoPoints {
        if let Some(MainIter { point, .. }) = self.main_iter.as_ref() {
            TwoPoints::new(*point, self.ghost.map(|(tg, _)| tg).unwrap())
        } else {
            TwoPoints::new_after_ghost(self.point)
        }
    }

    /// The [`Text`] that's being iterated over.
    pub fn text(&self) -> &Text {
        self.text
    }

    /// Handles meta [`Tag`]s.
    ///
    /// [`Tag`]: super::Tag
    #[inline(always)]
    fn handle_meta_tag(&mut self, tag: &RawTag, b: usize) -> bool {
        match tag {
            RawTag::Inlay(_, id) => {
                if b < self.point.byte() || self.conceals > 0 {
                    return true;
                }
                let text = self.text.get_ghost(*id).unwrap();

                let (this_ghost, total_ghost) = if let Some((ghost, dist)) = &mut self.ghost {
                    if ghost.byte() >= *dist + text.last_point().byte() {
                        *dist += text.last_point().byte();
                        return true;
                    }
                    (text.point_at_byte(ghost.byte() - *dist), *ghost)
                } else {
                    (Point::default(), Point::default())
                };

                let iter = FwdIter::new_at(text, this_ghost.to_two_points_before(), true);
                let point = std::mem::replace(&mut self.point, this_ghost);
                let init_point = std::mem::replace(&mut self.init_point, this_ghost);
                let chars = std::mem::replace(&mut self.chars, iter.chars);
                let tags = std::mem::replace(&mut self.tags, iter.tags);

                self.ghost = Some((total_ghost, total_ghost.byte()));
                self.main_iter = Some(MainIter { point, init_point, chars, tags });
            }
            RawTag::StartConceal(_) => self.conceals += 1,
            RawTag::EndConceal(_) => {
                self.conceals = self.conceals.saturating_sub(1);
                if self.conceals == 0 {
                    // If we have moved forward and were in a ghost, that ghost is no
                    // longer valid.
                    self.ghost.take_if(|_| self.point.byte() < b);
                    self.point = self.point.max(self.text.point_at_byte(b));
                    self.chars = buf_chars_fwd(self.text, self.point.byte(), false);
                }
            }
            RawTag::ConcealUntil(b) => {
                let point = self.text.point_at_byte(*b as usize);
                *self = FwdIter::new_at(self.text, point.to_two_points_before(), false);
                return false;
            }
            RawTag::Spacer(_) | RawTag::SpawnedWidget(..) | RawTag::Overlay(..)
                if b < self.init_point.byte() => {}
            RawTag::StartToggle(..) | RawTag::EndToggle(..) => {}
            _ => return false,
        }

        true
    }
}

impl<'t> Iterator for FwdIter<'t> {
    type Item = TextPlace<'t>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if let Some((b, tag)) = self
            .tags
            .next_if(|(b, _)| *b <= self.point.byte() || self.conceals > 0)
        {
            if self.handle_meta_tag(&tag, b) {
                self.next()
            } else {
                let tags = &self.text.0.tags;
                Some(TextPlace::new(self.points(), TextPart::from_raw(tags, tag)))
            }
        } else if let Some(char) = self.chars.next() {
            let points = self.points();
            self.point = self.point.fwd(char);

            self.ghost = match self.main_iter {
                Some(..) => self.ghost.map(|(g, d)| (g.fwd(char), d + 1)),
                None => None,
            };

            Some(TextPlace::new(points, TextPart::Char(char)))
        } else if let Some(main_iter) = self.main_iter.take() {
            self.point = main_iter.point;
            self.init_point = main_iter.init_point;
            self.chars = main_iter.chars;
            self.tags = main_iter.tags;

            self.next()
        } else {
            None
        }
    }
}

/// An [`Iterator`] over the [`TextPart`]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<'t> {
    text: &'t Text,
    point: Point,
    init_point: Point,
    chars: RevChars<'t>,
    tags: tags::RevTags<'t>,
    conceals: usize,

    main_iter: Option<MainIter<RevChars<'t>, tags::RevTags<'t>>>,
    ghost: Option<(Point, usize)>,
}

impl<'t> RevIter<'t> {
    /// Returns a new reverse [`Iterator`] over the [`TextPlace`]s in
    /// the [`Text`].
    #[track_caller]
    pub(super) fn new_at(text: &'t Text, points: TwoPoints) -> Self {
        let TwoPoints { real, ghost } = points;
        let point = real.min(text.end_point());

        let ghost = ghost.and_then(|offset| {
            let points = text.ghost_max_points_at(real.byte());
            points.ghost.map(|max| (max.min(offset), max.byte()))
        });

        Self {
            text,
            point,
            init_point: point,
            chars: buf_chars_rev(text, point.byte()),
            tags: text.tags_rev(point.byte(), None),
            conceals: 0,

            main_iter: None,
            ghost,
        }
    }

    ////////// Querying functions

    /// Returns the current real and ghost [`Point`]s.
    pub fn points(&self) -> TwoPoints {
        if let Some(MainIter { point, .. }) = self.main_iter.as_ref() {
            TwoPoints::new(*point, self.point)
        } else if let Some((ghost, _)) = self.ghost {
            TwoPoints::new(self.point, ghost)
        } else {
            TwoPoints::new_after_ghost(self.point)
        }
    }

    /// The [`Text`] that's being iterated over.
    pub fn text(&self) -> &'t Text {
        self.text
    }

    /// Wether the [`Iterator`] is on a [`Inlay`].
    ///
    /// [`Inlay`]: super::Inlay
    pub fn is_on_ghost(&self) -> bool {
        self.main_iter.is_some()
    }

    /// Handles meta [`Tag`]s.
    ///
    /// [`Tag`]: super::Tag
    #[inline]
    fn handled_meta_tag(&mut self, tag: &RawTag, b: usize) -> bool {
        match tag {
            RawTag::Inlay(_, id) => {
                if b > self.point.byte() || self.conceals > 0 {
                    return true;
                }
                let text = self.text.get_ghost(*id).unwrap();

                let (ghost_b, this_ghost) = if let Some((offset, dist)) = &mut self.ghost {
                    if *dist - text.last_point().byte() >= offset.byte() {
                        *dist -= text.last_point().byte();
                        return true;
                    }
                    (
                        text.point_at_byte(offset.byte() + text.last_point().byte() - *dist),
                        *offset,
                    )
                } else {
                    let this = text.last_point();
                    let points = self.text.ghost_max_points_at(b);
                    (this, points.ghost.unwrap())
                };

                let iter = text.iter_rev(ghost_b.to_two_points_before());
                let point = std::mem::replace(&mut self.point, this_ghost);
                let init_point = std::mem::replace(&mut self.init_point, this_ghost);
                let chars = std::mem::replace(&mut self.chars, iter.chars);
                let tags = std::mem::replace(&mut self.tags, iter.tags);

                self.ghost = Some((this_ghost, this_ghost.byte()));
                self.main_iter = Some(MainIter { point, init_point, chars, tags });
            }

            RawTag::StartConceal(_) => {
                self.conceals = self.conceals.saturating_sub(1);
                if self.conceals == 0 {
                    self.ghost.take_if(|_| b < self.point.byte());
                    self.point = self.point.min(self.text.point_at_byte(b));
                    self.chars = buf_chars_rev(self.text, self.point.byte());
                }
            }
            RawTag::EndConceal(_) => self.conceals += 1,
            RawTag::ConcealUntil(b) => {
                let point = self.text.point_at_byte(*b as usize);
                *self = RevIter::new_at(self.text, point.to_two_points_before());
                return false;
            }
            RawTag::Spacer(_) | RawTag::SpawnedWidget(..) | RawTag::Overlay(..)
                if b > self.init_point.byte() => {}
            RawTag::StartToggle(..) | RawTag::EndToggle(..) => {}
            _ => return false,
        }

        true
    }
}

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

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if let Some((b, tag)) = self
            .tags
            .next_if(|(b, _)| *b >= self.point.byte() || self.conceals > 0)
        {
            if self.handled_meta_tag(&tag, b) {
                self.next()
            } else {
                let tags = &self.text.0.tags;
                Some(TextPlace::new(self.points(), TextPart::from_raw(tags, tag)))
            }
        } else if let Some(char) = self.chars.next() {
            self.point = self.point.rev(char);

            self.ghost = match self.main_iter {
                Some(..) => self.ghost.map(|(g, d)| (g.rev(char), d - 1)),
                None => None,
            };

            Some(TextPlace::new(self.points(), TextPart::Char(char)))
        } else if let Some(main_iter) = self.main_iter.take() {
            self.point = main_iter.point;
            self.init_point = main_iter.init_point;
            self.chars = main_iter.chars;
            self.tags = main_iter.tags;

            self.next()
        } else {
            None
        }
    }
}

fn buf_chars_fwd(text: &Text, b: usize, minus_last_nl: bool) -> FwdChars<'_> {
    let [s0, s1] = text
        .slices(b..text.len() - minus_last_nl as usize)
        .map(|s| unsafe { std::str::from_utf8_unchecked(s) });
    s0.chars().chain(s1.chars())
}

fn buf_chars_rev(text: &Text, b: usize) -> RevChars<'_> {
    let [s0, s1] = text
        .slices(..b)
        .map(|s| unsafe { std::str::from_utf8_unchecked(s) });
    s1.chars().rev().chain(s0.chars().rev())
}

/// An element of a [`Text`].
///
/// This struct is comprised of three parts:
///
/// - A real [`Point`], representing a position on the real `Text`;
/// - A ghost `Point`, which is a position in a [`Inlay`], [`None`] if
///   not in a `Inlay`;
/// - A [`TextPart`], which will either be a `char` or a [`Tag`];
///
/// [`Inlay`]: super::Inlay
/// [`Tag`]: super::Tag
#[derive(Debug, Clone, Copy)]
pub struct TextPlace<'t> {
    /// The real [`Point`].
    pub real: Point,
    /// The [`Point`] in a [`Inlay`].
    ///
    /// If there are multiple `Inlay`s in the same character, this
    /// `Point` will point to a sum of the previous [`Text`]'s
    /// [lengths] plus the position on this specific `Inlay`, so
    /// every `Point` should point to a specific position in a char.
    ///
    /// [`Inlay`]: super::Inlay
    /// [lengths]: super::Strs::len
    pub ghost: Option<Point>,
    /// A [`TextPart`], which will either be a `char` or a [`Tag`];
    ///
    /// [`Tag`]: super::Tag
    pub part: TextPart<'t>,
}

impl<'t> TextPlace<'t> {
    /// Returns a new [`TextPlace`].
    #[inline]
    const fn new(points: TwoPoints, part: TextPart<'t>) -> Self {
        let TwoPoints { real, ghost } = points;
        Self { real, ghost, part }
    }

    /// Whether this [`TextPlace`] is in a [`Inlay`].
    ///
    /// [`Inlay`]: super::Inlay
    pub const fn is_real(&self) -> bool {
        self.ghost.is_none()
    }

    /// Returns the real position, if not on a [`Inlay`].
    ///
    /// [`Inlay`]: super::Inlay
    pub const fn as_real_char(self) -> Option<(Point, char)> {
        let Some(char) = self.part.as_char() else {
            return None;
        };
        if self.ghost.is_none() {
            Some((self.real, char))
        } else {
            None
        }
    }

    /// The real [byte](Point::byte).
    pub const fn byte(&self) -> usize {
        self.real.byte()
    }

    /// The real [char](Point::char).
    pub const fn char(&self) -> usize {
        self.real.char()
    }

    /// The real [line](Point::line).
    pub const fn line(&self) -> usize {
        self.real.line()
    }

    /// The real and ghost [`Point`]s, can be used as [`TwoPoints`].
    pub const fn points(&self) -> TwoPoints {
        if let Some(ghost) = self.ghost {
            TwoPoints::new(self.real, ghost)
        } else {
            TwoPoints::new_after_ghost(self.real)
        }
    }
}

type FwdChars<'t> = Chain<Chars<'t>, Chars<'t>>;
type RevChars<'t> = Chain<Rev<Chars<'t>>, Rev<Chars<'t>>>;

use crate::form::FormId;

/// A part of the [`Text`], can be a [`char`] or a [`Tag`].
///
/// This type is used in iteration by [Ui]s in order to
/// correctly print Duat's content. Additionally, you may be
/// able to tell that there is no ghost text or concealment
/// tags, and there is a [`ResetState`].
///
/// That is because the [`Text`]'s iteration process automatically
/// gets rid of these tags, since, from the point of view of the
/// ui, ghost text is just regular text, while conceals are
/// simply the lack of text. And if the ui can handle printing
/// regular text, printing ghost text should be a breeze.
///
/// [`Text`]: super::Text
/// [`Tag`]: super::Tag
/// [Ui]: crate::ui::traits::RawUi
/// [`ResetState`]: Part::ResetState
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[doc(hidden)]
pub enum TextPart<'t> {
    /// A printed `char`, can be real or a [`Inlay`].
    ///
    /// [`Inlay`]: super::Inlay
    Char(char),
    /// Push a [`Form`] to the [`Painter`].
    ///
    /// [`Form`]: crate::form::Form
    /// [`Painter`]: crate::form::Painter
    PushForm(FormId, u8),
    /// Pop a [`Form`] from the [`Painter`].
    ///
    /// [`Form`]: crate::form::Form
    /// [`Painter`]: crate::form::Painter
    PopForm(FormId),
    /// Add a [`Spacer`].
    ///
    /// [`Spacer`]: super::Spacer
    Spacer,
    /// An inlay [`Text`].
    Overlay(&'t Text),
    /// A spawned [`Widget`].
    ///
    /// [`Widget`]: crate::ui::Widget
    SpawnedWidget(SpawnId),
    /// Push a mask to the [`Painter`], which can map [`Form`]s given
    /// a suffix.
    ///
    /// [`Form`]: crate::form::Form
    /// [`Painter`]: crate::form::Painter
    PushMask(MaskId),
    /// Pop a mask from the [`Painter`].
    PopMask(MaskId),
    /// Resets all [`FormId`]s, [`ToggleId`]s and alignments.
    ///
    /// Used when a [`Conceal`] covers a large region, which Duat
    /// optimizes by just not iterating over the [`TextPart`]s within.
    /// This could skip some [`Tag`]s, so this variant serves the
    /// purpose of terminating or initiating in place of skipped
    /// [`Tag`]s.
    ///
    /// This variant does not actually represent any [`Tag`].
    ///
    /// [`Conceal`]: super::Conceal
    /// [`Tag`]: super::Tag
    ResetState,
}

impl<'t> TextPart<'t> {
    /// Returns a new [`TextPart`] from a [`RawTag`].
    #[inline]
    pub(super) fn from_raw(tags: &'t InnerTags, value: RawTag) -> Self {
        match value {
            RawTag::PushForm(_, id, prio) => Self::PushForm(id, prio),
            RawTag::PopForm(_, id) => Self::PopForm(id),
            RawTag::Spacer(_) => Self::Spacer,
            RawTag::ConcealUntil(_) => Self::ResetState,
            RawTag::SpawnedWidget(_, id) => Self::SpawnedWidget(id),
            RawTag::Overlay(_, id) => Self::Overlay(tags.get_ghost(id).unwrap()),
            RawTag::PushMask(_, id) => Self::PushMask(id),
            RawTag::PopMask(_, id) => Self::PopMask(id),
            RawTag::StartConceal(_)
            | RawTag::EndConceal(_)
            | RawTag::Inlay(..)
            | RawTag::StartToggle(..)
            | RawTag::EndToggle(..) => {
                unreachable!("These tags are automatically processed elsewhere.")
            }
        }
    }

    /// Returns `true` if the part is [`Char`].
    ///
    /// [`Char`]: TextPart::Char
    #[must_use]
    #[inline]
    pub const fn is_char(&self) -> bool {
        matches!(self, TextPart::Char(_))
    }

    /// Returns `true` if the part is not [`Char`].
    ///
    /// [`Char`]: TextPart::Char
    #[inline]
    pub const fn is_tag(&self) -> bool {
        !self.is_char()
    }

    /// Returns [`Some`] if the part is [`Char`].
    ///
    /// [`Char`]: TextPart::Char
    #[inline]
    pub const fn as_char(&self) -> Option<char> {
        if let Self::Char(v) = self {
            Some(*v)
        } else {
            None
        }
    }
}

#[derive(Debug, Clone)]
struct MainIter<Chars, Tags> {
    point: Point,
    init_point: Point,
    chars: Chars,
    tags: Tags,
}