Commit b51e5d360f

b51e5d360f911b8c2327bebe890a854bbd518dd2

parent: 499f83af29

Unregistered key

vaw <git@nlih.de> · 2026-07-24 18:26 UTC
committer: <noreply@github.com>

Don't wrap messages without `formatted_body` in middle of word (#486)

Layout: unified · split

src/util.rs +25 −9
@@ -26,23 +26,38 @@ pub fn split_cow(cow: Cow<'_, str>, idx: usize) -> (Cow<'_, str>, Cow<'_, str>)
26 26
27pub fn take_width(s: Cow<'_, str>, width: usize) -> ((Cow<'_, str>, usize), Cow<'_, str>) { 27pub fn take_width(s: Cow<'_, str>, width: usize) -> ((Cow<'_, str>, usize), Cow<'_, str>) {
28 // Find where to split the line. 28 // Find where to split the line.
29 let mut w = 0; 29 let mut cur_width = 0;
30 30
31 let idx = UnicodeSegmentation::grapheme_indices(s.as_ref(), true) 31 let mut idx = UnicodeSegmentation::split_word_bound_indices(s.as_ref())
32 .find_map(|(i, g)| { 32 .find_map(|(i, word)| {
33 let gw = UnicodeWidthStr::width(g); 33 let word_width = UnicodeWidthStr::width(word);
34 if w + gw > width { 34 if cur_width + word_width > width {
35 Some(i) 35 Some(i)
36 } else { 36 } else {
37 w += gw; 37 cur_width += word_width;
38 None 38 None
39 } 39 }
40 }) 40 })
41 .unwrap_or(s.len()); 41 .unwrap_or(s.len());
42 42
43 if idx == 0 {
44 // first word is wider than available; fall back to splitting by width
45 idx = UnicodeSegmentation::grapheme_indices(s.as_ref(), true)
46 .find_map(|(i, graph)| {
47 let graph_width = UnicodeWidthStr::width(graph);
48 if cur_width + graph_width > width {
49 Some(i)
50 } else {
51 cur_width += graph_width;
52 None
53 }
54 })
55 .unwrap_or(s.len());
56 }
57
43 let (s0, s1) = split_cow(s, idx); 58 let (s0, s1) = split_cow(s, idx);
44 59
45 ((s0, w), s1) 60 ((s0, cur_width), s1)
46} 61}
47 62
48pub struct WrappedLinesIterator<'a> { 63pub struct WrappedLinesIterator<'a> {
@@ -183,8 +198,9 @@ pub mod tests {
183 198
184 let mut iter = wrap(s, 5); 199 let mut iter = wrap(s, 5);
185 assert_eq!(iter.next(), Some((Cow::Borrowed("hello"), 5))); 200 assert_eq!(iter.next(), Some((Cow::Borrowed("hello"), 5)));
186 assert_eq!(iter.next(), Some((Cow::Borrowed(" worl"), 5))); 201 assert_eq!(iter.next(), Some((Cow::Borrowed(" "), 1)));
187 assert_eq!(iter.next(), Some((Cow::Borrowed("d!"), 2))); 202 assert_eq!(iter.next(), Some((Cow::Borrowed("world"), 5)));
203 assert_eq!(iter.next(), Some((Cow::Borrowed("!"), 1)));
188 assert_eq!(iter.next(), Some((Cow::Borrowed("abcde"), 5))); 204 assert_eq!(iter.next(), Some((Cow::Borrowed("abcde"), 5)));
189 assert_eq!(iter.next(), Some((Cow::Borrowed("fghij"), 5))); 205 assert_eq!(iter.next(), Some((Cow::Borrowed("fghij"), 5)));
190 assert_eq!(iter.next(), Some((Cow::Borrowed("klmno"), 5))); 206 assert_eq!(iter.next(), Some((Cow::Borrowed("klmno"), 5)));