#![deny(missing_docs)]
use std::{
convert::Infallible,
fmt::{Display, Formatter},
ops::Range,
str::FromStr,
};
#[derive(Clone, Default)]
pub struct TextLine {
text: String,
indices: Vec<usize>,
}
impl TextLine {
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();
}
}
pub fn from_string(text: String) -> Self {
let mut result = Self {
text,
indices: Vec::new(),
};
result.refresh_indices();
result
}
pub fn is_empty(&self) -> bool {
self.text.is_empty()
}
pub fn len(&self) -> usize {
if self.indices.is_empty() {
self.text.len()
} else {
self.indices.len()
}
}
pub fn as_str(&self) -> &str {
&self.text
}
pub fn string_index(&self, index: usize) -> usize {
if !self.indices.is_empty() && index > 0 {
self.indices[index - 1] + index
} else {
index
}
}
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()
}
pub fn insert(&mut self, index: usize, c: char) {
self.text.insert(self.string_index(index), c);
self.indices.clear();
self.refresh_indices();
}
pub fn remove(&mut self, index: usize) -> char {
let result = self.text.remove(self.string_index(index));
self.indices.clear();
self.refresh_indices();
result
}
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();
}
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
}
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;