use unicode_segmentation::UnicodeSegmentation;
pub fn char_len(text: &str) -> usize {
text.chars().count()
}
pub fn clamp(text: &str, caret: usize) -> usize {
cluster_floor(text, caret.min(char_len(text)))
}
pub fn byte_of(text: &str, at: usize) -> usize {
text.char_indices().nth(at).map_or(text.len(), |(i, _)| i)
}
pub fn char_of(text: &str, byte: usize) -> usize {
text[..byte.min(text.len())].chars().count()
}
fn cluster_before(text: &str, at: usize) -> usize {
if text.is_ascii() {
return at.saturating_sub(1);
}
let mut start = 0;
let mut prev = 0;
for g in text.graphemes(true) {
if start >= at {
break;
}
prev = start;
start += g.chars().count();
}
prev
}
fn cluster_after(text: &str, at: usize) -> usize {
if text.is_ascii() {
return (at + 1).min(text.len());
}
let mut end = 0;
for g in text.graphemes(true) {
end += g.chars().count();
if end > at {
return end;
}
}
end
}
fn cluster_floor(text: &str, at: usize) -> usize {
if text.is_ascii() {
return at.min(text.len());
}
let mut start = 0;
for g in text.graphemes(true) {
let len = g.chars().count();
if start + len > at {
return start;
}
start += len;
}
start
}
fn word_flags(text: &str) -> Vec<bool> {
let joins = |c: char| !c.is_control() && unicode_width::UnicodeWidthChar::width(c) == Some(0);
let mut flags: Vec<bool> = Vec::with_capacity(text.len());
for c in text.chars() {
let flag = match flags.last() {
Some(&prev) if joins(c) => prev,
_ => crate::widgets::editor::is_word_char(c),
};
flags.push(flag);
}
flags
}
fn word_start_before(text: &str, at: usize) -> usize {
let word = word_flags(text);
let mut i = at.min(word.len());
while i > 0 && !word[i - 1] {
i -= 1;
}
while i > 0 && word[i - 1] {
i -= 1;
}
cluster_floor(text, i)
}
fn word_end_after(text: &str, at: usize) -> usize {
let word = word_flags(text);
let mut i = at.min(word.len());
while i < word.len() && !word[i] {
i += 1;
}
while i < word.len() && word[i] {
i += 1;
}
cluster_floor(text, i).max(at.min(word.len()))
}
pub fn caret_left(text: &str, caret: usize, word: bool) -> usize {
let at = clamp(text, caret);
if word {
word_start_before(text, at)
} else {
cluster_before(text, at)
}
}
pub fn caret_right(text: &str, caret: usize, word: bool) -> usize {
let at = clamp(text, caret);
if word {
word_end_after(text, at)
} else {
cluster_after(text, at)
}
}
pub fn insert_at(text: &str, caret: usize, add: &str) -> (String, usize) {
let at = clamp(text, caret);
let added: String = add.chars().filter(|c| !c.is_control()).collect();
if added.is_empty() {
return (text.to_string(), at);
}
let b = byte_of(text, at);
let mut out = String::with_capacity(text.len() + added.len());
out.push_str(&text[..b]);
out.push_str(&added);
out.push_str(&text[b..]);
let end = at + char_len(&added);
let floor = cluster_floor(&out, end);
let caret = if floor == end {
end
} else {
cluster_after(&out, floor)
};
(out, caret)
}
pub fn delete_before(text: &str, caret: usize, word: bool) -> (String, usize) {
let at = clamp(text, caret);
let from = caret_left(text, at, word);
if from == at {
return (text.to_string(), at);
}
(cut(text, from, at), from)
}
pub fn delete_at(text: &str, caret: usize, word: bool) -> (String, usize) {
let at = clamp(text, caret);
let to = caret_right(text, at, word);
if to == at {
return (text.to_string(), at);
}
(cut(text, at, to), at)
}
fn cut(text: &str, from: usize, to: usize) -> String {
let (a, b) = (byte_of(text, from), byte_of(text, to));
let mut out = String::with_capacity(text.len() - (b - a));
out.push_str(&text[..a]);
out.push_str(&text[b..]);
out
}
struct Cluster {
start: usize,
width: usize,
}
fn clusters(text: &str) -> Vec<Cluster> {
let mut start = 0;
text.graphemes(true)
.map(|g| {
let len = g.chars().count();
let c = Cluster {
start,
width: unicode_width::UnicodeWidthStr::width(g),
};
start += len;
c
})
.collect()
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Window {
pub start: usize,
pub end: usize,
pub caret_cell: usize,
}
pub fn window(text: &str, caret: usize, avail: usize) -> Window {
let cl = clusters(text);
let total = char_len(text);
let caret = clamp(text, caret);
let avail = avail.max(1);
let at = cl.iter().position(|c| c.start >= caret).unwrap_or(cl.len());
let before_w: usize = cl[..at].iter().map(|c| c.width).sum();
let mut first = 0;
let mut dropped = 0;
while first < at && before_w - dropped >= avail {
dropped += cl[first].width;
first += 1;
}
let caret_cell = before_w - dropped;
let mut used = caret_cell;
let mut last = at;
if last < cl.len() {
let w = cl[last].width.max(1);
if used + w <= avail {
used += w;
last += 1;
while last < cl.len() {
let w = cl[last].width;
if used + w > avail {
break;
}
used += w;
last += 1;
}
}
}
Window {
start: cl.get(first).map_or(total, |c| c.start),
end: cl.get(last).map_or(total, |c| c.start),
caret_cell,
}
}
pub fn char_at_cell(text: &str, start: usize, cell: usize) -> usize {
let mut at = 0;
for c in clusters(text).iter().filter(|c| c.start >= start) {
if cell < at + c.width {
return c.start;
}
at += c.width;
}
char_len(text)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_click_cell_maps_to_the_char_under_it() {
assert_eq!(char_at_cell("abc", 0, 0), 0);
assert_eq!(char_at_cell("abc", 0, 2), 2);
assert_eq!(char_at_cell("abc", 0, 9), 3, "past the end");
assert_eq!(char_at_cell("abcdef", 2, 1), 3, "a scrolled row");
assert_eq!(char_at_cell("日本x", 0, 1), 0);
assert_eq!(char_at_cell("日本x", 0, 2), 1);
assert_eq!(char_at_cell("日本x", 0, 4), 2);
}
#[test]
fn steps_move_by_cluster_not_by_code_point() {
let t = "ae\u{301}b";
assert_eq!(caret_right(t, 1, false), 3, "over e + accent in one step");
assert_eq!(caret_left(t, 3, false), 1);
let f = "x🇪🇸y";
assert_eq!(caret_right(f, 1, false), 3);
assert_eq!(caret_left(f, 3, false), 1);
assert_eq!(caret_left("ab", 0, false), 0);
assert_eq!(caret_right("ab", 2, false), 2);
assert_eq!(caret_right("ab", 99, false), 2, "a stale caret clamps");
}
#[test]
fn word_steps_skip_a_run_then_a_word() {
let t = "foo bar_baz, qux";
assert_eq!(caret_left(t, 17, true), 14, "back over qux");
assert_eq!(caret_left(t, 14, true), 5, "back over `, ` and bar_baz");
assert_eq!(caret_left(t, 5, true), 0);
assert_eq!(caret_right(t, 0, true), 3);
assert_eq!(caret_right(t, 3, true), 12, "over the gap and bar_baz");
assert_eq!(caret_right(t, 17, true), 17);
assert_eq!(caret_left("привет мир", 10, true), 7);
}
#[test]
fn insert_lands_at_the_caret_and_drops_control_chars() {
assert_eq!(insert_at("ac", 1, "b"), ("abc".to_string(), 2));
assert_eq!(insert_at("ac", 9, "b"), ("acb".to_string(), 3));
assert_eq!(insert_at("ac", 0, "x\ny\tz"), ("xyzac".to_string(), 3));
assert_eq!(insert_at("ac", 1, "\n"), ("ac".to_string(), 1));
assert_eq!(insert_at("日本", 1, "語"), ("日語本".to_string(), 2));
}
#[test]
fn deletes_cut_a_cluster_or_a_word_and_keep_the_caret_honest() {
assert_eq!(delete_before("abc", 2, false), ("ac".to_string(), 1));
assert_eq!(delete_before("abc", 0, false), ("abc".to_string(), 0));
assert_eq!(delete_at("abc", 1, false), ("ac".to_string(), 1));
assert_eq!(delete_at("abc", 3, false), ("abc".to_string(), 3));
assert_eq!(delete_before("ae\u{301}", 3, false), ("a".to_string(), 1));
assert_eq!(delete_before("foo bar", 7, true), ("foo ".to_string(), 4));
assert_eq!(delete_at("foo bar", 0, true), (" bar".to_string(), 0));
}
#[test]
fn window_keeps_the_caret_in_view_and_inside_the_row() {
let w = window("abc", 3, 10);
assert_eq!((w.start, w.end, w.caret_cell), (0, 3, 3));
let w = window("abcdef", 2, 10);
assert_eq!((w.start, w.end, w.caret_cell), (0, 6, 2));
let w = window("abcdefghij", 10, 5);
assert_eq!((w.start, w.end, w.caret_cell), (6, 10, 4));
let w = window("abcdefghij", 0, 5);
assert_eq!((w.start, w.end, w.caret_cell), (0, 5, 0));
for caret in 0..=10 {
let w = window("abcdefghij", caret, 5);
assert!(w.caret_cell < 5, "caret {caret}: {w:?}");
assert!(w.start <= caret && caret <= w.end.max(caret));
}
}
#[test]
fn window_counts_wide_characters_in_cells() {
let w = window("日本語", 0, 5);
assert_eq!((w.start, w.end), (0, 2), "the third does not straddle");
let w = window("日本語", 3, 5);
assert!(w.caret_cell < 5);
assert_eq!(w.start, 1, "one char scrolled off to fit the caret");
}
#[test]
fn a_word_walk_keeps_a_combining_mark_with_its_base() {
let t = "e\u{301}x y";
assert_eq!(caret_right(t, 0, true), 3);
assert_eq!(caret_left(t, 3, true), 0);
}
#[test]
fn word_flags_classify_as_the_editor_does() {
let t = "e\u{301}x \u{301}y-\u{FE0F}_z";
let chars: Vec<char> = t.chars().collect();
let want: Vec<bool> = (0..chars.len())
.map(|i| crate::widgets::editor::word_char_at(&chars, i))
.collect();
assert_eq!(word_flags(t), want);
}
#[test]
fn typing_before_a_lone_accent_puts_the_caret_after_the_cluster_it_makes() {
let (t, c) = insert_at("\u{301}x", 0, "e");
assert_eq!((t.as_str(), c), ("e\u{301}x", 2));
let (t, c) = insert_at(&t, c, "d");
assert_eq!((t.as_str(), c), ("e\u{301}dx", 3));
}
#[test]
fn an_emoji_cluster_is_one_glyph_for_width_and_clicks() {
let t = "a\u{1F44D}\u{1F3FD}b";
let w = window(t, 3, 4);
assert_eq!((w.start, w.end, w.caret_cell), (0, 4, 3));
assert_eq!(char_at_cell(t, 0, 2), 1);
assert_eq!(char_at_cell(t, 0, 3), 3);
assert_eq!(clamp(t, 2), 1);
}
}