| 1 | //! Shared text helpers for TUI selection and clipboard workflows. |
| 2 | |
| 3 | use ratatui::text::{Line, Span}; |
| 4 | use unicode_segmentation::UnicodeSegmentation; |
| 5 | use unicode_width::{UnicodeWidthChar, UnicodeWidthStr}; |
| 6 | |
| 7 | use crate::osc8; |
| 8 | |
| 9 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 10 | pub enum CopyLineSeparator { |
| 11 | None, |
| 12 | Space, |
| 13 | Newline, |
| 14 | } |
| 15 | |
| 16 | impl CopyLineSeparator { |
| 17 | #[must_use] |
| 18 | pub const fn as_str(self) -> &'static str { |
| 19 | match self { |
| 20 | Self::None => "", |
| 21 | Self::Space => " ", |
| 22 | Self::Newline => "\n", |
| 23 | } |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | pub fn truncate_line_to_width(text: &str, max_width: usize) -> String { |
| 28 | if max_width == 0 { |
| 29 | return String::new(); |
| 30 | } |
| 31 | if text_display_width(text) <= max_width { |
| 32 | return text.to_string(); |
| 33 | } |
| 34 | // For very small budgets, take whole graphemes until the next one would |
| 35 | // exceed the display width. Never split an emoji or combining sequence. |
| 36 | if max_width <= 3 { |
| 37 | let mut out = String::new(); |
| 38 | let mut width = 0usize; |
| 39 | for grapheme in text.graphemes(true) { |
| 40 | let grapheme_width = grapheme_display_width(grapheme); |
| 41 | if width + grapheme_width > max_width { |
| 42 | break; |
| 43 | } |
| 44 | out.push_str(grapheme); |
| 45 | width += grapheme_width; |
| 46 | } |
| 47 | return out; |
| 48 | } |
| 49 | |
| 50 | let mut out = String::new(); |
| 51 | let mut width = 0usize; |
| 52 | let limit = max_width.saturating_sub(3); |
| 53 | for grapheme in text.graphemes(true) { |
| 54 | let grapheme_width = grapheme_display_width(grapheme); |
| 55 | if width + grapheme_width > limit { |
| 56 | break; |
| 57 | } |
| 58 | out.push_str(grapheme); |
| 59 | width += grapheme_width; |
| 60 | } |
| 61 | out.push_str("..."); |
| 62 | out |
| 63 | } |
| 64 | |
| 65 | /// Truncate `text` to `max_width` display columns, preferring whole words. |
| 66 | pub fn semantic_truncate(text: &str, max_width: usize) -> String { |
| 67 | if max_width == 0 { |
| 68 | return String::new(); |
| 69 | } |
| 70 | if text_display_width(text) <= max_width { |
| 71 | return text.to_string(); |
| 72 | } |
| 73 | |
| 74 | const ELLIPSIS: char = '…'; |
| 75 | let ellipsis_width = char_display_width(ELLIPSIS); |
| 76 | let limit = max_width.saturating_sub(ellipsis_width); |
| 77 | if limit == 0 { |
| 78 | return ELLIPSIS.to_string(); |
| 79 | } |
| 80 | |
| 81 | let mut width = 0usize; |
| 82 | let mut cut_byte = 0usize; |
| 83 | let mut last_word_end = None; |
| 84 | let mut in_word = false; |
| 85 | for (byte_idx, grapheme) in text.grapheme_indices(true) { |
| 86 | let grapheme_width = grapheme_display_width(grapheme); |
| 87 | if width + grapheme_width > limit { |
| 88 | break; |
| 89 | } |
| 90 | width += grapheme_width; |
| 91 | cut_byte = byte_idx + grapheme.len(); |
| 92 | if grapheme.chars().all(char::is_whitespace) { |
| 93 | if in_word { |
| 94 | last_word_end = Some(byte_idx); |
| 95 | in_word = false; |
| 96 | } |
| 97 | } else if breaks_after_cjk(grapheme) { |
| 98 | // Han and kana have no spaces to wait for: every character is a |
| 99 | // word end. Without this, one space early in a Chinese or |
| 100 | // Japanese line cuts everything after it. |
| 101 | last_word_end = Some(cut_byte); |
| 102 | in_word = false; |
| 103 | } else { |
| 104 | in_word = true; |
| 105 | } |
| 106 | } |
| 107 | if cut_byte == 0 { |
| 108 | return ELLIPSIS.to_string(); |
| 109 | } |
| 110 | |
| 111 | let mut body = if let Some(word_end) = last_word_end { |
| 112 | text[..word_end].trim_end() |
| 113 | } else { |
| 114 | text[..cut_byte].trim_end() |
| 115 | }; |
| 116 | if body.is_empty() { |
| 117 | body = text[..cut_byte].trim_end(); |
| 118 | } |
| 119 | let mut out = body.to_string(); |
| 120 | out.push(ELLIPSIS); |
| 121 | out |
| 122 | } |
| 123 | |
| 124 | /// A cut may follow a Han, kana or CJK punctuation character, except an |
| 125 | /// opening bracket, which would be left dangling before the ellipsis. |
| 126 | fn breaks_after_cjk(grapheme: &str) -> bool { |
| 127 | let Some(first) = grapheme.chars().next() else { |
| 128 | return false; |
| 129 | }; |
| 130 | crate::translation::is_cjk(first) |
| 131 | && !matches!( |
| 132 | first, |
| 133 | '(' | '「' | '『' | '【' | '〔' | '《' | '〈' | '[' | '{' |
| 134 | ) |
| 135 | } |
| 136 | |
| 137 | pub fn semantic_truncate_with_affixes( |
| 138 | prefix: &str, |
| 139 | text: &str, |
| 140 | suffix: &str, |
| 141 | max_width: usize, |
| 142 | ) -> String { |
| 143 | let fixed_width = text_display_width(prefix) + text_display_width(suffix); |
| 144 | if fixed_width > max_width { |
| 145 | return semantic_truncate(&format!("{prefix}{text}{suffix}"), max_width); |
| 146 | } |
| 147 | format!( |
| 148 | "{prefix}{}{suffix}", |
| 149 | semantic_truncate_between_affixes(prefix, text, suffix, max_width) |
| 150 | ) |
| 151 | } |
| 152 | |
| 153 | pub fn semantic_truncate_between_affixes( |
| 154 | prefix: &str, |
| 155 | text: &str, |
| 156 | suffix: &str, |
| 157 | max_width: usize, |
| 158 | ) -> String { |
| 159 | let fixed_width = text_display_width(prefix) + text_display_width(suffix); |
| 160 | if fixed_width > max_width { |
| 161 | return String::new(); |
| 162 | } |
| 163 | semantic_truncate(text, max_width - fixed_width) |
| 164 | } |
| 165 | |
| 166 | /// Convert a rendered transcript line to plain text, stripping OSC-8 link |
| 167 | /// escape sequences. The caller is responsible for shifting selection columns |
| 168 | /// to account for any visual-only rail prefix (see |
| 169 | /// `TranscriptViewCache::rail_prefix_width`). |
| 170 | pub fn line_to_plain(line: &Line<'static>) -> String { |
| 171 | let mut out = String::new(); |
| 172 | append_spans_plain(line.spans.iter(), &mut out); |
| 173 | out |
| 174 | } |
| 175 | |
| 176 | fn append_spans_plain<'a, I>(spans: I, out: &mut String) |
| 177 | where |
| 178 | I: Iterator<Item = &'a Span<'a>>, |
| 179 | { |
| 180 | for span in spans { |
| 181 | if span.content.contains('\x1b') { |
| 182 | osc8::strip_into(&span.content, out); |
| 183 | } else { |
| 184 | out.push_str(span.content.as_ref()); |
| 185 | } |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | pub fn text_display_width(text: &str) -> usize { |
| 190 | text.graphemes(true).map(grapheme_display_width).sum() |
| 191 | } |
| 192 | |
| 193 | pub fn pad_to_display_width(text: &str, width: usize) -> String { |
| 194 | let padding = width.saturating_sub(text_display_width(text)); |
| 195 | format!("{text}{}", " ".repeat(padding)) |
| 196 | } |
| 197 | |
| 198 | /// Visible width of one grapheme: ratatui strips control characters before |
| 199 | /// painting, so they occupy no cells. Every other grapheme keeps the shared |
| 200 | /// [`grapheme_display_width`] contract. |
| 201 | fn visible_grapheme_width(grapheme: &str) -> usize { |
| 202 | if grapheme.chars().any(|c| c.is_control()) { |
| 203 | 0 |
| 204 | } else { |
| 205 | grapheme_display_width(grapheme) |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | /// Display width in painted terminal columns: control characters are |
| 210 | /// invisible (ratatui strips them), so they add nothing. |
| 211 | /// |
| 212 | /// Mouse selection coordinates are terminal cells, so the copy path must |
| 213 | /// measure in this space: the fixed-4 [`text_display_width`] would shift |
| 214 | /// every column after a tab away from what the user dragged over. The two |
| 215 | /// agree on text without control characters. |
| 216 | pub fn text_visible_width(text: &str) -> usize { |
| 217 | text.graphemes(true).map(visible_grapheme_width).sum() |
| 218 | } |
| 219 | |
| 220 | /// Slice `[start, end)` in painted terminal columns, the space the mouse |
| 221 | /// reports. |
| 222 | /// |
| 223 | /// A grapheme overlapping the window is kept whole under the same strict |
| 224 | /// rule for every width: zero-width control spans join the output only when |
| 225 | /// the window strictly covers their position, so interior tabs survive while |
| 226 | /// un-aimable edge touches stay out. |
| 227 | pub fn slice_visible_columns(text: &str, start: usize, end: usize) -> String { |
| 228 | if end <= start { |
| 229 | return String::new(); |
| 230 | } |
| 231 | |
| 232 | let mut out = String::new(); |
| 233 | let mut col = 0usize; |
| 234 | for grapheme in text.graphemes(true) { |
| 235 | let grapheme_start = col; |
| 236 | let grapheme_end = col.saturating_add(visible_grapheme_width(grapheme)); |
| 237 | if grapheme_end > start && grapheme_start < end { |
| 238 | out.push_str(grapheme); |
| 239 | } |
| 240 | col = grapheme_end; |
| 241 | if col >= end { |
| 242 | break; |
| 243 | } |
| 244 | } |
| 245 | out |
| 246 | } |
| 247 | |
| 248 | pub fn char_display_width(ch: char) -> usize { |
| 249 | match ch { |
| 250 | '\t' => 4, |
| 251 | // Enclosed Alphanumerics (U+2460-U+24FF), Dingbat Circled Digits |
| 252 | // (U+2776-U+2793), and Circled Numbers on Black Square (U+3248-U+324F) |
| 253 | // have East Asian Width "Ambiguous" but are rendered as 2 columns in |
| 254 | // CJK terminals. unicode-width's width() conservatively reports 1; we |
| 255 | // match the terminal. (#4479) |
| 256 | '\u{2460}'..='\u{24FF}' | '\u{2776}'..='\u{2793}' | '\u{3248}'..='\u{324F}' => 2, |
| 257 | _ => { |
| 258 | // `width()` returns `None` for control/unassigned chars (default them to |
| 259 | // one column so layout doesn't collapse) and `Some(0)` for genuinely |
| 260 | // zero-width chars — combining marks, ZWJ, zero-width spaces — which must |
| 261 | // stay 0 so display-width math (truncation, slicing, overflow, copy) |
| 262 | // matches what the terminal actually renders. |
| 263 | UnicodeWidthChar::width(ch).unwrap_or(1) |
| 264 | } |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | /// Measure one extended grapheme using the same string-level Unicode rules as |
| 269 | /// Ratatui. String width intentionally differs from the sum of codepoint widths |
| 270 | /// for keycaps, ZWJ emoji, modifiers, and other terminal ligatures. |
| 271 | /// |
| 272 | /// Keycap sequences (such as 1\u{fe0f}\u{20e3}) that lack an FE0F variation |
| 273 | /// selector still render as 2 columns in terminals, but unicode-width's |
| 274 | /// `grapheme.width()` only reports 1. We force 2 when U+20E3 is present in a |
| 275 | /// multi-codepoint grapheme. (#4479) |
| 276 | pub fn grapheme_display_width(grapheme: &str) -> usize { |
| 277 | if grapheme == "\t" { |
| 278 | return 4; |
| 279 | } |
| 280 | if let Some(ch) = grapheme.chars().next() |
| 281 | && ch.len_utf8() == grapheme.len() |
| 282 | { |
| 283 | return char_display_width(ch); |
| 284 | } |
| 285 | // Keycap sequences always render as 2 columns. unicode-width's |
| 286 | // `width()` undercounts the non-FE0F variant to 1. |
| 287 | if grapheme.contains('\u{20e3}') { |
| 288 | return 2; |
| 289 | } |
| 290 | UnicodeWidthStr::width(grapheme) |
| 291 | } |
| 292 | |
| 293 | pub const MAX_DISPLAY_GRAPHEME_BYTES: usize = 32 * 1024; |
| 294 | |
| 295 | pub struct DisplayGrapheme<'a> { |
| 296 | pub text: &'a str, |
| 297 | pub cells: &'a [(char, usize)], |
| 298 | pub width: usize, |
| 299 | pub clipped_bytes: usize, |
| 300 | pub escaped: bool, |
| 301 | } |
| 302 | |
| 303 | pub struct DisplayNormalizer { |
| 304 | pending: String, |
| 305 | cells: Vec<(char, usize)>, |
| 306 | cursor: unicode_segmentation::GraphemeCursor, |
| 307 | column: usize, |
| 308 | clipped_bytes: usize, |
| 309 | clipped_tag: usize, |
| 310 | exact: bool, |
| 311 | escaping: bool, |
| 312 | } |
| 313 | |
| 314 | impl DisplayNormalizer { |
| 315 | #[must_use] |
| 316 | pub fn new(start_column: usize) -> Self { |
| 317 | Self { |
| 318 | pending: String::new(), |
| 319 | cells: Vec::new(), |
| 320 | cursor: unicode_segmentation::GraphemeCursor::new(0, usize::MAX, true), |
| 321 | column: start_column, |
| 322 | clipped_bytes: 0, |
| 323 | clipped_tag: 0, |
| 324 | exact: false, |
| 325 | escaping: false, |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | #[must_use] |
| 330 | pub fn new_exact(start_column: usize) -> Self { |
| 331 | let mut normalizer = Self::new(start_column); |
| 332 | normalizer.exact = true; |
| 333 | normalizer |
| 334 | } |
| 335 | |
| 336 | pub fn push(&mut self, text: &str, tag: usize, emit: &mut impl FnMut(DisplayGrapheme<'_>)) { |
| 337 | for ch in text.chars() { |
| 338 | if codewhale_sanitize::sanitize::is_bidi_control(ch) { |
| 339 | continue; |
| 340 | } |
| 341 | let ch = if ch != '\t' && (ch.is_control() || matches!(ch, '\u{2028}' | '\u{2029}')) { |
| 342 | ' ' |
| 343 | } else { |
| 344 | ch |
| 345 | }; |
| 346 | if self.escaping { |
| 347 | if ch.is_whitespace() { |
| 348 | self.escaping = false; |
| 349 | } else { |
| 350 | self.emit_escape(ch, tag, emit); |
| 351 | continue; |
| 352 | } |
| 353 | } |
| 354 | if self.clipped_bytes > 0 { |
| 355 | if ch.is_whitespace() { |
| 356 | self.emit_clipped(emit); |
| 357 | } else { |
| 358 | self.clipped_bytes = self.clipped_bytes.saturating_add(ch.len_utf8()); |
| 359 | continue; |
| 360 | } |
| 361 | } |
| 362 | if ch == '\t' { |
| 363 | let column = self |
| 364 | .column |
| 365 | .saturating_add(grapheme_display_width(&self.pending)); |
| 366 | for _ in 0..(4 - column % 4) { |
| 367 | self.scalar(' ', tag, emit); |
| 368 | } |
| 369 | } else { |
| 370 | self.scalar(ch, tag, emit); |
| 371 | } |
| 372 | } |
| 373 | } |
| 374 | |
| 375 | pub fn finish(&mut self, emit: &mut impl FnMut(DisplayGrapheme<'_>)) { |
| 376 | if self.clipped_bytes > 0 { |
| 377 | self.emit_clipped(emit); |
| 378 | } |
| 379 | self.emit_pending(emit); |
| 380 | self.escaping = false; |
| 381 | } |
| 382 | |
| 383 | fn scalar(&mut self, ch: char, tag: usize, emit: &mut impl FnMut(DisplayGrapheme<'_>)) { |
| 384 | let mut encoded = [0; 4]; |
| 385 | let text = ch.encode_utf8(&mut encoded); |
| 386 | 'scalar: loop { |
| 387 | let start = self.pending.len(); |
| 388 | loop { |
| 389 | match self.cursor.next_boundary(text, start) { |
| 390 | Ok(Some(boundary)) if boundary == start => { |
| 391 | self.emit_pending(emit); |
| 392 | continue 'scalar; |
| 393 | } |
| 394 | Err(unicode_segmentation::GraphemeIncomplete::PreContext(end)) => { |
| 395 | if end > 0 |
| 396 | && let Some(context) = self.pending.get(..end) |
| 397 | { |
| 398 | self.cursor.provide_context(context, 0); |
| 399 | } else { |
| 400 | self.overflow(ch, tag, emit); |
| 401 | return; |
| 402 | } |
| 403 | } |
| 404 | Err(unicode_segmentation::GraphemeIncomplete::NextChunk) => break, |
| 405 | _ => { |
| 406 | self.overflow(ch, tag, emit); |
| 407 | return; |
| 408 | } |
| 409 | } |
| 410 | } |
| 411 | let needed = self.pending.len().saturating_add(text.len()); |
| 412 | if needed > MAX_DISPLAY_GRAPHEME_BYTES { |
| 413 | self.overflow(ch, tag, emit); |
| 414 | return; |
| 415 | } |
| 416 | if needed > self.pending.capacity() { |
| 417 | let capacity = needed |
| 418 | .max(self.pending.capacity().saturating_mul(2)) |
| 419 | .clamp(64, MAX_DISPLAY_GRAPHEME_BYTES); |
| 420 | self.pending |
| 421 | .reserve_exact(capacity.saturating_sub(self.pending.len())); |
| 422 | } |
| 423 | self.pending.push(ch); |
| 424 | self.cells.push((ch, tag)); |
| 425 | return; |
| 426 | } |
| 427 | } |
| 428 | |
| 429 | fn overflow(&mut self, ch: char, tag: usize, emit: &mut impl FnMut(DisplayGrapheme<'_>)) { |
| 430 | self.clipped_tag = self.cells.first().map_or(tag, |&(_, tag)| tag); |
| 431 | if self.exact { |
| 432 | self.emit_ascii(r"[\u{…}]", self.clipped_tag, true, emit); |
| 433 | for index in 0..self.cells.len() { |
| 434 | let (pending, tag) = self.cells[index]; |
| 435 | self.emit_escape(pending, tag, emit); |
| 436 | } |
| 437 | self.emit_escape(ch, tag, emit); |
| 438 | self.escaping = true; |
| 439 | } else { |
| 440 | self.clipped_bytes = self.pending.len().saturating_add(ch.len_utf8()); |
| 441 | } |
| 442 | self.pending.clear(); |
| 443 | self.cells.clear(); |
| 444 | self.cursor = unicode_segmentation::GraphemeCursor::new(0, usize::MAX, true); |
| 445 | } |
| 446 | |
| 447 | fn emit_escape(&mut self, ch: char, tag: usize, emit: &mut impl FnMut(DisplayGrapheme<'_>)) { |
| 448 | let mut bytes = [0; 10]; |
| 449 | let mut length = 0; |
| 450 | for escaped in ch.escape_unicode() { |
| 451 | bytes[length] = escaped as u8; |
| 452 | length += 1; |
| 453 | } |
| 454 | let text = std::str::from_utf8(&bytes[..length]).expect("Unicode escapes are ASCII"); |
| 455 | self.emit_ascii(text, tag, false, emit); |
| 456 | } |
| 457 | |
| 458 | fn emit_ascii( |
| 459 | &mut self, |
| 460 | text: &str, |
| 461 | tag: usize, |
| 462 | escaped: bool, |
| 463 | emit: &mut impl FnMut(DisplayGrapheme<'_>), |
| 464 | ) { |
| 465 | let mut cells = [(' ', tag); 64]; |
| 466 | let mut length = 0; |
| 467 | for ch in text.chars() { |
| 468 | cells[length] = (ch, tag); |
| 469 | length += 1; |
| 470 | } |
| 471 | emit(DisplayGrapheme { |
| 472 | text, |
| 473 | cells: &cells[..length], |
| 474 | width: length, |
| 475 | clipped_bytes: 0, |
| 476 | escaped, |
| 477 | }); |
| 478 | self.column = self.column.saturating_add(length); |
| 479 | } |
| 480 | |
| 481 | fn emit_pending(&mut self, emit: &mut impl FnMut(DisplayGrapheme<'_>)) { |
| 482 | if self.pending.is_empty() { |
| 483 | return; |
| 484 | } |
| 485 | let width = grapheme_display_width(&self.pending); |
| 486 | emit(DisplayGrapheme { |
| 487 | text: &self.pending, |
| 488 | cells: &self.cells, |
| 489 | width, |
| 490 | clipped_bytes: 0, |
| 491 | escaped: false, |
| 492 | }); |
| 493 | self.column = self.column.saturating_add(width); |
| 494 | self.pending.clear(); |
| 495 | self.cells.clear(); |
| 496 | self.cursor = unicode_segmentation::GraphemeCursor::new(0, usize::MAX, true); |
| 497 | } |
| 498 | |
| 499 | fn emit_clipped(&mut self, emit: &mut impl FnMut(DisplayGrapheme<'_>)) { |
| 500 | let text = format!("[… {} B …]", self.clipped_bytes); |
| 501 | self.cells |
| 502 | .extend(text.chars().map(|ch| (ch, self.clipped_tag))); |
| 503 | let width = grapheme_display_width(&text); |
| 504 | emit(DisplayGrapheme { |
| 505 | text: &text, |
| 506 | cells: &self.cells, |
| 507 | width, |
| 508 | clipped_bytes: self.clipped_bytes, |
| 509 | escaped: false, |
| 510 | }); |
| 511 | self.column = self.column.saturating_add(width); |
| 512 | self.clipped_bytes = 0; |
| 513 | self.cells.clear(); |
| 514 | } |
| 515 | } |
| 516 | |
| 517 | pub fn display_graphemes<'a>( |
| 518 | pieces: impl Iterator<Item = (&'a str, usize)>, |
| 519 | start_column: usize, |
| 520 | mut emit: impl FnMut(DisplayGrapheme<'_>), |
| 521 | ) { |
| 522 | let mut normalizer = DisplayNormalizer::new(start_column); |
| 523 | for (text, tag) in pieces { |
| 524 | normalizer.push(text, tag, &mut emit); |
| 525 | } |
| 526 | normalizer.finish(&mut emit); |
| 527 | } |
| 528 | |
| 529 | pub fn display_graphemes_exact<'a>( |
| 530 | pieces: impl Iterator<Item = (&'a str, usize)>, |
| 531 | start_column: usize, |
| 532 | mut emit: impl FnMut(DisplayGrapheme<'_>), |
| 533 | ) { |
| 534 | let mut normalizer = DisplayNormalizer::new_exact(start_column); |
| 535 | for (text, tag) in pieces { |
| 536 | normalizer.push(text, tag, &mut emit); |
| 537 | } |
| 538 | normalizer.finish(&mut emit); |
| 539 | } |
| 540 | |
| 541 | #[cfg(test)] |
| 542 | mod tests { |
| 543 | use super::*; |
| 544 | use ratatui::text::Span; |
| 545 | |
| 546 | #[test] |
| 547 | fn line_to_plain_strips_osc_8_wrapper() { |
| 548 | let wrapped = format!( |
| 549 | "\x1b]8;;{}\x1b\\{}\x1b]8;;\x1b\\", |
| 550 | "https://example.com", "https://example.com" |
| 551 | ); |
| 552 | let line = Line::from(vec![ |
| 553 | Span::raw("see "), |
| 554 | Span::raw(wrapped), |
| 555 | Span::raw(" for details"), |
| 556 | ]); |
| 557 | let text = line_to_plain(&line); |
| 558 | assert_eq!(text, "see https://example.com for details"); |
| 559 | } |
| 560 | |
| 561 | #[test] |
| 562 | fn line_to_plain_passes_through_plain_spans() { |
| 563 | let line = Line::from(vec![Span::raw("plain "), Span::raw("text")]); |
| 564 | let text = line_to_plain(&line); |
| 565 | assert_eq!(text, "plain text"); |
| 566 | } |
| 567 | |
| 568 | #[test] |
| 569 | fn line_to_plain_includes_all_spans() { |
| 570 | // Visual-only rail spans are stripped by the caller using |
| 571 | // TranscriptViewCache::rail_prefix_width — line_to_plain itself |
| 572 | // is a faithful span-to-string pass-through. |
| 573 | let line = Line::from(vec![Span::raw("\u{2502} "), Span::raw("tool output")]); |
| 574 | let text = line_to_plain(&line); |
| 575 | assert_eq!(text, "\u{2502} tool output"); |
| 576 | } |
| 577 | |
| 578 | #[test] |
| 579 | fn slice_text_respects_column_bounds() { |
| 580 | let text = "hello world"; |
| 581 | assert_eq!(slice_visible_columns(text, 0, 5), "hello"); |
| 582 | assert_eq!(slice_visible_columns(text, 6, 11), "world"); |
| 583 | assert_eq!(slice_visible_columns(text, 0, 0), ""); |
| 584 | assert_eq!(slice_visible_columns(text, 0, 100), text); |
| 585 | } |
| 586 | |
| 587 | #[test] |
| 588 | fn slice_text_handles_multibyte_characters() { |
| 589 | let text = "a─b"; // U+2500 is 1 display column on supported terminals |
| 590 | assert_eq!(slice_visible_columns(text, 1, 2), "─"); |
| 591 | assert_eq!(slice_visible_columns(text, 0, 3), text); |
| 592 | } |
| 593 | |
| 594 | #[test] |
| 595 | fn slice_text_truncates_at_end() { |
| 596 | let text = "ab"; |
| 597 | assert_eq!(slice_visible_columns(text, 1, 5), "b"); |
| 598 | } |
| 599 | |
| 600 | #[test] |
| 601 | fn visible_width_ignores_stripped_controls() { |
| 602 | assert_eq!(text_visible_width("\t"), 0); |
| 603 | assert_eq!(text_visible_width("\ta"), 1); |
| 604 | assert_eq!(text_visible_width("ab\t"), 2); |
| 605 | assert_eq!(text_visible_width("a\tb"), 2); |
| 606 | } |
| 607 | |
| 608 | #[test] |
| 609 | fn visible_slice_keeps_interior_controls_only() { |
| 610 | // Interior tab strictly inside the window survives. |
| 611 | assert_eq!(slice_visible_columns("ab\tcdef", 0, 4), "ab\tcd"); |
| 612 | // Zero-width span at the window edge stays out, like any grapheme. |
| 613 | assert_eq!(slice_visible_columns("\txy", 0, 2), "xy"); |
| 614 | assert_eq!(slice_visible_columns("ab", 0, 2), "ab"); |
| 615 | } |
| 616 | |
| 617 | // --- Unicode / CJK / terminal-width QA (issue #3488) ------------------- |
| 618 | // These exercise the production width helpers directly so the assertions |
| 619 | // track the same code path the renderer uses. |
| 620 | |
| 621 | #[test] |
| 622 | fn text_display_width_counts_cjk_as_two_columns() { |
| 623 | assert_eq!(text_display_width("中文"), 4); // two wide glyphs |
| 624 | assert_eq!(text_display_width("Hello世界"), 9); // 5 ASCII + 2×2 |
| 625 | // Full-width (ambiguous→wide) punctuation is two columns each. |
| 626 | assert_eq!(text_display_width(",。!?"), 8); |
| 627 | } |
| 628 | |
| 629 | #[test] |
| 630 | fn text_display_width_treats_zero_width_marks_as_zero() { |
| 631 | // A combining mark adds no column: "e" + U+0301 renders as one cell. |
| 632 | // (Regression guard: the old `.max(1)` counted it as 1, over-reporting |
| 633 | // width and causing premature truncation / border drift on text with |
| 634 | // combining marks or ZWJ emoji sequences.) |
| 635 | assert_eq!(text_display_width("e\u{0301}"), 1); |
| 636 | assert_eq!(text_display_width("cafe\u{0301}"), 4); |
| 637 | // The complete ZWJ emoji is one two-column grapheme, matching Ratatui. |
| 638 | assert_eq!(text_display_width("\u{1F469}\u{200D}\u{1F4BB}"), 2); |
| 639 | } |
| 640 | |
| 641 | #[test] |
| 642 | fn text_display_width_keeps_control_and_tab_widths() { |
| 643 | // Control chars still occupy a column (avoid layout collapse); tab = 4. |
| 644 | assert_eq!(text_display_width("a\u{0007}b"), 3); |
| 645 | assert_eq!(text_display_width("\t"), 4); |
| 646 | assert_eq!(text_display_width("\ta"), 5); |
| 647 | } |
| 648 | |
| 649 | #[test] |
| 650 | fn truncate_line_to_width_respects_display_width_not_byte_len() { |
| 651 | // No truncation when the string already fits by display width. |
| 652 | assert_eq!(truncate_line_to_width("中文", 10), "中文"); |
| 653 | // Oversized: reserve 3 cols for the ellipsis, fill the rest by width. |
| 654 | let out = truncate_line_to_width("中文测试", 7); |
| 655 | assert_eq!(out, "中文..."); |
| 656 | assert_eq!(text_display_width(&out), 7); |
| 657 | // Never split a wide glyph across the boundary, and never emit U+FFFD. |
| 658 | let clipped = truncate_line_to_width("界界界界界", 5); |
| 659 | assert!(text_display_width(&clipped) <= 5); |
| 660 | assert!(!clipped.contains('\u{FFFD}')); |
| 661 | } |
| 662 | |
| 663 | #[test] |
| 664 | fn semantic_truncate_prefers_word_boundaries() { |
| 665 | let out = semantic_truncate("hello world foo bar", 14); |
| 666 | assert_eq!(out, "hello world…"); |
| 667 | assert!(text_display_width(&out) <= 14); |
| 668 | } |
| 669 | |
| 670 | #[test] |
| 671 | fn semantic_truncate_falls_back_with_long_words_and_wide_glyphs() { |
| 672 | let long_word = semantic_truncate("supercalifragilistic", 8); |
| 673 | assert_eq!(long_word, "superca…"); |
| 674 | assert!(text_display_width(&long_word) <= 8); |
| 675 | |
| 676 | let cjk = semantic_truncate("中文测试文本", 7); |
| 677 | assert_eq!(cjk, "中文测…"); |
| 678 | assert!(text_display_width(&cjk) <= 7); |
| 679 | } |
| 680 | |
| 681 | #[test] |
| 682 | fn semantic_truncate_breaks_between_cjk_after_a_space() { |
| 683 | // The space after "Operate" used to be the only word end, so the |
| 684 | // Chinese clause after it was dropped whole. |
| 685 | let out = semantic_truncate("Operate 把你的提示词变成目标", 20); |
| 686 | assert_eq!(out, "Operate 把你的提示…"); |
| 687 | assert!(text_display_width(&out) <= 20); |
| 688 | |
| 689 | // An opening bracket is not left dangling before the ellipsis. |
| 690 | assert_eq!(semantic_truncate("模型已切换(原为", 13), "模型已切换…"); |
| 691 | } |
| 692 | |
| 693 | #[test] |
| 694 | fn semantic_truncate_handles_empty_and_tiny_budgets() { |
| 695 | assert_eq!(semantic_truncate("", 10), ""); |
| 696 | assert_eq!(semantic_truncate("hello", 0), ""); |
| 697 | assert_eq!(semantic_truncate("hello", 1), "…"); |
| 698 | } |
| 699 | |
| 700 | #[test] |
| 701 | fn semantic_truncate_between_affixes_reserves_fixed_columns() { |
| 702 | let hint = semantic_truncate_between_affixes( |
| 703 | " > [ ] Prefix stability (", |
| 704 | "whether system/tools stayed cacheable", |
| 705 | ")", |
| 706 | 49, |
| 707 | ); |
| 708 | let row = format!(" > [ ] Prefix stability ({hint})"); |
| 709 | assert_eq!(hint, "whether system/tools…"); |
| 710 | assert!(text_display_width(&row) <= 49); |
| 711 | } |
| 712 | |
| 713 | #[test] |
| 714 | fn slice_text_slices_cjk_by_display_column() { |
| 715 | // Columns: 中=[0,2) 文=[2,4) a=[4,5) b=[5,6) |
| 716 | let text = "中文ab"; |
| 717 | assert_eq!(slice_visible_columns(text, 0, 2), "中"); |
| 718 | assert_eq!(slice_visible_columns(text, 2, 4), "文"); |
| 719 | assert_eq!(slice_visible_columns(text, 4, 6), "ab"); |
| 720 | } |
| 721 | |
| 722 | // --- New #3488 fixtures: CJK/wide-glyph truncation on selector-style rows. |
| 723 | // truncate_line_to_width is the production helper behind sidebar (file_tree), |
| 724 | // statusline (footer_ui), hotbar, and picker (mouse_ui) row rendering, so |
| 725 | // these exercise the same truncation path those surfaces use. |
| 726 | |
| 727 | #[test] |
| 728 | fn truncate_line_to_width_full_width_cjk_lands_on_glyph_boundary() { |
| 729 | // Each Han glyph is two columns. With an odd budget the truncation must |
| 730 | // land on a whole-glyph boundary (reserving three columns for the |
| 731 | // ellipsis), never leaving a half-rendered wide cell or emitting U+FFFD. |
| 732 | let title = "项目报告结果"; // 6 glyphs, 12 columns |
| 733 | let out = truncate_line_to_width(title, 7); |
| 734 | // Budget 7 -> limit 4 columns -> two glyphs fit, then the ellipsis. |
| 735 | assert_eq!(out, "项目..."); |
| 736 | assert_eq!(text_display_width(&out), 7); |
| 737 | // The kept prefix is composed only of whole wide glyphs (each 2 cols), |
| 738 | // proving the boundary glyph was dropped whole, not split. |
| 739 | let prefix = out.strip_suffix("...").expect("ellipsis present"); |
| 740 | assert!(prefix.chars().all(|c| char_display_width(c) == 2)); |
| 741 | assert!(!out.contains('\u{FFFD}')); |
| 742 | } |
| 743 | |
| 744 | #[test] |
| 745 | fn truncate_line_to_width_mixed_ascii_cjk_row_keeps_ellipsis_within_budget() { |
| 746 | // A sidebar/selector row mixing an ASCII label with a CJK title, wider |
| 747 | // than the column budget, must truncate with a trailing ellipsis that |
| 748 | // still fits by display width and must not split a wide glyph. |
| 749 | let row = "Task: 数据库迁移任务 done"; // ASCII label + 7 Han glyphs |
| 750 | let budget = 12; |
| 751 | let out = truncate_line_to_width(row, budget); |
| 752 | assert!(out.ends_with("..."), "expected ellipsis, got {out:?}"); |
| 753 | // Ellipsis-and-content fit within the budget by *display* width. |
| 754 | assert!(text_display_width(&out) <= budget); |
| 755 | // The non-ellipsis prefix stays within budget-minus-ellipsis, so the |
| 756 | // wide glyph on the boundary was dropped whole rather than half-drawn. |
| 757 | let prefix = out.strip_suffix("...").expect("ellipsis present"); |
| 758 | assert!(text_display_width(prefix) <= budget - 3); |
| 759 | assert!(!out.contains('\u{FFFD}')); |
| 760 | // The semantic ASCII prefix survives truncation. |
| 761 | assert!(out.starts_with("Task:")); |
| 762 | } |
| 763 | |
| 764 | #[test] |
| 765 | fn truncate_line_to_width_dense_cjk_selector_row_survives_narrow_widths() { |
| 766 | // Picker/selector rows degrade through truncate_line_to_width when the |
| 767 | // terminal is narrow. A dense row with a leading marker glyph and CJK |
| 768 | // content must stay within budget at tiny widths, without panicking or |
| 769 | // emitting a replacement char from a mid-glyph byte split. |
| 770 | let row = "▸ 中文项目 · main"; // marker + CJK + separator + branch |
| 771 | for width in [1usize, 2, 3, 4, 6, 8] { |
| 772 | let out = truncate_line_to_width(row, width); |
| 773 | assert!( |
| 774 | text_display_width(&out) <= width, |
| 775 | "width={width}: {out:?} exceeds budget" |
| 776 | ); |
| 777 | assert!( |
| 778 | !out.contains('\u{FFFD}'), |
| 779 | "width={width}: truncation split a wide glyph" |
| 780 | ); |
| 781 | } |
| 782 | } |
| 783 | |
| 784 | // --- keycap / grapheme regression guard (#4479) --------------------------- |
| 785 | // Fully qualified keycap sequences render as two columns. Codepoint sums |
| 786 | // report one; the canonical string/grapheme contract reports two. |
| 787 | |
| 788 | #[test] |
| 789 | fn text_display_width_treats_keycap_sequence_as_two_columns() { |
| 790 | for keycap in [ |
| 791 | "1\u{fe0f}\u{20e3}", |
| 792 | "9\u{fe0f}\u{20e3}", |
| 793 | "#\u{fe0f}\u{20e3}", |
| 794 | ] { |
| 795 | assert_eq!(text_display_width(keycap), 2); |
| 796 | assert_eq!(text_display_width(keycap), UnicodeWidthStr::width(keycap)); |
| 797 | } |
| 798 | // A digit directly followed by U+20E3 (without FE0F variation selector) |
| 799 | // still renders as a 2-column keycap in terminals. We force this in |
| 800 | // grapheme_display_width when the grapheme contains U+20E3. |
| 801 | // A standalone U+20E3 is a zero-width combining mark. |
| 802 | assert_eq!(text_display_width("1\u{20e3}"), 2); |
| 803 | assert_eq!(text_display_width("\u{20e3}"), 0); |
| 804 | } |
| 805 | |
| 806 | #[test] |
| 807 | fn circled_digit_display_width() { |
| 808 | assert_eq!(char_display_width('\u{2460}'), 2); |
| 809 | assert_eq!(char_display_width('\u{2461}'), 2); |
| 810 | assert_eq!(char_display_width('\u{24ea}'), 2); |
| 811 | assert_eq!(char_display_width('\u{2776}'), 2); |
| 812 | assert_eq!(text_display_width("\u{2460}\u{2461}\u{2462}"), 6); |
| 813 | assert_eq!(text_display_width("Step \u{2460}: init"), 13); |
| 814 | assert_eq!(text_display_width("A\u{24d0}B"), 4); |
| 815 | } |
| 816 | |
| 817 | #[test] |
| 818 | fn unicode_width_reports_circled_digits_as_two_columns() { |
| 819 | // Regression guard for the unicode-width patch (#4479): Ratatui |
| 820 | // renders text through UnicodeWidthChar::width(), so the patch must |
| 821 | // make even the raw crate API report 2 columns for ambiguous-width |
| 822 | // characters — otherwise Ratatui places them in 1 cell while the |
| 823 | // terminal paints 2, shifting every downstream column. |
| 824 | assert_eq!(UnicodeWidthChar::width('\u{2460}'), Some(2)); |
| 825 | assert_eq!(UnicodeWidthChar::width('\u{24ea}'), Some(2)); |
| 826 | assert_eq!(UnicodeWidthStr::width("\u{2460}\u{2461}\u{2462}"), 6); |
| 827 | } |
| 828 | |
| 829 | #[test] |
| 830 | fn slice_text_does_not_split_keycap_sequence() { |
| 831 | let row = "step 1\u{fe0f}\u{20e3} done"; |
| 832 | // The keycap occupies columns [5, 7). Any overlapping selection keeps |
| 833 | // the complete grapheme; no isolated FE0F/U+20E3 mark may escape. |
| 834 | for (start, end) in [(0, 7), (5, 6), (6, 7)] { |
| 835 | let sliced = slice_visible_columns(row, start, end); |
| 836 | assert!( |
| 837 | sliced.contains("1\u{fe0f}\u{20e3}"), |
| 838 | "range=({start}, {end}) split keycap: {sliced:?}" |
| 839 | ); |
| 840 | } |
| 841 | } |
| 842 | |
| 843 | #[test] |
| 844 | fn truncate_line_to_width_always_stays_within_budget_with_keycap() { |
| 845 | // Budgets from zero through wide, with and without surrounding text. |
| 846 | let cases = [ |
| 847 | "1\u{fe0f}\u{20e3}", |
| 848 | "A 1\u{fe0f}\u{20e3} B", |
| 849 | "step 2\u{fe0f}\u{20e3} and 3\u{fe0f}\u{20e3} continue", |
| 850 | ]; |
| 851 | for text in &cases { |
| 852 | for budget in 0..=text_display_width(text) + 4 { |
| 853 | let out = truncate_line_to_width(text, budget); |
| 854 | let width = text_display_width(&out); |
| 855 | assert!( |
| 856 | width <= budget, |
| 857 | "budget={budget} text={text:?} -> {out:?} (width={width})" |
| 858 | ); |
| 859 | assert!(!out.ends_with('\u{fe0f}')); |
| 860 | assert!(!out.starts_with('\u{20e3}')); |
| 861 | } |
| 862 | } |
| 863 | } |
| 864 | } |
| 865 |