text-editing 0.2.2

A simple string with utilities for editing
Documentation
#![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());
    /// ```
    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();
        }
    }

    /// 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!");
    /// ```
    pub fn from_string(text: String) -> Self {
        let mut result = Self {
            text,
            indices: Vec::new(),
        };
        result.refresh_indices();
        result
    }

    /// Checks if the line is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use text_editing::TextLine;
    ///
    /// let line = TextLine::new();
    /// assert!(line.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.text.is_empty()
    }

    /// Returns the length of the text line.
    ///
    /// # Examples
    ///
    /// ```
    /// use text_editing::TextLine;
    ///
    /// let line = TextLine::from_string("Hello, world!".into());
    /// assert_eq!(line.len(), 13);
    /// ```
    pub 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!");
    /// ```
    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);
    /// ```
    pub fn string_index(&self, index: usize) -> usize {
        if !self.indices.is_empty() && index > 0 {
            self.indices[index - 1] + index
        } else {
            index
        }
    }

    /// Returns the char at the specified position.
    ///
    /// # Panics
    ///
    /// Panics if the position is out of bounds.
    ///
    /// # Examples
    ///
    /// ```
    /// use text_editing::TextLine;
    ///
    /// let line = TextLine::from_string("Hello, world!".into());
    /// assert_eq!(line.char_at(7), 'w');
    /// ```
    pub fn char_at(&self, at: usize) -> char {
        self.char_at_checked(at).unwrap()
    }

    fn char_at_checked(&self, at: usize) -> Option<char> {
        self.text[self.string_index(at)..].chars().next()
    }

    /// Inserts a new char into the text line.
    ///
    /// # 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);
        self.indices.clear();
        self.refresh_indices();
    }

    /// Removes a char from the text line and returns it.
    ///
    /// # 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));
        self.indices.clear();
        self.refresh_indices();
        result
    }

    /// Removes the specified range from the text line.
    ///
    /// # 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),
            "",
        );
        self.indices.clear();
        self.refresh_indices();
    }

    /// 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!");
    /// ```
    pub fn split(&mut self, index: usize) -> Self {
        let mut result = Self {
            text: self.text.split_off(self.string_index(index)),
            indices: Vec::new(),
        };
        self.indices.clear();
        self.refresh_indices();
        result.refresh_indices();
        result
    }

    /// 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);
        self.indices.clear();
        self.refresh_indices();
    }
}

impl FromStr for TextLine {
    type Err = Infallible;

    fn from_str(text: &str) -> Result<Self, Infallible> {
        Ok(Self::from_string(text.to_string()))
    }
}

impl Display for TextLine {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

impl From<String> for TextLine {
    fn from(text: String) -> Self {
        Self::from_string(text)
    }
}

impl From<TextLine> for String {
    fn from(text_line: TextLine) -> Self {
        text_line.text
    }
}

mod cursor;
mod editing;

pub use cursor::Direction;