rat_text/
lib.rs

1#![doc = include_str!("../readme.md")]
2#![allow(clippy::uninlined_format_args)]
3use std::error::Error;
4use std::fmt::{Debug, Display, Formatter};
5use std::ops::Range;
6
7pub mod clipboard;
8#[cfg(feature = "palette")]
9pub mod color_input;
10pub mod date_input;
11pub mod line_number;
12pub mod number_input;
13pub mod text_area;
14pub mod text_input;
15pub mod text_input_mask;
16pub mod undo_buffer;
17
18mod cache;
19mod glyph2;
20mod grapheme;
21mod range_map;
22mod text_core;
23mod text_store;
24
25pub use grapheme::Grapheme;
26
27use crate::_private::NonExhaustive;
28pub use pure_rust_locales::Locale;
29pub use rat_cursor::{HasScreenCursor, impl_screen_cursor, screen_cursor};
30use rat_scrolled::ScrollStyle;
31use ratatui::style::Style;
32use ratatui::widgets::Block;
33
34pub mod event {
35    //!
36    //! Event-handler traits and Keybindings.
37    //!
38
39    pub use rat_event::*;
40
41    /// Runs only the navigation events, not any editing.
42    #[derive(Debug)]
43    pub struct ReadOnly;
44
45    /// Result of event handling.
46    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
47    pub enum TextOutcome {
48        /// The given event has not been used at all.
49        Continue,
50        /// The event has been recognized, but the result was nil.
51        /// Further processing for this event may stop.
52        Unchanged,
53        /// The event has been recognized and there is some change
54        /// due to it.
55        /// Further processing for this event may stop.
56        /// Rendering the ui is advised.
57        Changed,
58        /// Text content has changed.
59        TextChanged,
60    }
61
62    impl ConsumedEvent for TextOutcome {
63        fn is_consumed(&self) -> bool {
64            *self != TextOutcome::Continue
65        }
66    }
67
68    // Useful for converting most navigation/edit results.
69    impl From<bool> for TextOutcome {
70        fn from(value: bool) -> Self {
71            if value {
72                TextOutcome::Changed
73            } else {
74                TextOutcome::Unchanged
75            }
76        }
77    }
78
79    impl From<Outcome> for TextOutcome {
80        fn from(value: Outcome) -> Self {
81            match value {
82                Outcome::Continue => TextOutcome::Continue,
83                Outcome::Unchanged => TextOutcome::Unchanged,
84                Outcome::Changed => TextOutcome::Changed,
85            }
86        }
87    }
88
89    impl From<TextOutcome> for Outcome {
90        fn from(value: TextOutcome) -> Self {
91            match value {
92                TextOutcome::Continue => Outcome::Continue,
93                TextOutcome::Unchanged => Outcome::Unchanged,
94                TextOutcome::Changed => Outcome::Changed,
95                TextOutcome::TextChanged => Outcome::Changed,
96            }
97        }
98    }
99}
100
101/// This flag sets the behaviour of the widget when
102/// it detects that it gained focus.
103///
104/// Available for all text-input widgets except TextArea.
105#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
106pub enum TextFocusGained {
107    /// None
108    None,
109    /// Editing overwrites the current content.
110    /// Any movement resets this flag and allows editing.
111    #[default]
112    Overwrite,
113    /// Select all text on focus gain.
114    SelectAll,
115}
116
117/// This flag sets the behaviour of the widget when
118/// it detects that it lost focus.
119///
120/// Available for all text-input widgets except TextArea.
121#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
122pub enum TextFocusLost {
123    /// None
124    None,
125    /// Sets the offset to 0. This prevents strangely clipped
126    /// text for long inputs.
127    #[default]
128    Position0,
129}
130
131/// This flag sets the behaviour of the widget when
132/// Tab/BackTab is pressed.
133///
134/// Available for MaskedInput.
135#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
136pub enum TextTab {
137    /// Tab jumps to the next section of the masked input.
138    #[default]
139    MoveToNextSection,
140    /// Tab behaves regular and jumps to the next widget.
141    MoveToNextWidget,
142}
143
144/// Combined style for the widget.
145#[derive(Debug, Clone)]
146pub struct TextStyle {
147    pub style: Style,
148    pub scroll: Option<ScrollStyle>,
149    pub block: Option<Block<'static>>,
150    pub border_style: Option<Style>,
151    pub title_style: Option<Style>,
152    pub focus: Option<Style>,
153    pub select: Option<Style>,
154    pub invalid: Option<Style>,
155
156    /// Focus behaviour.
157    pub on_focus_gained: Option<TextFocusGained>,
158    /// Focus behaviour.
159    pub on_focus_lost: Option<TextFocusLost>,
160    /// Tab behaviour.
161    pub on_tab: Option<TextTab>,
162
163    pub non_exhaustive: NonExhaustive,
164}
165
166impl Default for TextStyle {
167    fn default() -> Self {
168        Self {
169            style: Default::default(),
170            scroll: Default::default(),
171            block: Default::default(),
172            border_style: Default::default(),
173            title_style: Default::default(),
174            focus: Default::default(),
175            select: Default::default(),
176            invalid: Default::default(),
177            on_focus_gained: Default::default(),
178            on_focus_lost: Default::default(),
179            on_tab: Default::default(),
180            non_exhaustive: NonExhaustive,
181        }
182    }
183}
184
185pub mod core {
186    //!
187    //! Core structs for text-editing.
188    //! Used to implement the widgets.
189    //!
190
191    pub use crate::text_core::TextCore;
192    pub use crate::text_core::core_op;
193    pub use crate::text_store::SkipLine;
194    pub use crate::text_store::TextStore;
195    pub use crate::text_store::text_rope::TextRope;
196    pub use crate::text_store::text_string::TextString;
197}
198
199#[derive(Debug, PartialEq)]
200pub enum TextError {
201    /// Invalid text.
202    InvalidText(String),
203    /// Clipboard error occurred.
204    Clipboard,
205    /// Indicates that the passed text-range was out of bounds.
206    TextRangeOutOfBounds(TextRange),
207    /// Indicates that the passed text-position was out of bounds.
208    TextPositionOutOfBounds(TextPosition),
209    /// Indicates that the passed line index was out of bounds.
210    ///
211    /// Contains the index attempted and the actual length of the
212    /// `Rope`/`RopeSlice` in lines, in that order.
213    LineIndexOutOfBounds(upos_type, upos_type),
214    /// Column index is out of bounds.
215    ColumnIndexOutOfBounds(upos_type, upos_type),
216    /// Indicates that the passed byte index was out of bounds.
217    ///
218    /// Contains the index attempted and the actual length of the
219    /// `Rope`/`RopeSlice` in bytes, in that order.
220    ByteIndexOutOfBounds(usize, usize),
221    /// Indicates that the passed char index was out of bounds.
222    ///
223    /// Contains the index attempted and the actual length of the
224    /// `Rope`/`RopeSlice` in chars, in that order.
225    CharIndexOutOfBounds(usize, usize),
226    /// out of bounds.
227    ///
228    /// Contains the [start, end) byte indices of the range and the actual
229    /// length of the `Rope`/`RopeSlice` in bytes, in that order.  When
230    /// either the start or end are `None`, that indicates a half-open range.
231    ByteRangeOutOfBounds(Option<usize>, Option<usize>, usize),
232    /// Indicates that the passed char-index range was partially or fully
233    /// out of bounds.
234    ///
235    /// Contains the [start, end) char indices of the range and the actual
236    /// length of the `Rope`/`RopeSlice` in chars, in that order.  When
237    /// either the start or end are `None`, that indicates a half-open range.
238    CharRangeOutOfBounds(Option<usize>, Option<usize>, usize),
239    /// Indicates that the passed byte index was not a char boundary.
240    ///
241    /// Contains the passed byte index.
242    ByteIndexNotCharBoundary(usize),
243    /// Indicates that the passed byte range didn't line up with char
244    /// boundaries.
245    ///
246    /// Contains the [start, end) byte indices of the range, in that order.
247    /// When either the start or end are `None`, that indicates a half-open
248    /// range.
249    ByteRangeNotCharBoundary(
250        Option<usize>, // Start.
251        Option<usize>, // End.
252    ),
253    /// Indicates that a reversed byte-index range (end < start) was
254    /// encountered.
255    ///
256    /// Contains the [start, end) byte indices of the range, in that order.
257    ByteRangeInvalid(
258        usize, // Start.
259        usize, // End.
260    ),
261    /// Indicates that a reversed char-index range (end < start) was
262    /// encountered.
263    ///
264    /// Contains the [start, end) char indices of the range, in that order.
265    CharRangeInvalid(
266        usize, // Start.
267        usize, // End.
268    ),
269    /// Invalid regex for search.
270    InvalidSearch,
271}
272
273impl Display for TextError {
274    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
275        write!(f, "{:?}", self)
276    }
277}
278
279impl Error for TextError {}
280
281/// Row/Column type.
282#[allow(non_camel_case_types)]
283pub type upos_type = u32;
284/// Row/Column type.
285#[allow(non_camel_case_types)]
286pub type ipos_type = i32;
287
288/// Text position.
289#[derive(Default, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Hash)]
290pub struct TextPosition {
291    pub y: upos_type,
292    pub x: upos_type,
293}
294
295impl TextPosition {
296    /// New position.
297    pub const fn new(x: upos_type, y: upos_type) -> TextPosition {
298        Self { y, x }
299    }
300}
301
302impl Debug for TextPosition {
303    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
304        write!(f, "{}|{}", self.x, self.y)
305    }
306}
307
308impl From<(upos_type, upos_type)> for TextPosition {
309    fn from(value: (upos_type, upos_type)) -> Self {
310        Self {
311            y: value.1,
312            x: value.0,
313        }
314    }
315}
316
317impl From<TextPosition> for (upos_type, upos_type) {
318    fn from(value: TextPosition) -> Self {
319        (value.x, value.y)
320    }
321}
322
323// TODO: replace with standard Range.
324/// Exclusive range for text ranges.
325#[derive(Default, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Hash)]
326pub struct TextRange {
327    /// column, row
328    pub start: TextPosition,
329    /// column, row
330    pub end: TextPosition,
331}
332
333impl Debug for TextRange {
334    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
335        write!(
336            f,
337            "{}|{}-{}|{}",
338            self.start.x, self.start.y, self.end.x, self.end.y
339        )
340    }
341}
342
343impl From<Range<TextPosition>> for TextRange {
344    fn from(value: Range<TextPosition>) -> Self {
345        assert!(value.start <= value.end);
346        Self {
347            start: value.start,
348            end: value.end,
349        }
350    }
351}
352
353impl From<Range<(upos_type, upos_type)>> for TextRange {
354    fn from(value: Range<(upos_type, upos_type)>) -> Self {
355        Self {
356            start: TextPosition::from(value.start),
357            end: TextPosition::from(value.end),
358        }
359    }
360}
361
362impl From<TextRange> for Range<TextPosition> {
363    fn from(value: TextRange) -> Self {
364        value.start..value.end
365    }
366}
367
368impl TextRange {
369    /// Maximum text range.
370    pub const MAX: TextRange = TextRange {
371        start: TextPosition {
372            y: upos_type::MAX,
373            x: upos_type::MAX,
374        },
375        end: TextPosition {
376            y: upos_type::MAX,
377            x: upos_type::MAX,
378        },
379    };
380
381    /// New text range.
382    ///
383    /// Panic
384    /// Panics if start > end.
385    pub fn new(start: impl Into<TextPosition>, end: impl Into<TextPosition>) -> Self {
386        let start = start.into();
387        let end = end.into();
388
389        assert!(start <= end);
390
391        TextRange { start, end }
392    }
393
394    /// Empty range
395    #[inline]
396    pub fn is_empty(&self) -> bool {
397        self.start == self.end
398    }
399
400    /// Range contains the given position.
401    #[inline]
402    pub fn contains_pos(&self, pos: impl Into<TextPosition>) -> bool {
403        let pos = pos.into();
404        pos >= self.start && pos < self.end
405    }
406
407    /// Range fully before the given position.
408    #[inline]
409    pub fn before_pos(&self, pos: impl Into<TextPosition>) -> bool {
410        let pos = pos.into();
411        pos >= self.end
412    }
413
414    /// Range fully after the given position.
415    #[inline]
416    pub fn after_pos(&self, pos: impl Into<TextPosition>) -> bool {
417        let pos = pos.into();
418        pos < self.start
419    }
420
421    /// Range contains the other range.
422    #[inline(always)]
423    pub fn contains(&self, other: TextRange) -> bool {
424        other.start >= self.start && other.end <= self.end
425    }
426
427    /// Range before the other range.
428    #[inline(always)]
429    pub fn before(&self, other: TextRange) -> bool {
430        other.start > self.end
431    }
432
433    /// Range after the other range.
434    #[inline(always)]
435    pub fn after(&self, other: TextRange) -> bool {
436        other.end < self.start
437    }
438
439    /// Range overlaps with other range.
440    #[inline(always)]
441    pub fn intersects(&self, other: TextRange) -> bool {
442        other.start <= self.end && other.end >= self.start
443    }
444
445    /// Return the modified value range, that accounts for a
446    /// text insertion of range.
447    #[inline]
448    pub fn expand(&self, range: TextRange) -> TextRange {
449        TextRange::new(self.expand_pos(range.start), self.expand_pos(range.end))
450    }
451
452    /// Return the modified position, that accounts for a
453    /// text insertion of range.
454    #[inline]
455    pub fn expand_pos(&self, pos: TextPosition) -> TextPosition {
456        let delta_lines = self.end.y - self.start.y;
457
458        // swap x and y to enable tuple comparison
459        if pos < self.start {
460            pos
461        } else if pos == self.start {
462            self.end
463        } else {
464            if pos.y > self.start.y {
465                TextPosition::new(pos.x, pos.y + delta_lines)
466            } else if pos.y == self.start.y {
467                if pos.x >= self.start.x {
468                    TextPosition::new(pos.x - self.start.x + self.end.x, pos.y + delta_lines)
469                } else {
470                    pos
471                }
472            } else {
473                pos
474            }
475        }
476    }
477
478    /// Return the modified value range, that accounts for a
479    /// text deletion of range.
480    #[inline]
481    pub fn shrink(&self, range: TextRange) -> TextRange {
482        TextRange::new(self.shrink_pos(range.start), self.shrink_pos(range.end))
483    }
484
485    /// Return the modified position, that accounts for a
486    /// text deletion of the range.
487    #[inline]
488    pub fn shrink_pos(&self, pos: TextPosition) -> TextPosition {
489        let delta_lines = self.end.y - self.start.y;
490
491        // swap x and y to enable tuple comparison
492        if pos < self.start {
493            pos
494        } else if pos >= self.start && pos <= self.end {
495            self.start
496        } else {
497            // after row
498            if pos.y > self.end.y {
499                TextPosition::new(pos.x, pos.y - delta_lines)
500            } else if pos.y == self.end.y {
501                if pos.x >= self.end.x {
502                    TextPosition::new(pos.x - self.end.x + self.start.x, pos.y - delta_lines)
503                } else {
504                    pos
505                }
506            } else {
507                pos
508            }
509        }
510    }
511}
512
513/// Trait for a cursor (akin to an Iterator, not the blinking thing).
514///
515/// This is not a [DoubleEndedIterator] which can iterate from both ends of
516/// the iterator, but moves a cursor forward/back over the collection.
517pub trait Cursor: Iterator {
518    /// Return the previous item.
519    fn prev(&mut self) -> Option<Self::Item>;
520
521    /// Peek next.
522    fn peek_next(&mut self) -> Option<Self::Item> {
523        let v = self.next();
524        self.prev();
525        v
526    }
527
528    /// Peek prev.
529    fn peek_prev(&mut self) -> Option<Self::Item> {
530        let v = self.prev();
531        self.next();
532        v
533    }
534
535    /// Offset of the current cursor position into the underlying text.
536    fn text_offset(&self) -> usize;
537}
538
539mod _private {
540    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
541    pub struct NonExhaustive;
542}