use std::collections::HashMap;
use std::fmt;
use std::ops::{Range, RangeInclusive};
use crate::error::{GuiError, GuiResult};
use crate::events::UiEvent;
use crate::ui::{Backend, Ui};
use crate::widgets::{Color, TextRun, TextStyle, WidgetKind};
use crate::WidgetId;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StyledTextError {
InvalidRange {
start: usize,
end: usize,
len: usize,
},
InvalidLine {
line: usize,
line_count: usize,
},
UnknownStyle(StyleId),
UnknownMarker(MarkerId),
UnknownIndicator(IndicatorId),
ReadOnly,
EmbeddedNul,
}
impl fmt::Display for StyledTextError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
StyledTextError::InvalidRange { start, end, len } => {
write!(
f,
"range {start}..{end} is not valid for a text of length {len}"
)
}
StyledTextError::InvalidLine { line, line_count } => {
write!(f, "line {line} does not exist ({line_count} lines)")
}
StyledTextError::UnknownStyle(id) => write!(f, "unknown style {}", id.0),
StyledTextError::UnknownMarker(id) => write!(f, "unknown marker {}", id.0),
StyledTextError::UnknownIndicator(id) => write!(f, "unknown indicator {}", id.0),
StyledTextError::ReadOnly => write!(f, "the document is read-only"),
StyledTextError::EmbeddedNul => write!(f, "text cannot contain NUL"),
}
}
}
impl std::error::Error for StyledTextError {}
impl From<StyledTextError> for GuiError {
fn from(error: StyledTextError) -> Self {
GuiError::StyledText(error)
}
}
pub type StyledTextResult<T> = Result<T, StyledTextError>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct StyleId(pub u16);
impl StyleId {
pub const DEFAULT: StyleId = StyleId(0);
}
#[derive(Debug, Clone, PartialEq)]
pub struct StyleTable {
styles: Vec<(String, TextStyle)>,
}
impl Default for StyleTable {
fn default() -> Self {
Self::new()
}
}
impl StyleTable {
pub fn new() -> Self {
Self {
styles: vec![("default".to_owned(), TextStyle::new())],
}
}
pub fn define(&mut self, name: &str, style: TextStyle) -> StyleId {
if let Some(id) = self.id_of(name) {
self.styles[id.0 as usize].1 = style;
return id;
}
if self.styles.len() >= u16::MAX as usize {
let last = self.styles.len() - 1;
self.styles[last] = (name.to_owned(), style);
return StyleId(last as u16);
}
self.styles.push((name.to_owned(), style));
StyleId((self.styles.len() - 1) as u16)
}
pub fn set(&mut self, id: StyleId, style: TextStyle) -> StyledTextResult<()> {
let slot = self
.styles
.get_mut(id.0 as usize)
.ok_or(StyledTextError::UnknownStyle(id))?;
slot.1 = style;
Ok(())
}
pub fn id_of(&self, name: &str) -> Option<StyleId> {
self.styles
.iter()
.position(|(existing, _)| existing == name)
.map(|index| StyleId(index as u16))
}
pub fn id_or_default(&self, name: &str) -> StyleId {
self.id_of(name).unwrap_or(StyleId::DEFAULT)
}
pub fn get(&self, id: StyleId) -> Option<&TextStyle> {
self.styles.get(id.0 as usize).map(|(_, style)| style)
}
pub fn name(&self, id: StyleId) -> Option<&str> {
self.styles
.get(id.0 as usize)
.map(|(name, _)| name.as_str())
}
pub fn len(&self) -> usize {
self.styles.len()
}
pub fn is_empty(&self) -> bool {
false
}
}
pub trait StyledTextLexer: Send {
fn name(&self) -> &str;
fn default_styles(&self) -> Vec<(&'static str, TextStyle)> {
Vec::new()
}
fn lex(&self, text: &str, styles: &StyleTable) -> Vec<(Range<usize>, StyleId)>;
}
#[derive(Debug, Clone, Copy, Default)]
pub struct PlainLexer;
impl StyledTextLexer for PlainLexer {
fn name(&self) -> &str {
"plain"
}
fn lex(&self, _text: &str, _styles: &StyleTable) -> Vec<(Range<usize>, StyleId)> {
Vec::new()
}
}
const KEYWORD_COLOR: Color = Color::rgb(0x3b, 0x5f, 0xc8);
const COMMENT_COLOR: Color = Color::rgb(0x5a, 0x8a, 0x48);
const STRING_COLOR: Color = Color::rgb(0xb3, 0x52, 0x1e);
const NUMBER_COLOR: Color = Color::rgb(0x0e, 0x86, 0x6b);
const TYPE_COLOR: Color = Color::rgb(0x1f, 0x7a, 0x96);
const MACRO_COLOR: Color = Color::rgb(0x8a, 0x45, 0xc0);
const ATTRIBUTE_COLOR: Color = Color::rgb(0x80, 0x80, 0x80);
#[derive(Debug, Clone, Copy, Default)]
pub struct RustLexer;
const RUST_KEYWORDS: &[&str] = &[
"as", "async", "await", "break", "const", "continue", "crate", "dyn", "else", "enum", "extern",
"false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub",
"ref", "return", "self", "Self", "static", "struct", "super", "trait", "true", "type",
"unsafe", "use", "where", "while", "yield",
];
const RUST_PRIMITIVES: &[&str] = &[
"bool", "char", "str", "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64",
"i128", "isize", "f32", "f64",
];
fn is_ident_byte(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || byte == b'_' || byte >= 0x80
}
fn skip_quoted(bytes: &[u8], start: usize) -> usize {
let mut i = start + 1;
while i < bytes.len() {
match bytes[i] {
b'\\' => i += 2,
b'"' => return i + 1,
_ => i += 1,
}
}
bytes.len()
}
fn skip_char_literal(text: &str, start: usize) -> Option<usize> {
let bytes = text.as_bytes();
if bytes.get(start + 1) == Some(&b'\\') {
let mut j = start + 2;
while j < bytes.len() && bytes[j] != b'\'' && bytes[j] != b'\n' {
j += 1;
}
return (bytes.get(j) == Some(&b'\'')).then_some(j + 1);
}
let ch = text.get(start + 1..)?.chars().next()?;
let close = start + 1 + ch.len_utf8();
(ch != '\'' && bytes.get(close) == Some(&b'\'')).then_some(close + 1)
}
impl StyledTextLexer for RustLexer {
fn name(&self) -> &str {
"rust"
}
fn default_styles(&self) -> Vec<(&'static str, TextStyle)> {
vec![
(
"keyword",
TextStyle::new().fg_color(KEYWORD_COLOR).bold(true),
),
(
"comment",
TextStyle::new().fg_color(COMMENT_COLOR).italic(true),
),
("string", TextStyle::new().fg_color(STRING_COLOR)),
("number", TextStyle::new().fg_color(NUMBER_COLOR)),
("type", TextStyle::new().fg_color(TYPE_COLOR)),
("macro", TextStyle::new().fg_color(MACRO_COLOR)),
("attribute", TextStyle::new().fg_color(ATTRIBUTE_COLOR)),
(
"lifetime",
TextStyle::new().fg_color(STRING_COLOR).italic(true),
),
]
}
fn lex(&self, text: &str, styles: &StyleTable) -> Vec<(Range<usize>, StyleId)> {
let bytes = text.as_bytes();
let n = bytes.len();
let mut out = Vec::new();
let mut push = |range: Range<usize>, name: &str| {
out.push((range, styles.id_or_default(name)));
};
let mut i = 0;
while i < n {
let c = bytes[i];
let next = bytes.get(i + 1).copied();
if c == b'/' && next == Some(b'/') {
let start = i;
while i < n && bytes[i] != b'\n' {
i += 1;
}
push(start..i, "comment");
continue;
}
if c == b'/' && next == Some(b'*') {
let start = i;
i += 2;
let mut depth = 1;
while i < n && depth > 0 {
if bytes[i] == b'/' && bytes.get(i + 1) == Some(&b'*') {
depth += 1;
i += 2;
} else if bytes[i] == b'*' && bytes.get(i + 1) == Some(&b'/') {
depth -= 1;
i += 2;
} else {
i += 1;
}
}
i = i.min(n);
push(start..i, "comment");
continue;
}
if c == b'"' {
let start = i;
i = skip_quoted(bytes, i);
push(start..i, "string");
continue;
}
if c == b'r' || c == b'b' {
let start = i;
let mut j = i;
if bytes[j] == b'b' {
j += 1;
}
if bytes.get(j) == Some(&b'r') {
let mut k = j + 1;
let mut hashes = 0;
while bytes.get(k) == Some(&b'#') {
hashes += 1;
k += 1;
}
if bytes.get(k) == Some(&b'"') {
k += 1;
let end = loop {
if k >= n {
break n;
}
if bytes[k] == b'"'
&& k + hashes < n
&& bytes[k + 1..=k + hashes].iter().all(|b| *b == b'#')
{
break k + 1 + hashes;
}
k += 1;
};
push(start..end, "string");
i = end;
continue;
}
} else if j > i && bytes.get(j) == Some(&b'"') {
i = skip_quoted(bytes, j);
push(start..i, "string");
continue;
} else if j > i && bytes.get(j) == Some(&b'\'') {
if let Some(end) = skip_char_literal(text, j) {
push(start..end, "string");
i = end;
continue;
}
}
}
if c == b'\'' {
if let Some(end) = skip_char_literal(text, i) {
push(i..end, "string");
i = end;
continue;
}
let mut j = i + 1;
while j < n && is_ident_byte(bytes[j]) {
j += 1;
}
if j > i + 1 {
push(i..j, "lifetime");
i = j;
} else {
i += 1;
}
continue;
}
if c == b'#'
&& (next == Some(b'[') || (next == Some(b'!') && bytes.get(i + 2) == Some(&b'[')))
{
let start = i;
let mut depth = 0;
while i < n && bytes[i] != b'\n' {
if bytes[i] == b'[' {
depth += 1;
} else if bytes[i] == b']' {
depth -= 1;
if depth == 0 {
i += 1;
break;
}
}
i += 1;
}
push(start..i, "attribute");
continue;
}
if c.is_ascii_digit() {
let start = i;
while i < n
&& (bytes[i].is_ascii_alphanumeric()
|| bytes[i] == b'_'
|| (bytes[i] == b'.' && bytes.get(i + 1).is_some_and(u8::is_ascii_digit)))
{
i += 1;
}
push(start..i, "number");
continue;
}
if is_ident_byte(c) {
let start = i;
while i < n && is_ident_byte(bytes[i]) {
i += 1;
}
let word = &text[start..i];
let keyword = RUST_KEYWORDS.contains(&word);
if !keyword && bytes.get(i) == Some(&b'!') && bytes.get(i + 1) != Some(&b'=') {
push(start..i + 1, "macro");
i += 1;
} else if keyword {
push(start..i, "keyword");
} else if RUST_PRIMITIVES.contains(&word)
|| word.chars().next().is_some_and(char::is_uppercase)
{
push(start..i, "type");
}
continue;
}
i += 1;
}
out
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct JsonLexer;
impl StyledTextLexer for JsonLexer {
fn name(&self) -> &str {
"json"
}
fn default_styles(&self) -> Vec<(&'static str, TextStyle)> {
vec![
("key", TextStyle::new().fg_color(TYPE_COLOR)),
("string", TextStyle::new().fg_color(STRING_COLOR)),
("number", TextStyle::new().fg_color(NUMBER_COLOR)),
(
"literal",
TextStyle::new().fg_color(KEYWORD_COLOR).bold(true),
),
]
}
fn lex(&self, text: &str, styles: &StyleTable) -> Vec<(Range<usize>, StyleId)> {
let bytes = text.as_bytes();
let n = bytes.len();
let mut out = Vec::new();
let mut i = 0;
while i < n {
let c = bytes[i];
if c == b'"' {
let start = i;
i = skip_quoted(bytes, i);
let mut j = i;
while j < n && bytes[j].is_ascii_whitespace() {
j += 1;
}
let name = if bytes.get(j) == Some(&b':') {
"key"
} else {
"string"
};
out.push((start..i, styles.id_or_default(name)));
continue;
}
if c == b'-' || c.is_ascii_digit() {
let start = i;
i += 1;
while i < n
&& (bytes[i].is_ascii_digit()
|| matches!(bytes[i], b'.' | b'e' | b'E' | b'+' | b'-'))
{
i += 1;
}
out.push((start..i, styles.id_or_default("number")));
continue;
}
if c.is_ascii_alphabetic() {
let start = i;
while i < n && bytes[i].is_ascii_alphanumeric() {
i += 1;
}
if matches!(&text[start..i], "true" | "false" | "null") {
out.push((start..i, styles.id_or_default("literal")));
}
continue;
}
i += 1;
}
out
}
}
pub fn builtin_lexer(name: &str) -> Option<Box<dyn StyledTextLexer>> {
match name {
"rust" => Some(Box::new(RustLexer)),
"json" => Some(Box::new(JsonLexer)),
"plain" => Some(Box::new(PlainLexer)),
_ => None,
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StyledTextEdit {
pub position: usize,
pub deleted: String,
pub inserted: String,
}
impl StyledTextEdit {
fn inverse(&self) -> Self {
Self {
position: self.position,
deleted: self.inserted.clone(),
inserted: self.deleted.clone(),
}
}
fn inserted_len(&self) -> usize {
self.inserted.chars().count()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct MarkerId(pub u32);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct IndicatorId(pub u32);
#[derive(Debug, Clone)]
struct Marker {
id: MarkerId,
line: usize,
background: Color,
}
#[derive(Debug, Clone)]
struct Indicator {
id: IndicatorId,
range: Range<usize>,
style: TextStyle,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct FindOptions {
pub case_sensitive: bool,
pub whole_word: bool,
pub backwards: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum EditOrigin {
Typing,
Other,
}
pub struct StyledDocument {
text: String,
char_len: usize,
line_starts: Vec<usize>,
styles: StyleTable,
lexer: Box<dyn StyledTextLexer>,
monospace: bool,
read_only: bool,
indent_unit: String,
undo: Vec<Vec<StyledTextEdit>>,
undo_len: usize,
save_point: Option<usize>,
group_depth: usize,
group_open: bool,
last_origin: Option<EditOrigin>,
markers: Vec<Marker>,
indicators: Vec<Indicator>,
next_marker: u32,
next_indicator: u32,
caret_hint: Option<usize>,
}
impl fmt::Debug for StyledDocument {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("StyledDocument")
.field("chars", &self.char_len)
.field("lines", &self.line_starts.len())
.field("lexer", &self.lexer.name())
.field("read_only", &self.read_only)
.field("dirty", &self.is_dirty())
.finish_non_exhaustive()
}
}
impl Default for StyledDocument {
fn default() -> Self {
Self::new("")
}
}
fn normalize_newlines(text: &str) -> String {
if text.contains('\r') {
text.replace("\r\n", "\n").replace('\r', "\n")
} else {
text.to_owned()
}
}
fn byte_of(text: &str, position: usize) -> Option<usize> {
if position == 0 {
return Some(0);
}
match text.char_indices().nth(position) {
Some((index, _)) => Some(index),
None => (text.chars().count() == position).then_some(text.len()),
}
}
fn is_word_char(ch: char) -> bool {
ch.is_alphanumeric() || ch == '_'
}
fn chars_equal(a: char, b: char, case_sensitive: bool) -> bool {
a == b || (!case_sensitive && a.to_lowercase().eq(b.to_lowercase()))
}
fn overlay_style(base: &mut TextStyle, overlay: &TextStyle) {
base.bold |= overlay.bold;
base.italic |= overlay.italic;
base.underline |= overlay.underline;
base.strikethrough |= overlay.strikethrough;
base.dimmed |= overlay.dimmed;
base.monospace |= overlay.monospace;
if overlay.fg_color.is_some() {
base.fg_color = overlay.fg_color;
}
if overlay.bg_color.is_some() {
base.bg_color = overlay.bg_color;
}
if overlay.scale.is_some() {
base.scale = overlay.scale;
}
if overlay.link.is_some() {
base.link.clone_from(&overlay.link);
}
}
impl StyledDocument {
pub fn new(text: &str) -> Self {
let mut document = Self {
text: String::new(),
char_len: 0,
line_starts: vec![0],
styles: StyleTable::new(),
lexer: Box::new(PlainLexer),
monospace: true,
read_only: false,
indent_unit: " ".to_owned(),
undo: Vec::new(),
undo_len: 0,
save_point: Some(0),
group_depth: 0,
group_open: false,
last_origin: None,
markers: Vec::new(),
indicators: Vec::new(),
next_marker: 1,
next_indicator: 1,
caret_hint: None,
};
document.text = normalize_newlines(&text.replace('\0', ""));
document.reindex();
document
}
fn reindex(&mut self) {
self.line_starts.clear();
self.line_starts.push(0);
let mut count = 0;
for ch in self.text.chars() {
count += 1;
if ch == '\n' {
self.line_starts.push(count);
}
}
self.char_len = count;
}
pub fn text(&self) -> &str {
&self.text
}
pub fn len(&self) -> usize {
self.char_len
}
pub fn is_empty(&self) -> bool {
self.char_len == 0
}
pub fn text_range(&self, range: Range<usize>) -> StyledTextResult<&str> {
let bytes = self.byte_range(range)?;
Ok(&self.text[bytes])
}
fn invalid_range(&self, range: &Range<usize>) -> StyledTextError {
StyledTextError::InvalidRange {
start: range.start,
end: range.end,
len: self.char_len,
}
}
fn check_range(&self, range: &Range<usize>) -> StyledTextResult<()> {
if range.start > range.end || range.end > self.char_len {
return Err(self.invalid_range(range));
}
Ok(())
}
fn byte_range(&self, range: Range<usize>) -> StyledTextResult<Range<usize>> {
self.check_range(&range)?;
let start = byte_of(&self.text, range.start).unwrap_or(self.text.len());
let end = start
+ byte_of(&self.text[start..], range.end - range.start)
.unwrap_or(self.text.len() - start);
Ok(start..end)
}
pub fn byte_offset(&self, position: usize) -> StyledTextResult<usize> {
Ok(self.byte_range(position..position)?.start)
}
pub fn insert(&mut self, position: usize, text: &str) -> StyledTextResult<()> {
self.replace(position..position, text)
}
pub fn delete(&mut self, range: Range<usize>) -> StyledTextResult<()> {
self.replace(range, "")
}
pub fn append(&mut self, text: &str) -> StyledTextResult<()> {
let end = self.char_len;
self.replace(end..end, text)
}
pub fn replace(&mut self, range: Range<usize>, text: &str) -> StyledTextResult<()> {
self.edit(range, text, EditOrigin::Other)
}
pub fn set_text(&mut self, text: &str) -> StyledTextResult<()> {
let end = self.char_len;
self.replace(0..end, text)
}
pub fn load(&mut self, text: &str) -> StyledTextResult<()> {
if text.contains('\0') {
return Err(StyledTextError::EmbeddedNul);
}
self.text = normalize_newlines(text);
self.reindex();
self.undo.clear();
self.undo_len = 0;
self.save_point = Some(0);
self.last_origin = None;
self.markers.clear();
self.indicators.clear();
self.caret_hint = Some(0);
Ok(())
}
fn edit(
&mut self,
range: Range<usize>,
text: &str,
origin: EditOrigin,
) -> StyledTextResult<()> {
if self.read_only {
return Err(StyledTextError::ReadOnly);
}
if text.contains('\0') {
return Err(StyledTextError::EmbeddedNul);
}
let bytes = self.byte_range(range.clone())?;
let inserted = normalize_newlines(text);
if bytes.is_empty() && inserted.is_empty() {
return Ok(());
}
let edit = StyledTextEdit {
position: range.start,
deleted: self.text[bytes].to_owned(),
inserted,
};
self.apply(&edit);
self.record(edit, origin);
Ok(())
}
fn apply(&mut self, edit: &StyledTextEdit) {
let deleted_len = edit.deleted.chars().count();
let inserted_len = edit.inserted_len();
let start_line = self.line_of(edit.position);
let at_line_start = self.line_starts[start_line] == edit.position;
let bytes = self
.byte_range(edit.position..edit.position + deleted_len)
.expect("edit range checked by the caller");
self.text.replace_range(bytes, &edit.inserted);
self.reindex();
let removed_lines = edit.deleted.matches('\n').count();
let added_lines = edit.inserted.matches('\n').count();
let last_line = self.line_starts.len() - 1;
for marker in &mut self.markers {
if marker.line == start_line {
if at_line_start && edit.deleted.is_empty() {
marker.line += added_lines;
}
} else if marker.line > start_line + removed_lines {
marker.line = marker.line + added_lines - removed_lines;
} else if marker.line > start_line {
marker.line = start_line;
}
marker.line = marker.line.min(last_line);
}
let position = edit.position;
let deleted_end = position + deleted_len;
let shift = |offset: usize| offset + inserted_len - deleted_len;
self.indicators.retain_mut(|indicator| {
let Range { start, end } = indicator.range;
let new_start = if start < position {
start
} else if start >= deleted_end {
shift(start)
} else {
position + inserted_len
};
let new_end = if end <= position {
end
} else if end >= deleted_end {
shift(end)
} else {
position
};
indicator.range = new_start..new_end;
new_start < new_end
});
self.caret_hint = Some(position + inserted_len);
}
fn record(&mut self, edit: StyledTextEdit, origin: EditOrigin) {
self.undo.truncate(self.undo_len);
if self.save_point.is_some_and(|point| point > self.undo_len) {
self.save_point = None;
}
if self.group_depth > 0 && self.group_open {
if let Some(entry) = self.undo.last_mut() {
entry.push(edit);
return;
}
}
if origin == EditOrigin::Typing
&& self.last_origin == Some(EditOrigin::Typing)
&& self.group_depth == 0
&& self.save_point != Some(self.undo_len)
{
if let Some([previous]) = self.undo.last_mut().map(Vec::as_mut_slice) {
if let Some(merged) = coalesce(previous, &edit) {
*previous = merged;
return;
}
}
}
self.undo.push(vec![edit]);
self.undo_len = self.undo.len();
self.group_open = self.group_depth > 0;
self.last_origin = Some(origin);
}
pub fn can_undo(&self) -> bool {
self.undo_len > 0
}
pub fn can_redo(&self) -> bool {
self.undo_len < self.undo.len()
}
pub fn undo(&mut self) -> StyledTextResult<bool> {
if self.read_only {
return Err(StyledTextError::ReadOnly);
}
if self.undo_len == 0 {
return Ok(false);
}
self.undo_len -= 1;
let entry = self.undo[self.undo_len].clone();
for edit in entry.iter().rev() {
self.apply(&edit.inverse());
}
self.last_origin = None;
Ok(true)
}
pub fn redo(&mut self) -> StyledTextResult<bool> {
if self.read_only {
return Err(StyledTextError::ReadOnly);
}
if self.undo_len >= self.undo.len() {
return Ok(false);
}
let entry = self.undo[self.undo_len].clone();
for edit in &entry {
self.apply(edit);
}
self.undo_len += 1;
self.last_origin = None;
Ok(true)
}
pub fn begin_undo_group(&mut self) {
if self.group_depth == 0 {
self.group_open = false;
}
self.group_depth += 1;
}
pub fn end_undo_group(&mut self) {
self.group_depth = self.group_depth.saturating_sub(1);
if self.group_depth == 0 {
self.group_open = false;
self.last_origin = None;
}
}
pub fn clear_undo_history(&mut self) {
let dirty = self.is_dirty();
self.undo.clear();
self.undo_len = 0;
self.save_point = (!dirty).then_some(0);
self.last_origin = None;
}
pub fn set_save_point(&mut self) {
self.save_point = Some(self.undo_len);
self.last_origin = None;
}
pub fn is_dirty(&self) -> bool {
self.save_point != Some(self.undo_len)
}
pub fn line_count(&self) -> usize {
self.line_starts.len()
}
pub fn line_of(&self, position: usize) -> usize {
match self.line_starts.binary_search(&position) {
Ok(line) => line,
Err(next) => next - 1,
}
}
pub fn line_start(&self, line: usize) -> StyledTextResult<usize> {
self.line_starts
.get(line)
.copied()
.ok_or(StyledTextError::InvalidLine {
line,
line_count: self.line_starts.len(),
})
}
pub fn line_end(&self, line: usize) -> StyledTextResult<usize> {
self.line_start(line)?;
Ok(self
.line_starts
.get(line + 1)
.map_or(self.char_len, |next| next - 1))
}
pub fn line_text(&self, line: usize) -> StyledTextResult<&str> {
let range = self.line_start(line)?..self.line_end(line)?;
self.text_range(range)
}
pub fn line_column(&self, position: usize) -> (usize, usize) {
let position = position.min(self.char_len);
let line = self.line_of(position);
(line, position - self.line_starts[line])
}
pub fn position_of(&self, line: usize, column: usize) -> StyledTextResult<usize> {
let start = self.line_start(line)?;
let end = self.line_end(line)?;
Ok((start + column).min(end))
}
pub fn find(&self, query: &str, from: usize, options: FindOptions) -> Option<Range<usize>> {
let needle: Vec<char> = query.chars().collect();
let haystack: Vec<char> = self.text.chars().collect();
if needle.is_empty() || needle.len() > haystack.len() {
return None;
}
let matches_at = |start: usize| {
let end = start + needle.len();
let same = haystack[start..end]
.iter()
.zip(&needle)
.all(|(a, b)| chars_equal(*a, *b, options.case_sensitive));
if !same {
return false;
}
if options.whole_word {
let before = start.checked_sub(1).map(|i| haystack[i]);
let after = haystack.get(end).copied();
if before.is_some_and(is_word_char) || after.is_some_and(is_word_char) {
return false;
}
}
true
};
let last_start = haystack.len() - needle.len();
let found = if options.backwards {
let newest = from.min(haystack.len()).checked_sub(needle.len())?;
(0..=newest.min(last_start))
.rev()
.find(|&start| matches_at(start))
} else {
(from..=last_start).find(|&start| matches_at(start))
};
found.map(|start| start..start + needle.len())
}
pub fn replace_all(
&mut self,
query: &str,
replacement: &str,
options: FindOptions,
) -> StyledTextResult<usize> {
if self.read_only {
return Err(StyledTextError::ReadOnly);
}
if replacement.contains('\0') {
return Err(StyledTextError::EmbeddedNul);
}
let options = FindOptions {
backwards: false,
..options
};
let replacement_len = normalize_newlines(replacement).chars().count();
let mut count = 0;
let mut from = 0;
self.begin_undo_group();
let mut result = Ok(());
while let Some(found) = self.find(query, from, options) {
let start = found.start;
if let Err(error) = self.replace(found, replacement) {
result = Err(error);
break;
}
count += 1;
from = start + replacement_len;
}
self.end_undo_group();
result.map(|()| count)
}
pub fn indent_unit(&self) -> &str {
&self.indent_unit
}
pub fn set_indent_unit(&mut self, unit: &str) {
if !unit.is_empty() && !unit.contains(['\n', '\r', '\0']) {
self.indent_unit = unit.to_owned();
}
}
pub fn indent_lines(&mut self, lines: RangeInclusive<usize>) -> StyledTextResult<()> {
let (first, last) = self.check_lines(&lines)?;
if self.read_only {
return Err(StyledTextError::ReadOnly);
}
let unit = self.indent_unit.clone();
self.begin_undo_group();
for line in first..=last {
let start = self.line_starts[line];
if self.line_end(line).ok() != Some(start) {
self.insert(start, &unit)
.expect("line start is inside the text");
}
}
self.end_undo_group();
Ok(())
}
pub fn dedent_lines(&mut self, lines: RangeInclusive<usize>) -> StyledTextResult<()> {
let (first, last) = self.check_lines(&lines)?;
if self.read_only {
return Err(StyledTextError::ReadOnly);
}
let width = self.indent_unit.chars().count();
self.begin_undo_group();
for line in first..=last {
let text = self.line_text(line).unwrap_or_default();
let remove = if text.starts_with('\t') {
1
} else {
text.chars().take(width).take_while(|ch| *ch == ' ').count()
};
if remove > 0 {
let start = self.line_starts[line];
self.delete(start..start + remove)
.expect("indent is inside the line");
}
}
self.end_undo_group();
Ok(())
}
fn check_lines(&self, lines: &RangeInclusive<usize>) -> StyledTextResult<(usize, usize)> {
let (first, last) = (*lines.start(), *lines.end());
let line_count = self.line_count();
if first > last || last >= line_count {
return Err(StyledTextError::InvalidLine {
line: last.max(first),
line_count,
});
}
Ok((first, last))
}
pub fn is_read_only(&self) -> bool {
self.read_only
}
pub fn set_read_only(&mut self, read_only: bool) {
self.read_only = read_only;
}
pub fn styles(&self) -> &StyleTable {
&self.styles
}
pub fn styles_mut(&mut self) -> &mut StyleTable {
&mut self.styles
}
pub fn lexer_name(&self) -> &str {
self.lexer.name()
}
pub fn set_lexer(&mut self, lexer: Box<dyn StyledTextLexer>) {
for (name, style) in lexer.default_styles() {
if self.styles.id_of(name).is_none() {
self.styles.define(name, style);
}
}
self.lexer = lexer;
}
pub fn monospace(&self) -> bool {
self.monospace
}
pub fn set_monospace(&mut self, monospace: bool) {
self.monospace = monospace;
}
fn lexer_tokens(&self) -> Vec<(Range<usize>, StyleId)> {
let mut tokens = self.lexer.lex(&self.text, &self.styles);
let mut last_end = 0;
tokens.retain(|(range, id)| {
let keep = range.start >= last_end
&& range.start < range.end
&& range.end <= self.text.len()
&& self.text.is_char_boundary(range.start)
&& self.text.is_char_boundary(range.end)
&& self.styles.get(*id).is_some();
if keep {
last_end = range.end;
}
keep
});
tokens
}
pub fn tokens(&self) -> Vec<(Range<usize>, StyleId)> {
let mut out = Vec::new();
let mut chars = 0;
let mut byte = 0;
for (range, id) in self.lexer_tokens() {
chars += self.text[byte..range.start].chars().count();
let start = chars;
chars += self.text[range.clone()].chars().count();
byte = range.end;
out.push((start..chars, id));
}
out
}
pub fn style_at(&self, position: usize) -> TextStyle {
let Ok(byte) = self.byte_offset(position) else {
return TextStyle::new();
};
self.runs()
.into_iter()
.find(|run| run.range.contains(&byte))
.map(|run| run.style)
.unwrap_or_default()
}
pub fn runs(&self) -> Vec<TextRun> {
let len = self.text.len();
if len == 0 {
return Vec::new();
}
let tokens = self.lexer_tokens();
let mut overlays: Vec<(Range<usize>, TextStyle)> = Vec::new();
for marker in &self.markers {
let start = self.line_starts[marker.line];
let end = self
.line_starts
.get(marker.line + 1)
.copied()
.unwrap_or(self.char_len);
if let Ok(bytes) = self.byte_range(start..end) {
if !bytes.is_empty() {
overlays.push((bytes, TextStyle::new().bg_color(marker.background)));
}
}
}
for indicator in &self.indicators {
if let Ok(bytes) = self.byte_range(indicator.range.clone()) {
overlays.push((bytes, indicator.style.clone()));
}
}
let mut cuts = vec![0, len];
for range in tokens
.iter()
.map(|(range, _)| range)
.chain(overlays.iter().map(|(range, _)| range))
{
cuts.push(range.start);
cuts.push(range.end);
}
cuts.sort_unstable();
cuts.dedup();
let default = self
.styles
.get(StyleId::DEFAULT)
.cloned()
.unwrap_or_default();
let mut runs: Vec<TextRun> = Vec::new();
let mut token = 0;
for pair in cuts.windows(2) {
let (start, end) = (pair[0], pair[1]);
while token < tokens.len() && tokens[token].0.end <= start {
token += 1;
}
let mut style = match tokens.get(token) {
Some((range, id)) if range.start <= start => {
self.styles.get(*id).cloned().unwrap_or_default()
}
_ => default.clone(),
};
for (range, overlay) in &overlays {
if range.start <= start && start < range.end {
overlay_style(&mut style, overlay);
}
}
style.monospace |= self.monospace;
if style == TextStyle::new() {
continue;
}
match runs.last_mut() {
Some(last) if last.range.end == start && last.style == style => {
last.range.end = end;
}
_ => runs.push(TextRun::new(start..end, style)),
}
}
runs
}
pub fn add_marker(&mut self, line: usize, background: Color) -> StyledTextResult<MarkerId> {
self.line_start(line)?;
let id = MarkerId(self.next_marker);
self.next_marker += 1;
self.markers.push(Marker {
id,
line,
background,
});
Ok(id)
}
pub fn remove_marker(&mut self, id: MarkerId) -> StyledTextResult<()> {
let before = self.markers.len();
self.markers.retain(|marker| marker.id != id);
if self.markers.len() == before {
return Err(StyledTextError::UnknownMarker(id));
}
Ok(())
}
pub fn marker_line(&self, id: MarkerId) -> Option<usize> {
self.markers
.iter()
.find(|marker| marker.id == id)
.map(|marker| marker.line)
}
pub fn markers_on_line(&self, line: usize) -> Vec<MarkerId> {
self.markers
.iter()
.filter(|marker| marker.line == line)
.map(|marker| marker.id)
.collect()
}
pub fn next_marker_line(&self, line: usize) -> Option<usize> {
self.markers
.iter()
.map(|marker| marker.line)
.filter(|marked| *marked >= line)
.min()
}
pub fn previous_marker_line(&self, line: usize) -> Option<usize> {
self.markers
.iter()
.map(|marker| marker.line)
.filter(|marked| *marked <= line)
.max()
}
pub fn clear_markers(&mut self) {
self.markers.clear();
}
pub fn add_indicator(
&mut self,
range: Range<usize>,
style: TextStyle,
) -> StyledTextResult<IndicatorId> {
self.check_range(&range)?;
if range.is_empty() {
return Err(self.invalid_range(&range));
}
let id = IndicatorId(self.next_indicator);
self.next_indicator += 1;
self.indicators.push(Indicator { id, range, style });
Ok(id)
}
pub fn remove_indicator(&mut self, id: IndicatorId) -> StyledTextResult<()> {
let before = self.indicators.len();
self.indicators.retain(|indicator| indicator.id != id);
if self.indicators.len() == before {
return Err(StyledTextError::UnknownIndicator(id));
}
Ok(())
}
pub fn indicator_range(&self, id: IndicatorId) -> Option<Range<usize>> {
self.indicators
.iter()
.find(|indicator| indicator.id == id)
.map(|indicator| indicator.range.clone())
}
pub fn indicators_at(&self, position: usize) -> Vec<IndicatorId> {
self.indicators
.iter()
.filter(|indicator| indicator.range.contains(&position))
.map(|indicator| indicator.id)
.collect()
}
pub fn clear_indicators(&mut self) {
self.indicators.clear();
}
fn take_caret_hint(&mut self) -> Option<usize> {
self.caret_hint.take()
}
fn apply_view_text(&mut self, view_text: &str) -> StyledTextResult<Option<StyledTextEdit>> {
let new_text = normalize_newlines(&view_text.replace('\0', ""));
if new_text == self.text {
return Ok(None);
}
if self.read_only {
return Err(StyledTextError::ReadOnly);
}
let edit = diff(&self.text, &new_text);
let deleted_len = edit.deleted.chars().count();
let inserted_len = edit.inserted_len();
let is_keystroke = !edit.inserted.contains('\n')
&& !edit.deleted.contains('\n')
&& ((deleted_len == 0 && inserted_len == 1) || (deleted_len == 1 && inserted_len == 0));
let origin = if is_keystroke {
EditOrigin::Typing
} else {
EditOrigin::Other
};
self.edit(
edit.position..edit.position + deleted_len,
&edit.inserted,
origin,
)?;
Ok(Some(edit))
}
}
fn coalesce(previous: &StyledTextEdit, next: &StyledTextEdit) -> Option<StyledTextEdit> {
let previous_inserts = previous.deleted.is_empty() && !previous.inserted.is_empty();
let previous_deletes = previous.inserted.is_empty() && !previous.deleted.is_empty();
if previous_inserts
&& next.deleted.is_empty()
&& next.position == previous.position + previous.inserted_len()
{
let after_space = previous.inserted.ends_with(char::is_whitespace);
let word_starts = next.inserted.starts_with(|ch: char| !ch.is_whitespace());
if after_space && word_starts {
return None;
}
return Some(StyledTextEdit {
position: previous.position,
deleted: String::new(),
inserted: format!("{}{}", previous.inserted, next.inserted),
});
}
if previous_deletes && next.inserted.is_empty() {
if next.position + next.deleted.chars().count() == previous.position {
return Some(StyledTextEdit {
position: next.position,
deleted: format!("{}{}", next.deleted, previous.deleted),
inserted: String::new(),
});
}
if next.position == previous.position {
return Some(StyledTextEdit {
position: previous.position,
deleted: format!("{}{}", previous.deleted, next.deleted),
inserted: String::new(),
});
}
}
None
}
fn diff(old: &str, new: &str) -> StyledTextEdit {
let prefix: usize = old
.chars()
.zip(new.chars())
.take_while(|(a, b)| a == b)
.map(|(a, _)| a.len_utf8())
.sum();
let (old_rest, new_rest) = (&old[prefix..], &new[prefix..]);
let suffix: usize = old_rest
.chars()
.rev()
.zip(new_rest.chars().rev())
.take_while(|(a, b)| a == b)
.map(|(a, _)| a.len_utf8())
.sum();
StyledTextEdit {
position: old[..prefix].chars().count(),
deleted: old_rest[..old_rest.len() - suffix].to_owned(),
inserted: new_rest[..new_rest.len() - suffix].to_owned(),
}
}
struct StyledTextState {
document: StyledDocument,
pushed: Vec<TextRun>,
}
#[derive(Default)]
pub(crate) struct StyledTextRegistry {
widgets: HashMap<WidgetId, StyledTextState>,
}
impl StyledTextRegistry {
pub(crate) fn forget(&mut self, widget_id: WidgetId) {
self.widgets.remove(&widget_id);
}
}
impl<B: Backend> Ui<B> {
pub fn create_styled_text(&mut self, text: &str) -> GuiResult<WidgetId> {
if text.contains('\0') {
return Err(StyledTextError::EmbeddedNul.into());
}
let document = StyledDocument::new(text);
let widget = self.create(WidgetKind::RichText, Some(document.text()))?;
let _ = self.set_monospace(widget, true);
let _ = self.set_spell_check(widget, false);
self.styled_texts.widgets.insert(
widget,
StyledTextState {
document,
pushed: Vec::new(),
},
);
if let Err(error) = self.sync_styled_text(widget, true) {
self.styled_texts.forget(widget);
let _ = self.remove(widget);
return Err(error);
}
Ok(widget)
}
pub fn styled_text(&self, widget: WidgetId) -> GuiResult<&StyledDocument> {
self.styled_texts
.widgets
.get(&widget)
.map(|state| &state.document)
.ok_or(GuiError::WidgetNotFound(widget.0))
}
pub fn update_styled_text<R>(
&mut self,
widget: WidgetId,
change: impl FnOnce(&mut StyledDocument) -> R,
) -> GuiResult<R> {
let state = self
.styled_texts
.widgets
.get_mut(&widget)
.ok_or(GuiError::WidgetNotFound(widget.0))?;
let result = change(&mut state.document);
self.sync_styled_text(widget, false)?;
Ok(result)
}
pub fn set_styled_text_lexer(
&mut self,
widget: WidgetId,
lexer: Box<dyn StyledTextLexer>,
) -> GuiResult<()> {
self.update_styled_text(widget, |document| document.set_lexer(lexer))
}
pub fn styled_text_undo(&mut self, widget: WidgetId) -> GuiResult<bool> {
Ok(self.update_styled_text(widget, StyledDocument::undo)??)
}
pub fn styled_text_redo(&mut self, widget: WidgetId) -> GuiResult<bool> {
Ok(self.update_styled_text(widget, StyledDocument::redo)??)
}
pub fn styled_text_caret(&self, widget: WidgetId) -> GuiResult<(usize, usize)> {
let document = self.styled_text(widget)?;
let (_, end) = self.styled_text_selection(widget);
Ok(document.line_column(end))
}
pub fn styled_text_selected_lines(&self, widget: WidgetId) -> GuiResult<RangeInclusive<usize>> {
let document = self.styled_text(widget)?;
let (start, end) = self.styled_text_selection(widget);
let first = document.line_of(start);
let mut last = document.line_of(end);
if last > first && document.line_start(last).ok() == Some(end) {
last -= 1;
}
Ok(first..=last)
}
pub fn styled_text_go_to_line(&mut self, widget: WidgetId, line: usize) -> GuiResult<()> {
let position = self.styled_text(widget)?.line_start(line)?;
self.set_text_selection(widget, position, position)
}
pub fn styled_text_find(
&mut self,
widget: WidgetId,
query: &str,
options: FindOptions,
) -> GuiResult<Option<Range<usize>>> {
let (start, end) = self.styled_text_selection(widget);
let document = self.styled_text(widget)?;
let found = if options.backwards {
document
.find(query, start, options)
.or_else(|| document.find(query, document.len(), options))
} else {
document
.find(query, end, options)
.or_else(|| document.find(query, 0, options))
};
if let Some(range) = &found {
self.set_text_selection(widget, range.start, range.end)?;
}
Ok(found)
}
fn styled_text_selection(&self, widget: WidgetId) -> (usize, usize) {
let len = self
.styled_texts
.widgets
.get(&widget)
.map_or(0, |state| state.document.len());
let (start, end) = self
.text_selection(widget)
.ok()
.or_else(|| {
self.widget_spec(widget)
.ok()
.and_then(|spec| spec.text_selection)
})
.unwrap_or((0, 0));
(start.min(len), end.min(len))
}
fn sync_styled_text(&mut self, widget: WidgetId, force_runs: bool) -> GuiResult<()> {
let Some(state) = self.styled_texts.widgets.get_mut(&widget) else {
return Ok(());
};
let text = state.document.text().to_owned();
let caret = state.document.take_caret_hint();
let runs = state.document.runs();
let text_changed = self.text(widget).map_or(true, |shown| shown != text);
if text_changed {
self.set_text(widget, &text)?;
if let Some(caret) = caret {
let _ = self.set_text_selection(widget, caret, caret);
}
}
let Some(state) = self.styled_texts.widgets.get_mut(&widget) else {
return Ok(());
};
if force_runs || text_changed || state.pushed != runs {
state.pushed.clone_from(&runs);
self.set_rich_text_runs(widget, &runs)?;
}
Ok(())
}
pub(crate) fn observe_styled_text_event(&mut self, event: &UiEvent) {
let UiEvent::TextChanged { widget_id, text } = event else {
return;
};
let widget = *widget_id;
let Some(state) = self.styled_texts.widgets.get_mut(&widget) else {
return;
};
let was_dirty = state.document.is_dirty();
match state.document.apply_view_text(text) {
Ok(None) => {}
Ok(Some(edit)) => {
let dirty = state.document.is_dirty();
let _ = state.document.take_caret_hint();
let _ = self.sync_styled_text(widget, false);
self.queue_event(UiEvent::StyledTextModified {
widget_id: widget,
position: edit.position,
deleted: edit.deleted,
inserted: edit.inserted,
});
if dirty != was_dirty {
self.queue_event(UiEvent::StyledTextSavePointChanged {
widget_id: widget,
dirty,
});
}
}
Err(_) => {
let caret = diff(state.document.text(), &normalize_newlines(text)).position;
let _ = state.document.take_caret_hint();
let restored = state.document.text().to_owned();
if self.set_text(widget, &restored).is_ok() {
let _ = self.set_text_selection(widget, caret, caret);
let _ = self.sync_styled_text(widget, true);
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_support::MockBackend;
const RED: Color = Color::rgb(0xd0, 0x30, 0x30);
const BAND: Color = Color::rgb(0xff, 0xf3, 0xc4);
fn token_names(document: &StyledDocument) -> Vec<(String, String)> {
document
.tokens()
.into_iter()
.map(|(range, id)| {
(
document.text_range(range).unwrap().to_owned(),
document.styles().name(id).unwrap().to_owned(),
)
})
.collect()
}
fn type_text(document: &mut StyledDocument, at: usize, text: &str) {
for (position, ch) in (at..).zip(text.chars()) {
let mut next = document.text().to_owned();
let byte = byte_of(&next, position).unwrap();
next.insert(byte, ch);
document.apply_view_text(&next).unwrap();
}
}
fn backspace(document: &mut StyledDocument, at: usize, count: usize) {
for step in 0..count {
let position = at - step;
let mut next = document.text().to_owned();
let byte = byte_of(&next, position - 1).unwrap();
next.remove(byte);
document.apply_view_text(&next).unwrap();
}
}
#[test]
fn rust_lexer_marks_the_common_token_kinds() {
let mut document = StyledDocument::new(
"#[derive(Debug)]\nfn main<'a>() { let s: &'a str = r#\"x\"#; // hi\n println!(\"{}\", 42_u8 + b'c' as u8); /* a /* b */ c */ }",
);
document.set_lexer(Box::new(RustLexer));
let tokens = token_names(&document);
let has = |text: &str, style: &str| tokens.iter().any(|(t, s)| t == text && s == style);
assert!(has("#[derive(Debug)]", "attribute"), "{tokens:?}");
assert!(has("fn", "keyword"));
assert!(has("let", "keyword"));
assert!(has("'a", "lifetime"));
assert!(has("str", "type"));
assert!(has("r#\"x\"#", "string"));
assert!(has("// hi", "comment"));
assert!(has("println!", "macro"));
assert!(has("\"{}\"", "string"));
assert!(has("42_u8", "number"));
assert!(has("b'c'", "string"));
assert!(has("/* a /* b */ c */", "comment"));
assert!(
!tokens.iter().any(|(t, _)| t == "main"),
"plain identifiers stay default"
);
}
#[test]
fn rust_lexer_keeps_ranges_on_character_boundaries() {
let mut document = StyledDocument::new("let é = \"ü\"; // ✓\nlet c = 'ß';");
document.set_lexer(Box::new(RustLexer));
let tokens = token_names(&document);
assert!(tokens.contains(&("\"ü\"".into(), "string".into())));
assert!(tokens.contains(&("// ✓".into(), "comment".into())));
assert!(tokens.contains(&("'ß'".into(), "string".into())));
for run in document.runs() {
assert!(document.text().is_char_boundary(run.range.start));
assert!(document.text().is_char_boundary(run.range.end));
}
}
#[test]
fn json_lexer_tells_keys_from_values() {
let mut document = StyledDocument::new(
"{\"name\": \"demo\", \"size\": -1.5e3, \"ok\": true, \"x\": null}",
);
document.set_lexer(Box::new(JsonLexer));
let tokens = token_names(&document);
assert!(tokens.contains(&("\"name\"".into(), "key".into())));
assert!(tokens.contains(&("\"demo\"".into(), "string".into())));
assert!(tokens.contains(&("-1.5e3".into(), "number".into())));
assert!(tokens.contains(&("true".into(), "literal".into())));
assert!(tokens.contains(&("null".into(), "literal".into())));
}
#[test]
fn application_styles_win_over_lexer_suggestions() {
let mut document = StyledDocument::new("fn x() {}");
let mine = TextStyle::new().fg_color(RED);
document.styles_mut().define("keyword", mine.clone());
document.set_lexer(Box::new(RustLexer));
let id = document.styles().id_of("keyword").unwrap();
assert_eq!(document.styles().get(id), Some(&mine));
assert_eq!(document.style_at(0).fg_color, Some(RED));
assert!(builtin_lexer("json").is_some() && builtin_lexer("cobol").is_none());
}
#[test]
fn misbehaving_custom_lexer_output_is_filtered() {
struct Broken;
impl StyledTextLexer for Broken {
fn name(&self) -> &str {
"broken"
}
fn lex(&self, _text: &str, _styles: &StyleTable) -> Vec<(Range<usize>, StyleId)> {
vec![
(0..2, StyleId(1)),
(1..3, StyleId(1)),
(3..4, StyleId(9)),
(5..99, StyleId(1)),
(4..5, StyleId(1)),
]
}
}
let mut document = StyledDocument::new("ab é xyz");
document
.styles_mut()
.define("hot", TextStyle::new().bold(true));
document.set_lexer(Box::new(Broken));
assert_eq!(document.tokens(), vec![(0..2, StyleId(1))]);
}
#[test]
fn edits_validate_ranges_and_normalize_line_breaks() {
let mut document = StyledDocument::new("a\r\nb\rc");
assert_eq!(document.text(), "a\nb\nc");
assert_eq!(document.line_count(), 3);
assert_eq!(
document.insert(9, "x"),
Err(StyledTextError::InvalidRange {
start: 9,
end: 9,
len: 5
})
);
#[allow(clippy::reversed_empty_ranges)]
let reversed = document.delete(3..1);
assert!(matches!(
reversed,
Err(StyledTextError::InvalidRange { .. })
));
assert_eq!(document.insert(0, "x\0"), Err(StyledTextError::EmbeddedNul));
document.insert(1, "1\r\n2").unwrap();
assert_eq!(document.text(), "a1\n2\nb\nc");
assert!(!document.is_empty());
}
#[test]
fn line_helpers_use_character_positions() {
let document = StyledDocument::new("αβ\n\ngamma");
assert_eq!(document.line_count(), 3);
assert_eq!(document.line_start(2), Ok(4));
assert_eq!(document.line_end(0), Ok(2));
assert_eq!(document.line_text(1), Ok(""));
assert_eq!(document.line_text(2), Ok("gamma"));
assert_eq!(document.line_column(6), (2, 2));
assert_eq!(document.position_of(0, 99), Ok(2));
assert_eq!(
document.line_start(3),
Err(StyledTextError::InvalidLine {
line: 3,
line_count: 3
})
);
assert_eq!(document.byte_offset(2), Ok(4));
}
#[test]
fn typing_coalesces_by_word_and_undo_redo_walk_the_history() {
let mut document = StyledDocument::new("");
type_text(&mut document, 0, "let x");
assert_eq!(document.text(), "let x");
document.undo().unwrap();
assert_eq!(document.text(), "let ", "undo removes the last word");
document.undo().unwrap();
assert_eq!(document.text(), "");
assert!(!document.undo().unwrap());
document.redo().unwrap();
document.redo().unwrap();
assert_eq!(document.text(), "let x");
assert!(!document.redo().unwrap());
backspace(&mut document, 5, 2);
assert_eq!(document.text(), "let");
document.undo().unwrap();
assert_eq!(document.text(), "let x", "backspaces undo together");
}
#[test]
fn a_new_edit_discards_redo_and_programmatic_edits_never_merge() {
let mut document = StyledDocument::new("one");
document.append(" two").unwrap();
document.append(" three").unwrap();
document.undo().unwrap();
assert!(document.can_redo());
document.append("!").unwrap();
assert!(!document.can_redo());
assert_eq!(document.text(), "one two!");
document.undo().unwrap();
assert_eq!(document.text(), "one two");
}
#[test]
fn undo_groups_nest_into_one_step() {
let mut document = StyledDocument::new("abc");
document.begin_undo_group();
document.insert(0, "1").unwrap();
document.begin_undo_group();
document.insert(0, "2").unwrap();
document.end_undo_group();
document.append("3").unwrap();
document.end_undo_group();
assert_eq!(document.text(), "21abc3");
document.undo().unwrap();
assert_eq!(document.text(), "abc");
document.redo().unwrap();
assert_eq!(document.text(), "21abc3");
}
#[test]
fn save_point_tracks_dirty_state_through_undo_and_redo() {
let mut document = StyledDocument::new("x");
assert!(!document.is_dirty());
type_text(&mut document, 1, "yz");
assert!(document.is_dirty());
document.set_save_point();
assert!(!document.is_dirty());
type_text(&mut document, 3, "w");
assert!(document.is_dirty());
document.undo().unwrap();
assert!(
!document.is_dirty(),
"typing after a save does not merge into the saved step"
);
document.undo().unwrap();
assert!(document.is_dirty());
document.append("!").unwrap();
document.undo().unwrap();
assert!(
document.is_dirty(),
"the save point was in the discarded redo steps"
);
document.load("fresh").unwrap();
assert!(!document.is_dirty() && !document.can_undo());
}
#[test]
fn find_honours_case_whole_word_and_direction() {
let document = StyledDocument::new("Foo foo food foo");
let plain = FindOptions::default();
assert_eq!(document.find("foo", 0, plain), Some(0..3));
let case = FindOptions {
case_sensitive: true,
..plain
};
assert_eq!(document.find("foo", 0, case), Some(4..7));
let word = FindOptions {
whole_word: true,
..plain
};
assert_eq!(document.find("foo", 5, word), Some(13..16));
let back = FindOptions {
backwards: true,
..plain
};
assert_eq!(document.find("foo", 12, back), Some(8..11));
assert_eq!(document.find("foo", 2, back), None);
assert_eq!(document.find("", 0, plain), None);
assert_eq!(document.find("zzz", 0, plain), None);
}
#[test]
fn replace_all_is_one_undo_step() {
let mut document = StyledDocument::new("a-b-c");
let count = document
.replace_all("-", "--", FindOptions::default())
.unwrap();
assert_eq!(count, 2);
assert_eq!(document.text(), "a--b--c");
document.undo().unwrap();
assert_eq!(document.text(), "a-b-c");
}
#[test]
fn indent_and_dedent_lines() {
let mut document = StyledDocument::new("a\n\n b\n\tc");
document.indent_lines(0..=2).unwrap();
assert_eq!(document.text(), " a\n\n b\n\tc");
document.dedent_lines(0..=3).unwrap();
assert_eq!(document.text(), "a\n\n b\nc");
document.undo().unwrap();
document.undo().unwrap();
assert_eq!(document.text(), "a\n\n b\n\tc");
document.set_indent_unit("\t");
document.indent_lines(3..=3).unwrap();
assert_eq!(document.line_text(3), Ok("\t\tc"));
assert!(matches!(
document.indent_lines(2..=9),
Err(StyledTextError::InvalidLine { .. })
));
}
#[test]
fn markers_move_with_their_lines() {
let mut document = StyledDocument::new("zero\none\ntwo\nthree");
let two = document.add_marker(2, BAND).unwrap();
let zero = document.add_marker(0, BAND).unwrap();
document.insert(0, "new\n").unwrap();
assert_eq!(document.marker_line(two), Some(3));
assert_eq!(
document.marker_line(zero),
Some(1),
"a line break at a line start pushes it"
);
document
.insert(document.line_end(1).unwrap(), " tail")
.unwrap();
assert_eq!(document.marker_line(zero), Some(1));
let start = document.line_start(1).unwrap();
let end = document.line_start(3).unwrap();
document.delete(start..end).unwrap();
assert_eq!(
document.marker_line(two),
Some(1),
"the text before it went away"
);
assert_eq!(document.next_marker_line(0), Some(1));
assert_eq!(document.previous_marker_line(0), None);
assert_eq!(document.markers_on_line(1).len(), 2);
document.remove_marker(two).unwrap();
assert_eq!(
document.remove_marker(two),
Err(StyledTextError::UnknownMarker(two))
);
assert!(document.add_marker(9, BAND).is_err());
}
#[test]
fn indicators_track_edits_and_vanish_with_their_text() {
let mut document = StyledDocument::new("let value = 1;");
let squiggle = TextStyle::new().underline(true).fg_color(RED);
let id = document.add_indicator(4..9, squiggle).unwrap();
document.insert(0, " ").unwrap();
assert_eq!(document.indicator_range(id), Some(8..13));
document.insert(10, "XX").unwrap();
assert_eq!(
document.indicator_range(id),
Some(8..15),
"inside: it grows"
);
assert_eq!(document.indicators_at(9), vec![id]);
document.delete(6..10).unwrap();
assert_eq!(
document.indicator_range(id),
Some(6..11),
"a deleted start is trimmed"
);
document.delete(5..12).unwrap();
assert_eq!(document.indicator_range(id), None);
assert_eq!(
document.remove_indicator(id),
Err(StyledTextError::UnknownIndicator(id))
);
assert!(document.add_indicator(2..2, TextStyle::new()).is_err());
}
#[test]
fn runs_layer_lexer_marker_and_indicator_styles() {
let mut document = StyledDocument::new("fn a() {}\nlet b = 2;");
document.set_lexer(Box::new(RustLexer));
document.add_marker(1, BAND).unwrap();
document
.add_indicator(14..15, TextStyle::new().underline(true).fg_color(RED))
.unwrap();
let runs = document.runs();
let mut covered = 0;
for run in &runs {
assert_eq!(run.range.start, covered, "runs tile the text");
covered = run.range.end;
assert!(run.style.monospace);
}
assert_eq!(covered, document.text().len());
let keyword = document.style_at(0);
assert!(keyword.bold && keyword.bg_color.is_none());
let marked_keyword = document.style_at(10);
assert!(marked_keyword.bold);
assert_eq!(marked_keyword.bg_color, Some(BAND));
let flagged = document.style_at(14);
assert!(flagged.underline);
assert_eq!(flagged.fg_color, Some(RED));
assert_eq!(flagged.bg_color, Some(BAND));
document.set_monospace(false);
assert!(document
.runs()
.iter()
.all(|run| run.style != TextStyle::new()));
assert!(StyledDocument::new("").runs().is_empty());
}
#[test]
fn diff_finds_the_changed_middle() {
let edit = diff("hello world", "hello brave world");
assert_eq!(edit.position, 6);
assert_eq!(edit.deleted, "");
assert_eq!(edit.inserted, "brave ");
let edit = diff("aaa", "aa");
assert_eq!((edit.position, edit.deleted.as_str()), (2, "a"));
let edit = diff("ä€x", "äyx");
assert_eq!(
(edit.position, edit.deleted.as_str(), edit.inserted.as_str()),
(1, "€", "y")
);
}
fn ui_with(text: &str) -> (Ui<MockBackend>, WidgetId) {
let mut ui = Ui::new(MockBackend::default());
let widget = ui.create_styled_text(text).unwrap();
(ui, widget)
}
fn user_types(ui: &mut Ui<MockBackend>, widget: WidgetId, text: &str) -> Vec<UiEvent> {
ui.backend_mut().push_event(UiEvent::TextChanged {
widget_id: widget,
text: text.to_owned(),
});
let mut events = Vec::new();
while let Some(event) = ui.poll_event().unwrap() {
events.push(event);
}
events
}
fn native_runs(ui: &Ui<MockBackend>, widget: WidgetId) -> Vec<TextRun> {
ui.backend().created[&widget].rich_text_runs.clone()
}
#[test]
fn creates_a_monospace_rich_text_with_styled_runs() {
let (mut ui, widget) = ui_with("fn main() {}");
assert_eq!(ui.widget_spec(widget).unwrap().kind, WidgetKind::RichText);
assert_eq!(ui.text(widget).unwrap(), "fn main() {}");
ui.set_styled_text_lexer(widget, Box::new(RustLexer))
.unwrap();
let runs = native_runs(&ui, widget);
assert!(runs.iter().any(|run| run.range == (0..2) && run.style.bold));
assert_eq!(ui.styled_text(widget).unwrap().lexer_name(), "rust");
assert!(ui.create_styled_text("a\0b").is_err());
}
#[test]
fn user_typing_updates_the_document_and_queues_events() {
let (mut ui, widget) = ui_with("let x = 1;");
ui.set_styled_text_lexer(widget, Box::new(RustLexer))
.unwrap();
let events = user_types(&mut ui, widget, "let x = 12;");
assert!(events.contains(&UiEvent::StyledTextModified {
widget_id: widget,
position: 9,
deleted: String::new(),
inserted: "2".into(),
}));
assert!(events.contains(&UiEvent::StyledTextSavePointChanged {
widget_id: widget,
dirty: true,
}));
assert!(events
.iter()
.any(|event| matches!(event, UiEvent::TextChanged { .. })));
let runs = native_runs(&ui, widget);
let number = runs
.iter()
.find(|run| run.style.fg_color == Some(NUMBER_COLOR))
.unwrap();
assert_eq!(number.range, 8..10, "the longer number is restyled");
let echo = user_types(&mut ui, widget, "let x = 12;");
assert!(!echo
.iter()
.any(|event| matches!(event, UiEvent::StyledTextModified { .. })));
assert!(ui.styled_text_undo(widget).unwrap());
assert_eq!(ui.text(widget).unwrap(), "let x = 1;");
assert!(!ui.styled_text(widget).unwrap().is_dirty());
assert!(ui.styled_text_redo(widget).unwrap());
assert_eq!(ui.text(widget).unwrap(), "let x = 12;");
}
#[test]
fn pasted_crlf_is_normalized_in_the_view() {
let (mut ui, widget) = ui_with("a");
let events = user_types(&mut ui, widget, "a\r\nb");
assert!(events.contains(&UiEvent::StyledTextModified {
widget_id: widget,
position: 1,
deleted: String::new(),
inserted: "\nb".into(),
}));
assert_eq!(ui.text(widget).unwrap(), "a\nb");
}
#[test]
fn read_only_reverts_user_edits() {
let (mut ui, widget) = ui_with("locked");
ui.update_styled_text(widget, |document| document.set_read_only(true))
.unwrap();
let events = user_types(&mut ui, widget, "lockedX");
assert!(!events
.iter()
.any(|event| matches!(event, UiEvent::StyledTextModified { .. })));
assert_eq!(ui.text(widget).unwrap(), "locked");
assert_eq!(ui.styled_text(widget).unwrap().text(), "locked");
assert_eq!(
ui.styled_text_undo(widget),
Err(GuiError::StyledText(StyledTextError::ReadOnly))
);
}
#[test]
fn programmatic_updates_are_silent_and_place_the_caret() {
let (mut ui, widget) = ui_with("line one\nline two");
ui.update_styled_text(widget, |document| document.insert(9, "new ").unwrap())
.unwrap();
assert_eq!(ui.text(widget).unwrap(), "line one\nnew line two");
assert_eq!(
ui.widget_spec(widget).unwrap().text_selection,
Some((13, 13))
);
assert_eq!(ui.styled_text_caret(widget).unwrap(), (1, 4));
assert!(ui.poll_event().unwrap().is_none());
let found = ui
.styled_text_find(widget, "line", FindOptions::default())
.unwrap();
assert_eq!(found, Some(13..17));
let wrapped = ui
.styled_text_find(widget, "line", FindOptions::default())
.unwrap();
assert_eq!(wrapped, Some(0..4), "the search wraps around");
ui.set_text_selection(widget, 2, 10).unwrap();
assert_eq!(ui.styled_text_selected_lines(widget).unwrap(), 0..=1);
ui.set_text_selection(widget, 2, 9).unwrap();
assert_eq!(ui.styled_text_selected_lines(widget).unwrap(), 0..=0);
ui.styled_text_go_to_line(widget, 1).unwrap();
assert_eq!(ui.styled_text_caret(widget).unwrap(), (1, 0));
}
#[test]
fn removing_the_widget_drops_its_document() {
let (mut ui, widget) = ui_with("bye");
ui.remove(widget).unwrap();
assert!(matches!(
ui.styled_text(widget),
Err(GuiError::WidgetNotFound(_))
));
assert!(ui.update_styled_text(widget, |_| ()).is_err());
}
}