use crate::color::TextStyle;
use crate::widget::TextMetrics;
use std::collections::VecDeque;
use std::time::Instant;
const HISTORY_MAX_STEPS: usize = 200;
const HISTORY_MAX_BYTES: usize = 4 * 1024 * 1024;
const TYPING_COALESCE: std::time::Duration = std::time::Duration::from_millis(700);
#[derive(Clone, Debug)]
struct Snapshot {
text: String,
cursor: usize,
anchor: usize,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum EditKind {
Typing,
Other,
}
fn is_word_char(ch: char) -> bool {
ch.is_alphanumeric() || ch == '_'
}
pub const MAX_TEXT_LEN: usize = 16 * 1024 * 1024;
#[derive(Clone, Debug, Default)]
pub struct TextBuffer {
text: String,
cursor: usize,
anchor: usize,
undo: VecDeque<Snapshot>,
redo: Vec<Snapshot>,
undo_bytes: usize,
last_edit: Option<(Instant, EditKind)>,
}
impl TextBuffer {
pub fn new() -> Self {
Self::default()
}
pub fn from_text(text: impl Into<String>) -> Self {
let text = text.into();
let end = text.len();
Self {
text,
cursor: end,
anchor: end,
..Self::default()
}
}
pub fn text(&self) -> &str {
&self.text
}
pub fn len_bytes(&self) -> usize {
self.text.len()
}
pub fn len_chars(&self) -> usize {
self.text.chars().count()
}
pub fn is_empty(&self) -> bool {
self.text.is_empty()
}
pub fn cursor(&self) -> usize {
self.cursor
}
pub fn anchor(&self) -> usize {
self.anchor
}
pub fn selection(&self) -> Option<(usize, usize)> {
if self.anchor == self.cursor {
None
} else if self.anchor < self.cursor {
Some((self.anchor, self.cursor))
} else {
Some((self.cursor, self.anchor))
}
}
pub fn has_selection(&self) -> bool {
self.anchor != self.cursor
}
pub fn selected_text(&self) -> Option<&str> {
self.selection().map(|(a, b)| &self.text[a..b])
}
fn snap(&self, byte: usize) -> usize {
crate::cluster::snap(&self.text, byte)
}
pub fn set_cursor(&mut self, byte: usize) -> bool {
let pos = self.snap(byte);
let moved = pos != self.cursor;
self.cursor = pos;
self.anchor = pos;
moved
}
pub fn set_selection(&mut self, anchor: usize, cursor: usize) {
self.anchor = self.snap(anchor);
self.cursor = self.snap(cursor);
}
pub fn select_all(&mut self) {
self.anchor = 0;
self.cursor = self.text.len();
}
pub fn clear_selection(&mut self) {
self.anchor = self.cursor;
}
fn prev_boundary(&self, pos: usize) -> usize {
crate::cluster::prev_boundary(&self.text, pos).unwrap_or(0)
}
#[allow(dead_code)]
fn prev_boundary_chars(&self, pos: usize) -> usize {
if pos == 0 {
return 0;
}
let mut p = pos.min(self.text.len());
while p > 0 && !self.text.is_char_boundary(p) {
p -= 1;
}
if p == 0 {
return 0;
}
match self.text[..p].chars().next_back() {
Some(ch) => p - ch.len_utf8(),
None => 0,
}
}
fn next_boundary(&self, pos: usize) -> usize {
crate::cluster::next_boundary(&self.text, pos).unwrap_or(self.text.len())
}
pub fn move_left(&mut self, extend: bool) -> bool {
let target = self.prev_boundary(self.cursor);
if target == self.cursor {
return false;
}
self.cursor = target;
if !extend {
self.anchor = target;
}
true
}
pub fn move_right(&mut self, extend: bool) -> bool {
let target = self.next_boundary(self.cursor);
if target == self.cursor {
return false;
}
self.cursor = target;
if !extend {
self.anchor = target;
}
true
}
pub fn move_line_start(&mut self, extend: bool) -> bool {
let target = self.line_start(self.cursor);
if target == self.cursor {
return false;
}
self.cursor = target;
if !extend {
self.anchor = target;
}
true
}
pub fn move_line_end(&mut self, extend: bool) -> bool {
let target = self.line_end(self.cursor);
if target == self.cursor {
return false;
}
self.cursor = target;
if !extend {
self.anchor = target;
}
true
}
fn record(&mut self, kind: EditKind) {
let now = Instant::now();
if kind == EditKind::Typing {
if let Some((last_at, EditKind::Typing)) = self.last_edit {
if now.duration_since(last_at) < TYPING_COALESCE {
self.last_edit = Some((now, kind));
return;
}
}
}
self.last_edit = Some((now, kind));
self.undo_bytes += self.text.len();
self.undo.push_back(Snapshot {
text: self.text.clone(),
cursor: self.cursor,
anchor: self.anchor,
});
self.redo.clear();
while self.undo.len() > HISTORY_MAX_STEPS
|| (self.undo_bytes > HISTORY_MAX_BYTES && self.undo.len() > 1)
{
if let Some(dropped) = self.undo.pop_front() {
self.undo_bytes = self.undo_bytes.saturating_sub(dropped.text.len());
} else {
break;
}
}
}
pub fn undo_depth(&self) -> usize {
self.undo.len()
}
pub fn history_bytes(&self) -> usize {
self.undo_bytes
}
pub fn can_undo(&self) -> bool {
!self.undo.is_empty()
}
pub fn can_redo(&self) -> bool {
!self.redo.is_empty()
}
pub fn undo(&mut self) -> bool {
let Some(prev) = self.undo.pop_back() else {
return false;
};
self.undo_bytes = self.undo_bytes.saturating_sub(prev.text.len());
self.redo.push(Snapshot {
text: std::mem::take(&mut self.text),
cursor: self.cursor,
anchor: self.anchor,
});
self.text = prev.text;
self.cursor = prev.cursor.min(self.text.len());
self.anchor = prev.anchor.min(self.text.len());
self.last_edit = None;
true
}
pub fn redo(&mut self) -> bool {
let Some(next) = self.redo.pop() else {
return false;
};
self.undo_bytes += self.text.len();
self.undo.push_back(Snapshot {
text: std::mem::take(&mut self.text),
cursor: self.cursor,
anchor: self.anchor,
});
self.text = next.text;
self.cursor = next.cursor.min(self.text.len());
self.anchor = next.anchor.min(self.text.len());
self.last_edit = None;
true
}
pub fn clear_history(&mut self) {
self.undo.clear();
self.redo.clear();
self.undo_bytes = 0;
self.last_edit = None;
}
pub fn move_word_left(&mut self, extend: bool) -> bool {
let target = self.word_left_target(self.cursor);
if target == self.cursor {
return false;
}
self.cursor = target;
if !extend {
self.anchor = target;
}
true
}
pub fn move_word_right(&mut self, extend: bool) -> bool {
let target = self.word_right_target(self.cursor);
if target == self.cursor {
return false;
}
self.cursor = target;
if !extend {
self.anchor = target;
}
true
}
fn word_left_target(&self, pos: usize) -> usize {
let mut idx = pos;
while idx > 0 {
let (i, ch) = self.text[..idx].char_indices().next_back().unwrap();
if is_word_char(ch) {
break;
}
idx = i;
}
while idx > 0 {
let (i, ch) = self.text[..idx].char_indices().next_back().unwrap();
if !is_word_char(ch) {
break;
}
idx = i;
}
crate::cluster::snap(&self.text, idx)
}
fn word_right_target(&self, pos: usize) -> usize {
let mut idx = pos;
while idx < self.text.len() {
let ch = self.text[idx..].chars().next().unwrap();
if !is_word_char(ch) {
break;
}
idx += ch.len_utf8();
}
while idx < self.text.len() {
let ch = self.text[idx..].chars().next().unwrap();
if is_word_char(ch) {
break;
}
idx += ch.len_utf8();
}
self.cluster_ceil(idx)
}
fn cluster_ceil(&self, pos: usize) -> usize {
let pos = pos.min(self.text.len());
if pos == 0 || pos >= self.text.len() || crate::cluster::snap(&self.text, pos) == pos {
return pos;
}
crate::cluster::next_boundary(&self.text, pos).unwrap_or(self.text.len())
}
pub fn word_range_at(&self, byte: usize) -> Option<(usize, usize)> {
if self.text.is_empty() {
return None;
}
let pos = crate::cluster::snap(&self.text, byte.min(self.text.len()));
let at_word = self.text[pos..].chars().next().is_some_and(is_word_char);
if at_word {
return Some(self.word_bounds_around(pos, true));
}
let mut p = pos;
while p < self.text.len() {
let ch = self.text[p..].chars().next().unwrap();
if is_word_char(ch) {
return Some(self.word_bounds_around(p, true));
}
p += ch.len_utf8();
}
let mut p = pos;
while p > 0 {
let (i, ch) = self.text[..p].char_indices().next_back().unwrap();
if is_word_char(ch) {
return Some(self.word_bounds_around(i, false));
}
p = i;
}
let start = {
let mut s = pos;
while s > 0 {
let (i, ch) = self.text[..s].char_indices().next_back().unwrap();
if is_word_char(ch) {
break;
}
s = i;
}
crate::cluster::snap(&self.text, s)
};
let end = {
let mut e = pos;
while e < self.text.len() {
let ch = self.text[e..].chars().next().unwrap();
if is_word_char(ch) {
break;
}
e += ch.len_utf8();
}
self.cluster_ceil(e)
};
Some((start, end))
}
fn word_bounds_around(&self, pos: usize, _right_biased: bool) -> (usize, usize) {
let mut start = pos;
while start > 0 {
let (i, ch) = self.text[..start].char_indices().next_back().unwrap();
if !is_word_char(ch) {
break;
}
start = i;
}
let mut end = pos;
while end < self.text.len() {
let ch = self.text[end..].chars().next().unwrap();
if !is_word_char(ch) {
break;
}
end += ch.len_utf8();
}
(
crate::cluster::snap(&self.text, start),
self.cluster_ceil(end),
)
}
pub fn select_word_at(&mut self, byte: usize) -> bool {
let Some((start, end)) = self.word_range_at(byte) else {
return false;
};
if start == end {
return false;
}
self.set_selection(start, end);
true
}
pub fn delete_selection(&mut self) -> bool {
if !self.has_selection() {
return false;
}
self.record(EditKind::Other);
self.delete_selection_raw();
true
}
fn delete_selection_raw(&mut self) -> bool {
let Some((start, end)) = self.selection() else {
return false;
};
self.text.replace_range(start..end, "");
self.cursor = start;
self.anchor = start;
true
}
pub fn insert_str(&mut self, s: &str) {
if s.is_empty() {
return;
}
self.record(EditKind::Typing);
self.delete_selection_raw();
let room = MAX_TEXT_LEN.saturating_sub(self.text.len());
let mut take = s.len().min(room);
while take > 0 && !s.is_char_boundary(take) {
take -= 1;
}
if take == 0 {
return;
}
self.text.insert_str(self.cursor, &s[..take]);
self.cursor += take;
self.anchor = self.cursor;
}
pub fn insert_char(&mut self, ch: char) {
let mut buf = [0u8; 4];
self.insert_str(ch.encode_utf8(&mut buf));
}
pub fn backspace(&mut self) -> bool {
if self.has_selection() {
return self.delete_selection();
}
if self.cursor == 0 {
return false;
}
self.record(EditKind::Other);
let start = self.prev_boundary(self.cursor);
self.text.replace_range(start..self.cursor, "");
self.cursor = start;
self.anchor = start;
true
}
pub fn delete_forward(&mut self) -> bool {
if self.has_selection() {
return self.delete_selection();
}
if self.cursor >= self.text.len() {
return false;
}
self.record(EditKind::Other);
let end = self.next_boundary(self.cursor);
self.text.replace_range(self.cursor..end, "");
self.anchor = self.cursor;
true
}
pub fn line_start(&self, offset: usize) -> usize {
let offset = self.snap(offset);
match self.text[..offset].rfind('\n') {
Some(idx) => idx + 1,
None => 0,
}
}
pub fn line_end(&self, offset: usize) -> usize {
let offset = self.snap(offset);
match self.text[offset..].find('\n') {
Some(idx) => offset + idx,
None => self.text.len(),
}
}
pub fn current_line(&self) -> (usize, usize) {
(self.line_start(self.cursor), self.line_end(self.cursor))
}
pub fn current_line_text(&self) -> &str {
let (start, end) = self.current_line();
&self.text[start..end]
}
pub fn char_width(ch: char, metrics: &dyn TextMetrics, style: &TextStyle) -> f32 {
let mut buf = [0u8; 4];
let s = ch.encode_utf8(&mut buf);
metrics.measure_text(s, style).w
}
pub fn x_for_offset(&self, offset: usize, metrics: &dyn TextMetrics, style: &TextStyle) -> f32 {
let start = self.line_start(offset);
let end = self.line_end(offset);
let offset = self.snap(offset).clamp(start, end);
let mut x = 0.0;
for ch in self.text[start..offset].chars() {
x += Self::char_width(ch, metrics, style);
}
x
}
pub fn cursor_x(&self, metrics: &dyn TextMetrics, style: &TextStyle) -> f32 {
self.x_for_offset(self.cursor, metrics, style)
}
pub fn offset_for_x(&self, x: f32, metrics: &dyn TextMetrics, style: &TextStyle) -> usize {
let (start, end) = self.current_line();
let mut best = start;
let mut best_dist = (x - 0.0).abs();
let mut pen = 0.0f32;
for (idx, ch) in self.text[start..end].char_indices() {
pen += Self::char_width(ch, metrics, style);
let boundary = start + idx + ch.len_utf8();
let dist = (x - pen).abs();
if dist < best_dist {
best = boundary;
best_dist = dist;
}
}
best
}
pub fn place_cursor_at_x(
&mut self,
x: f32,
metrics: &dyn TextMetrics,
style: &TextStyle,
) -> usize {
let offset = self.offset_for_x(x, metrics, style);
self.set_cursor(offset);
offset
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::geometry::Size;
struct Mono;
impl TextMetrics for Mono {
fn measure_text(&self, text: &str, _style: &TextStyle) -> Size {
let mut w = 0.0;
for ch in text.chars() {
w += if (ch as u32) >= 0x2E80 { 16.0 } else { 8.0 };
}
Size::new(w, 16.0)
}
fn line_height(&self, _style: &TextStyle) -> f32 {
16.0
}
fn scale(&self) -> f32 {
1.0
}
}
fn style() -> TextStyle {
TextStyle::default()
}
#[test]
fn insert_mixed_cjk_and_ascii() {
let mut buf = TextBuffer::new();
buf.insert_str("Hello");
buf.insert_char('中');
buf.insert_str(" Y901");
assert_eq!(buf.text(), "Hello中 Y901");
assert_eq!(buf.len_bytes(), 13);
assert_eq!(buf.cursor(), 13);
assert_eq!(buf.len_chars(), 11);
}
#[test]
fn insert_replaces_selection() {
let mut buf = TextBuffer::from_text("abcdef");
buf.set_selection(1, 4); assert_eq!(buf.selected_text(), Some("bcd"));
buf.insert_str("X");
assert_eq!(buf.text(), "aXef");
assert_eq!(buf.cursor(), 2);
assert!(!buf.has_selection());
}
#[test]
fn backspace_across_cjk_never_splits_utf8() {
let mut buf = TextBuffer::from_text("a中b");
assert_eq!(buf.cursor(), 5);
assert!(buf.backspace()); assert_eq!(buf.text(), "a中");
assert_eq!(buf.cursor(), 4);
assert!(buf.backspace()); assert_eq!(buf.text(), "a");
assert_eq!(buf.cursor(), 1);
assert!(buf.backspace()); assert_eq!(buf.text(), "");
assert_eq!(buf.cursor(), 0);
assert!(!buf.backspace(), "空缓冲区退格应返回 false");
assert!(buf.text().is_char_boundary(0));
}
#[test]
fn backspace_with_selection_deletes_selection() {
let mut buf = TextBuffer::from_text("你好世界");
buf.set_selection(3, 9); assert!(buf.backspace());
assert_eq!(buf.text(), "你界");
assert_eq!(buf.cursor(), 3);
}
#[test]
fn backspace_on_emoji_removes_whole_codepoint() {
let mut buf = TextBuffer::from_text("a😀");
assert_eq!(buf.len_bytes(), 5); buf.backspace();
assert_eq!(buf.text(), "a");
}
#[test]
fn delete_forward_removes_next_char() {
let mut buf = TextBuffer::from_text("中a");
buf.set_cursor(0);
assert!(buf.delete_forward());
assert_eq!(buf.text(), "a");
assert_eq!(buf.cursor(), 0);
}
#[test]
fn cursor_snaps_out_of_a_cluster_middle() {
let mut b = TextBuffer::from_text("कि");
for i in 0..=b.len_bytes() {
b.set_cursor(i);
let cur = b.cursor();
assert!(
cur == 0 || cur == b.len_bytes(),
"光标落在集群中间:set_cursor({i}) -> {cur}"
);
}
}
#[test]
fn backspace_deletes_a_whole_cluster_not_half_a_syllable() {
let mut b = TextBuffer::from_text("कि");
b.set_cursor(b.len_bytes());
assert!(b.backspace());
assert_eq!(b.text(), "", "整簇被删掉,实得 {:?}", b.text());
}
#[test]
fn combining_accent_is_deleted_with_its_base_letter() {
let text = "e\u{0301}";
let mut b = TextBuffer::from_text(text);
b.set_cursor(b.len_bytes());
assert!(b.backspace());
assert_eq!(b.text(), "", "重音应与基字母一起删除");
}
#[test]
fn arabic_letters_delete_one_at_a_time() {
let text = "مرحبا";
let mut b = TextBuffer::from_text(text);
b.set_cursor(b.len_bytes());
assert!(b.backspace());
assert_eq!(
b.text().chars().count(),
text.chars().count() - 1,
"只应删掉最后一个字母"
);
}
#[test]
fn cursor_snaps_to_char_boundary() {
let mut buf = TextBuffer::from_text("中");
buf.set_cursor(1);
assert_eq!(buf.cursor(), 0);
buf.set_cursor(2);
assert_eq!(buf.cursor(), 0);
buf.set_cursor(3);
assert_eq!(buf.cursor(), 3);
buf.set_cursor(999);
assert_eq!(buf.cursor(), 3);
}
#[test]
fn move_left_right_by_char() {
let mut buf = TextBuffer::from_text("a中b");
buf.set_cursor(0);
assert!(buf.move_right(false));
assert_eq!(buf.cursor(), 1); assert!(buf.move_right(false));
assert_eq!(buf.cursor(), 4); assert!(buf.move_left(false));
assert_eq!(buf.cursor(), 1); assert!(!buf.move_left(false) || buf.cursor() == 0);
}
#[test]
fn shift_move_extends_selection() {
let mut buf = TextBuffer::from_text("abc");
buf.set_cursor(0);
buf.move_right(true);
buf.move_right(true);
assert_eq!(buf.selection(), Some((0, 2)));
assert_eq!(buf.selected_text(), Some("ab"));
buf.move_left(true);
assert_eq!(buf.selection(), Some((0, 1)));
}
#[test]
fn x_for_offset_counts_cjk_as_two_cells() {
let buf = TextBuffer::from_text("a中b");
let s = style();
assert_eq!(buf.x_for_offset(0, &Mono, &s), 0.0);
assert_eq!(buf.x_for_offset(1, &Mono, &s), 8.0);
assert_eq!(buf.x_for_offset(4, &Mono, &s), 24.0);
assert_eq!(buf.x_for_offset(5, &Mono, &s), 32.0);
}
#[test]
fn offset_for_x_picks_nearest_boundary() {
let mut buf = TextBuffer::from_text("a中b");
buf.set_cursor(0);
let s = style();
assert_eq!(buf.offset_for_x(-5.0, &Mono, &s), 0);
assert_eq!(buf.offset_for_x(3.0, &Mono, &s), 0); assert_eq!(buf.offset_for_x(9.0, &Mono, &s), 1); assert_eq!(buf.offset_for_x(15.0, &Mono, &s), 1); assert_eq!(buf.offset_for_x(17.0, &Mono, &s), 4); assert_eq!(buf.offset_for_x(30.0, &Mono, &s), 5); assert_eq!(buf.offset_for_x(999.0, &Mono, &s), 5); }
#[test]
fn offset_roundtrip_through_x() {
let text = "Hello 你好 Y901";
let buf = TextBuffer::from_text(text);
let s = style();
for (byte, _ch) in text.char_indices() {
let x = buf.x_for_offset(byte, &Mono, &s);
let back = buf.offset_for_x(x, &Mono, &s);
assert_eq!(back, byte, "byte {byte} 经 X 往返后变成 {back}");
}
let end = text.len();
let x = buf.x_for_offset(end, &Mono, &s);
assert_eq!(buf.offset_for_x(x, &Mono, &s), end);
}
#[test]
fn click_places_cursor() {
let mut buf = TextBuffer::from_text("ab中");
buf.place_cursor_at_x(20.0, &Mono, &style());
assert_eq!(buf.cursor(), 2); assert!(!buf.has_selection());
}
#[test]
fn line_bounds_and_measure_are_per_line() {
let mut buf = TextBuffer::from_text("abc\ndefg");
assert_eq!(buf.line_start(0), 0);
assert_eq!(buf.line_end(0), 3);
buf.set_cursor(6); assert_eq!(buf.current_line(), (4, 8));
assert_eq!(buf.current_line_text(), "defg");
let s = style();
assert_eq!(buf.x_for_offset(4, &Mono, &s), 0.0);
assert_eq!(buf.x_for_offset(6, &Mono, &s), 16.0);
assert_eq!(buf.offset_for_x(17.0, &Mono, &s), 6);
}
#[test]
fn undo_is_a_stack_and_redo_mirrors_it() {
let mut buf = TextBuffer::new();
buf.insert_str("a");
assert!(buf.backspace());
buf.insert_str("b");
assert_eq!(buf.text(), "b");
assert!(buf.undo(), "应有可撤销步骤");
assert_eq!(buf.text(), "", "撤销插入 b → 空");
assert!(buf.undo());
assert_eq!(buf.text(), "a", "再撤销删除 → 回到 a");
assert!(buf.undo());
assert_eq!(buf.text(), "", "再撤销第一次插入 → 空");
assert!(!buf.undo(), "到底之后必须返回 false(不是 panic)");
assert!(buf.redo());
assert_eq!(buf.text(), "a", "重做第一次插入");
assert!(buf.redo());
assert_eq!(buf.text(), "", "重做删除");
assert!(buf.redo());
assert_eq!(buf.text(), "b", "重做第二次插入");
assert!(!buf.redo());
}
#[test]
fn consecutive_typing_coalesces_but_delete_breaks_the_run() {
let mut buf = TextBuffer::new();
buf.insert_str("x");
buf.insert_str("y");
buf.insert_str("z");
assert_eq!(buf.text(), "xyz");
assert_eq!(buf.undo_depth(), 1, "连续输入应合并为一步");
buf.undo();
assert_eq!(buf.text(), "");
let mut buf = TextBuffer::from_text("");
buf.insert_str("a");
buf.backspace();
assert_eq!(buf.text(), "");
assert_eq!(buf.undo_depth(), 2, "输入 + 删除是两步(删除不可合并)");
}
#[test]
fn history_respects_the_step_limit() {
let mut buf = TextBuffer::new();
for _ in 0..(HISTORY_MAX_STEPS + 50) {
buf.insert_str("a");
buf.record(EditKind::Other);
}
assert!(
buf.undo_depth() <= HISTORY_MAX_STEPS,
"撤销步数必须有上限,实得 {}",
buf.undo_depth()
);
let mut last = buf.text().len();
while buf.undo() {
let now = buf.text().len();
assert!(now <= last, "撤销后文本变长了:{last} → {now}");
last = now;
}
}
#[test]
fn history_respects_the_byte_budget() {
let mut buf = TextBuffer::new();
let chunk = "x".repeat(64 * 1024);
for _ in 0..16 {
buf.insert_str(&chunk);
buf.record(EditKind::Other);
}
assert!(
buf.history_bytes() <= HISTORY_MAX_BYTES,
"快照总字节必须受 HISTORY_MAX_BYTES 约束,实得 {}",
buf.history_bytes()
);
}
#[test]
fn word_moves_land_on_word_edges() {
let mut buf = TextBuffer::from_text("hello brave world");
assert_eq!(buf.cursor(), 17);
buf.move_word_left(false);
assert_eq!(buf.cursor(), 12, "world 的词首");
buf.move_word_left(false);
assert_eq!(buf.cursor(), 6, "brave 的词首");
buf.move_word_left(false);
assert_eq!(buf.cursor(), 0, "hello 的词首");
assert!(!buf.move_word_left(false), "已在开头,不再移动");
buf.move_word_right(false);
assert_eq!(buf.cursor(), 6, "hello 之后的下一个词首是 brave");
buf.move_word_right(false);
assert_eq!(buf.cursor(), 12, "再下一站是 world 的词首");
buf.move_word_right(false);
assert_eq!(buf.cursor(), 17, "最后一个词的下一站是末尾");
assert!(!buf.move_word_right(false), "已在末尾,不再移动");
}
#[test]
fn word_moves_skip_punctuation_and_whitespace_runs() {
let mut buf = TextBuffer::from_text("foo --- bar");
buf.move_word_left(false);
assert_eq!(buf.cursor(), 8, "bar 的词首");
buf.move_word_left(false);
assert_eq!(buf.cursor(), 0, "一次跨过 ' --- ' 到 foo 的词首");
}
#[test]
fn word_range_at_selects_the_word_or_the_neighbouring_one() {
let text = "alpha beta gamma";
let buf = TextBuffer::from_text(text);
assert_eq!(buf.word_range_at(7), Some((6, 10)), "点在词内 → 该词");
assert_eq!(buf.word_range_at(5), Some((6, 10)));
let buf = TextBuffer::from_text("alpha ");
assert_eq!(buf.word_range_at(5), Some((0, 5)));
let buf = TextBuffer::from_text("***");
assert_eq!(buf.word_range_at(1), Some((0, 3)));
assert_eq!(TextBuffer::new().word_range_at(0), None);
}
#[test]
fn word_range_never_splits_a_grapheme_cluster() {
let text = "cafe\u{301} bar";
let buf = TextBuffer::from_text(text);
let (start, end) = buf.word_range_at(6).expect("空格右侧有词");
assert_eq!(&text[start..end], "bar");
let (s2, e2) = buf.word_range_at(0).expect("左侧有词");
assert_eq!(
&text[s2..e2],
"cafe\u{301}",
"整个 cafe\u{301} 必须一次选中(e 与重音不拆开)"
);
}
#[test]
fn select_word_at_reports_whether_it_selected_anything() {
let mut buf = TextBuffer::from_text("one two");
assert!(buf.select_word_at(6));
assert_eq!(buf.selection(), Some((4, 7)));
let mut empty = TextBuffer::new();
assert!(!empty.select_word_at(0), "空文本选不出词");
}
#[test]
fn empty_buffer_measurements_are_zero() {
let buf = TextBuffer::new();
let s = style();
assert_eq!(buf.x_for_offset(0, &Mono, &s), 0.0);
assert_eq!(buf.offset_for_x(100.0, &Mono, &s), 0);
assert_eq!(buf.current_line(), (0, 0));
}
}