1use std::borrow::Cow;
5use std::ops::Range;
6
7use unicode_segmentation::UnicodeSegmentation;
8use unicode_width::UnicodeWidthStr;
9
10pub const ELLIPSIS: &str = "…";
12
13#[must_use]
15pub fn width(text: &str) -> u16 {
16 let cells = if is_printable_ascii(text) { text.len() } else { text.width() };
17 u16::try_from(cells).unwrap_or(u16::MAX)
18}
19
20#[must_use]
22pub fn grapheme_width(grapheme: &str) -> u16 {
23 width(grapheme)
24}
25
26pub(crate) fn is_printable_ascii(text: &str) -> bool {
29 text.bytes().all(|byte| matches!(byte, b' '..=b'~'))
30}
31
32#[must_use]
34pub fn truncate(text: &str, max: u16) -> Cow<'_, str> {
35 if width(text) <= max {
36 return Cow::Borrowed(text);
37 }
38 if max == 0 {
39 return Cow::Borrowed("");
40 }
41 let budget = max - 1;
42 let mut used = 0u16;
43 let mut out = String::new();
44 for grapheme in text.graphemes(true) {
45 let w = grapheme_width(grapheme);
46 if used + w > budget {
47 break;
48 }
49 used += w;
50 out.push_str(grapheme);
51 }
52 out.push_str(ELLIPSIS);
53 Cow::Owned(out)
54}
55
56#[must_use]
73pub fn truncate_middle(text: &str, max: u16) -> Cow<'_, str> {
74 if width(text) <= max {
75 return Cow::Borrowed(text);
76 }
77 if max == 0 {
78 return Cow::Borrowed("");
79 }
80 let budget = max - 1;
81 let graphemes: Vec<&str> = text.graphemes(true).collect();
82 let (mut head, mut head_used) = fitting(graphemes.iter(), budget / 2);
83 let (tail, tail_used) = fitting(graphemes[head..].iter().rev(), budget - head_used);
84 let (more, more_used) = fitting(graphemes[head..graphemes.len() - tail].iter(), budget - head_used - tail_used);
86 head += more;
87 head_used += more_used;
88 debug_assert!(head_used + tail_used <= budget);
89 let mut out = graphemes[..head].concat();
90 out.push_str(ELLIPSIS);
91 out.push_str(&graphemes[graphemes.len() - tail..].concat());
92 Cow::Owned(out)
93}
94
95fn fitting<'a>(graphemes: impl Iterator<Item = &'a &'a str>, budget: u16) -> (usize, u16) {
97 let mut count = 0;
98 let mut used = 0u16;
99 for grapheme in graphemes {
100 let w = grapheme_width(grapheme);
101 if used + w > budget {
102 break;
103 }
104 used += w;
105 count += 1;
106 }
107 (count, used)
108}
109
110#[must_use]
123pub fn wrap(text: &str, max: u16) -> Vec<String> {
124 wrap_ranges(text, max).into_iter().map(|range| text[range].to_owned()).collect()
125}
126
127#[must_use]
130pub fn wrap_ranges(text: &str, max: u16) -> Vec<Range<usize>> {
131 let mut lines = Vec::new();
132 if max == 0 {
133 return lines;
134 }
135 let mut paragraph_start = 0;
136 for paragraph in text.split('\n') {
137 let mut line: Option<Range<usize>> = None;
138 let mut line_width = 0u16;
139 for (offset, word, is_space) in runs(paragraph).flat_map(|(offset, run, space)| pieces(offset, run, space)) {
140 let start = paragraph_start + offset;
141 let end = start + word.len();
142 let word_width = width(word);
143 if is_space {
144 match &mut line {
145 Some(current) if line_width + word_width <= max => {
146 current.end = end;
147 line_width += word_width;
148 }
149 Some(_) => {
150 lines.push(trim_end(text, line.take()));
151 line_width = 0;
152 }
153 None => {}
154 }
155 continue;
156 }
157 if line_width + word_width <= max {
158 line = Some(line.map_or(start..end, |current| current.start..end));
159 line_width += word_width;
160 continue;
161 }
162 if line.is_some() && word_width <= max {
163 lines.push(trim_end(text, line.take()));
164 line = Some(start..end);
165 line_width = word_width;
166 continue;
167 }
168 let graphemes: Vec<(usize, &str)> = word.grapheme_indices(true).collect();
169 let tail =
173 graphemes.iter().rposition(|(_, g)| !is_closing_punctuation(g) && !is_no_break_space(g)).unwrap_or(0);
174 let tail_width: u16 = graphemes[tail..].iter().map(|(_, g)| grapheme_width(g)).sum();
175 for (index, (g_offset, grapheme)) in graphemes.iter().enumerate() {
176 let g_start = start + g_offset;
177 let g_end = g_start + grapheme.len();
178 let w = grapheme_width(grapheme);
179 let needed = if index == tail && tail_width <= max { tail_width } else { w };
180 if line_width + needed > max && line.is_some() {
181 lines.push(trim_end(text, line.take()));
182 line_width = 0;
183 }
184 line = Some(line.map_or(g_start..g_end, |current| current.start..g_end));
185 line_width += w;
186 }
187 }
188 lines.push(line.map_or(paragraph_start..paragraph_start, |current| trim_end(text, Some(current))));
189 paragraph_start += paragraph.len() + 1;
190 }
191 lines
192}
193
194fn runs(paragraph: &str) -> impl Iterator<Item = (usize, &str, bool)> {
198 let mut position = 0;
199 std::iter::from_fn(move || {
200 let start = position;
201 let (space, first) = char_at(paragraph, start)?;
202 position += first;
203 while let Some((_, len)) = char_at(paragraph, position).filter(|&(next, _)| next == space) {
204 position += len;
205 }
206 Some((start, ¶graph[start..position], space))
207 })
208}
209
210fn pieces(offset: usize, run: &str, space: bool) -> impl Iterator<Item = (usize, &str, bool)> {
213 let mut ends = Vec::new();
214 if !space && !is_printable_ascii(run) {
215 let graphemes: Vec<(usize, &str)> = run.grapheme_indices(true).collect();
216 ends.extend(graphemes.windows(2).filter(|pair| may_break_between(pair[0].1, pair[1].1)).map(|pair| pair[1].0));
217 }
218 ends.push(run.len());
219 let mut start = 0;
220 ends.into_iter().map(move |end| {
221 let piece = (offset + start, &run[start..end], space);
222 start = end;
223 piece
224 })
225}
226
227fn may_break_between(before: &str, after: &str) -> bool {
230 (is_cjk(before) || is_cjk(after)) && !is_closing_punctuation(after) && !is_opening_punctuation(before)
231}
232
233fn is_cjk(grapheme: &str) -> bool {
236 grapheme.chars().next().is_some_and(|c| {
237 matches!(c,
238 '\u{2E80}'..='\u{2FDF}' | '\u{3000}'..='\u{30FF}' | '\u{31C0}'..='\u{31FF}' | '\u{3400}'..='\u{4DBF}' | '\u{4E00}'..='\u{9FFF}' | '\u{F900}'..='\u{FAFF}' | '\u{FE30}'..='\u{FE4F}' | '\u{FF00}'..='\u{FFEF}' | '\u{20000}'..='\u{3FFFF}') })
248}
249
250fn char_at(text: &str, index: usize) -> Option<(bool, usize)> {
254 let byte = *text.as_bytes().get(index)?;
255 if byte.is_ascii() {
256 return Some((char::from(byte).is_whitespace(), 1));
257 }
258 text.get(index..)?.chars().next().map(|c| (c.is_whitespace() && !is_no_break(c), c.len_utf8()))
259}
260
261fn is_no_break(c: char) -> bool {
264 matches!(c, '\u{A0}' | '\u{202F}' | '\u{2007}')
265}
266
267fn is_no_break_space(grapheme: &str) -> bool {
268 grapheme.chars().all(is_no_break)
269}
270
271fn is_closing_punctuation(grapheme: &str) -> bool {
275 grapheme.chars().all(|c| {
276 matches!(
277 c,
278 '.' | ',' | ';' | ':' | '!' | '?' | ')' | ']' | '}' | '"' | '\'' | '…' | '’' | '”' | '»'
279 | '、' | '。' | '〃' | '々' | '〉' | '》' | '」' | '』' | '】' | '〕' | '〗' | '〙' | '〛' | '〞' | '〟'
280 | '〻' | '・' | 'ー' | 'ゝ' | 'ゞ' | 'ヽ' | 'ヾ' | '゛' | '゜' | '゠' | '‼' | '⁇' | '⁈' | '⁉'
281 | 'ぁ' | 'ぃ' | 'ぅ' | 'ぇ' | 'ぉ' | 'っ' | 'ゃ' | 'ゅ' | 'ょ' | 'ゎ' | 'ゕ' | 'ゖ'
282 | 'ァ' | 'ィ' | 'ゥ' | 'ェ' | 'ォ' | 'ッ' | 'ャ' | 'ュ' | 'ョ' | 'ヮ' | 'ヵ' | 'ヶ'
283 | '\u{31F0}'..='\u{31FF}'
284 | '!' | ')' | ',' | '.' | ':' | ';' | '?' | ']' | '}' | '⦆' | '。' | '」' | '、' | '・' | 'ー'
285 | 'ァ'..='ッ' | '゙' | '゚' | '%' | '〜' | '~'
286 )
287 })
288}
289
290fn is_opening_punctuation(grapheme: &str) -> bool {
292 grapheme.chars().all(|c| {
293 matches!(
294 c,
295 '(' | '['
296 | '{'
297 | '‘'
298 | '“'
299 | '«'
300 | '〈'
301 | '《'
302 | '「'
303 | '『'
304 | '【'
305 | '〔'
306 | '〖'
307 | '〘'
308 | '〚'
309 | '〝'
310 | '('
311 | '['
312 | '{'
313 | '⦅'
314 | '「'
315 )
316 })
317}
318
319fn trim_end(text: &str, range: Option<Range<usize>>) -> Range<usize> {
320 let range = range.unwrap_or(0..0);
321 let trimmed = text[range.clone()].trim_end();
322 range.start..range.start + trimmed.len()
323}
324
325#[cfg(test)]
326mod tests {
327 use super::*;
328
329 #[test]
330 fn measures_wide_and_combining_text() {
331 assert_eq!(width("abc"), 3);
332 assert_eq!(width("çığ"), 3);
333 assert_eq!(width("界"), 2);
334 assert_eq!(width("e\u{301}"), 1);
335 }
336
337 #[test]
338 fn truncates_with_ellipsis_by_cells() {
339 assert_eq!(truncate("quvyta", 10), "quvyta");
340 assert_eq!(truncate("quvyta-framework", 8), "quvyta-…");
341 assert_eq!(truncate("界界界", 4), "界…");
342 assert_eq!(truncate("abc", 0), "");
343 assert_eq!(width(&truncate("quvyta-framework", 8)), 8);
344 }
345
346 #[test]
347 fn truncate_middle_returns_text_that_fits_unchanged() {
348 assert!(matches!(truncate_middle("launcher.conf", 13), Cow::Borrowed("launcher.conf")));
349 assert!(matches!(truncate_middle("", 0), Cow::Borrowed("")));
350 }
351
352 #[test]
353 fn truncate_middle_keeps_head_and_tail_of_a_path() {
354 let path = "~/.config/quvyta/launcher.conf";
355 assert_eq!(truncate_middle(path, 25), "~/.config/qu…auncher.conf");
356 assert_eq!(truncate_middle(path, 20), "~/.config…ncher.conf", "the tail gets the odd cell");
357 assert_eq!(truncate_middle(path, 5), "~/…nf");
358 for max in 0..=30 {
359 assert_eq!(width(&truncate_middle(path, max)), max, "{max}");
360 }
361 }
362
363 #[test]
364 fn truncate_middle_never_splits_wide_characters() {
365 let path = "~/文書/設定/launcher.conf";
366 assert_eq!(width(path), 25);
367 assert_eq!(truncate_middle(path, 12), "~/文…er.conf");
369 assert_eq!(truncate_middle("界界界界界界", 6), "界…界", "one cell stays empty rather than half a character");
370 for max in 0..=25 {
371 assert!(width(&truncate_middle(path, max)) <= max, "{max}");
372 assert!(width(&truncate_middle("界界界界界界", max)) <= max, "{max}");
373 }
374 }
375
376 #[test]
377 fn truncate_middle_keeps_combining_marks_with_their_letter() {
378 let accented = "e\u{301}e\u{301}e\u{301}e\u{301}e\u{301}";
379 assert_eq!(truncate_middle(accented, 4), "e\u{301}…e\u{301}e\u{301}");
380 assert_eq!(truncate_middle("café\u{301}s/ünïcödé\u{301}", 7), "caf…ödé\u{301}");
381 }
382
383 #[test]
384 fn truncate_middle_at_tiny_widths() {
385 assert_eq!(truncate_middle("launcher.conf", 0), "");
386 assert_eq!(truncate_middle("launcher.conf", 1), "…");
387 assert_eq!(truncate_middle("launcher.conf", 2), "…f");
388 assert_eq!(truncate_middle("文書", 2), "…", "a wide tail does not fit in one cell");
389 assert_eq!(truncate_middle("文書", 3), "…書");
390 }
391
392 #[test]
393 fn wraps_words_and_breaks_long_ones() {
394 assert_eq!(wrap("the quick brown fox", 9), vec!["the quick", "brown fox"]);
395 assert_eq!(wrap("abcdefghij", 4), vec!["abcd", "efgh", "ij"]);
396 assert_eq!(wrap("a\n\nb", 5), vec!["a", "", "b"]);
397 assert_eq!(wrap("one two", 4), vec!["one", "two"]);
398 assert_eq!(wrap("at word boundaries, never", 18), vec!["at word", "boundaries, never"], "a comma stays");
399 assert_eq!(wrap("deploy 2026.9.1 done", 12), vec!["deploy", "2026.9.1", "done"]);
400 assert_eq!(wrap("abcdefgh.", 8), vec!["abcdefg", "h."], "a broken word keeps its full stop company");
401 assert_eq!(wrap("add abcdefghijk),", 8), vec!["add abcd", "efghij", "k),"]);
402 assert_eq!(wrap("abcdefghijk.", 4), vec!["abcd", "efgh", "ijk."]);
403 assert_eq!(wrap("........", 4), vec!["....", "...."], "all punctuation still breaks");
404 assert!(wrap("x", 0).is_empty());
405 }
406
407 #[test]
408 fn cjk_closing_punctuation_never_starts_a_line() {
409 assert_eq!(wrap("これはテストです。", 16), vec!["これはテストで", "す。"], "a full stop keeps its company");
410 assert_eq!(wrap("你好,世界", 4), vec!["你", "好,", "世界"], "an ideographic comma stays");
411 assert_eq!(
412 wrap("彼は「はい」と言った", 6),
413 vec!["彼は", "「は", "い」と", "言った"],
414 "brackets hold on to what they enclose"
415 );
416 assert_eq!(wrap("コーヒー", 4), vec!["コー", "ヒー"], "the long vowel mark stays after its kana");
417 assert_eq!(wrap("ちょっと", 6), vec!["ちょっ", "と"], "a small kana stays after the one it follows");
418 for text in ["一二三四五六七八九十、一二三。", "(全角)です!次は?", "設定を保存しました!次へ進みますか?"]
419 {
420 for max in 4..12 {
421 for line in wrap(text, max).iter().skip(1) {
422 let first = line.graphemes(true).next().unwrap_or_default();
423 assert!(!is_closing_punctuation(first), "{text:?} at {max}: a line starts with {first:?}");
424 }
425 for line in wrap(text, max) {
426 let last = line.graphemes(true).next_back().unwrap_or_default();
427 assert!(
428 line.graphemes(true).count() == 1 || !is_opening_punctuation(last),
429 "{text:?} at {max}: a line ends with {last:?}"
430 );
431 }
432 }
433 }
434 }
435
436 #[test]
437 fn cjk_text_without_spaces_breaks_between_ideographs() {
438 assert_eq!(wrap("防火墙已启用", 4), vec!["防火", "墙已", "启用"]);
439 assert_eq!(wrap("状态 防火墙已启用", 10), vec!["状态 防火", "墙已启用"], "the rest of a line is filled");
440 assert_eq!(wrap("hello 你好世界", 8), vec!["hello 你", "好世界"]);
441 assert_eq!(wrap("Rust で書く", 7), vec!["Rust で", "書く"]);
442 assert_eq!(wrap("パッケージを更新", 10), vec!["パッケージ", "を更新"]);
443 assert_eq!(wrap("안녕하세요 세계", 10), vec!["안녕하세요", "세계"], "Korean words stay whole");
444 }
445
446 #[test]
447 fn no_break_spaces_belong_to_the_word() {
448 assert_eq!(wrap("Est-ce vrai\u{a0}? Oui", 11), vec!["Est-ce", "vrai\u{a0}? Oui"]);
449 assert_eq!(wrap("Attention\u{202f}: fin", 10), vec!["Attentio", "n\u{202f}: fin"]);
450 assert_eq!(wrap("total 10\u{2007}000 kr", 8), vec!["total", "10\u{2007}000", "kr"]);
451 assert_eq!(
452 wrap("Vraiment\u{a0}?", 9),
453 vec!["Vraimen", "t\u{a0}?"],
454 "a broken word keeps its space with the mark"
455 );
456 assert_eq!(wrap("a b\u{a0}c", 3), vec!["a", "b\u{a0}c"]);
457 }
458
459 #[test]
462 fn unusual_text_measures_and_wraps_as_before() {
463 type Case = (&'static str, u16, &'static [&'static str], &'static [Range<usize>], &'static str);
465 let cases: [Case; 12] = [
466 ("a\u{a0}b c\u{a0}\u{a0}dd", 3, &["a\u{a0}b", "c", "dd"], &[0..4, 5..6, 10..12], "a\u{a0}…"),
467 ("x\u{3000}y z", 2, &["x", "y", "z"], &[0..1, 4..5, 6..7], "x…"),
468 ("tab\there and\u{b}vt", 4, &["tab", "here", "and", "vt"], &[0..3, 4..8, 9..12, 13..15], "tab…"),
469 (
470 "界界 界界界 e\u{301}e\u{301}e\u{301}",
471 3,
472 &["界", "界", "界", "界", "界", "e\u{301}e\u{301}e\u{301}"],
473 &[0..3, 3..6, 7..10, 10..13, 13..16, 17..26],
474 "界…",
475 ),
476 (" lead and trail ", 5, &["lead", "and", "trail", ""], &[2..6, 8..11, 12..17, 0..0], " le…"),
477 ("😀😀 ok", 3, &["😀", "😀", "ok"], &[0..4, 4..8, 9..11], "😀…"),
478 ("a\r\nb c", 2, &["a", "b", "c"], &[0..1, 3..4, 5..6], "a…"),
479 ("über straße ünïcödé", 6, &["über", "straße", "ünïcöd", "é"], &[0..5, 6..13, 14..23, 23..25], "über …"),
480 ("x\u{85}y\u{2028}z", 1, &["x", "y", "z"], &[0..1, 3..4, 7..8], "…"),
481 ("control\u{7}bell word", 8, &["control\u{7}", "bell", "word"], &[0..8, 8..12, 13..17], "control…"),
482 (
483 "👨\u{200d}👩\u{200d}👧 family",
484 4,
485 &["👨\u{200d}👩\u{200d}👧 f", "amil", "y"],
486 &[0..20, 20..24, 24..25],
487 "👨\u{200d}👩\u{200d}👧 …",
488 ),
489 ("add abcdefghijk),", 8, &["add abcd", "efghij", "k),"], &[0..8, 8..14, 14..17], "add abc…"),
490 ];
491 for (text, max, lines, ranges, truncated) in cases {
492 assert_eq!(wrap(text, max), lines, "{text:?}");
493 assert_eq!(wrap_ranges(text, max), ranges, "{text:?}");
494 assert_eq!(truncate(text, max), truncated, "{text:?}");
495 }
496 let widths = ["\t", "\u{7}", "\u{b}", "\r\n", "\u{a0}", "~", " ", "👨\u{200d}👩", "\u{7f}", ""].map(width);
497 assert_eq!(widths, [1, 1, 1, 1, 1, 1, 1, 2, 1, 0]);
498 }
499}