mirror of
https://github.com/openai/codex.git
synced 2026-11-27 23:31:09 +00:00
Fix TUI layout for halfwidth Japanese sound marks (#35962)
## What changed - Use Ratatui-compatible terminal widths throughout TUI layout, preserving full-width counters for long lines. - Wrap and truncate on grapheme boundaries so halfwidth kana sound marks and emoji sequences stay intact. - Apply the corrected sizing to text input, selection popups, status and history cells, Markdown, hyperlinks, and scrollable cloud diffs. ## Testing - Add focused unit and snapshot coverage for wrapping, truncation, cursor and mask alignment, popup columns, status output, session headers, Markdown tables, process output, and scrollable diffs. GitOrigin-RevId: 294ec0bcff743c6bb16d55ec26308524ce741879
This commit is contained in:
1 parent
cef3910ea4
commit
3725f02cf3
38 files changed
+1335
-245
No files matched your search
+321
-16
@@ -32,9 +32,198 @@ use std::ops::Range;
|
||||
use textwrap::Options;
|
||||
use textwrap::WordSeparator;
|
||||
use textwrap::core::Word;
|
||||
use textwrap::core::display_width;
|
||||
use textwrap::word_splitters::split_words;
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
|
||||
use crate::line_truncation::line_width;
|
||||
use crate::render::line_utils::push_owned_lines;
|
||||
use crate::width::display_width;
|
||||
|
||||
/// Projected text keeps source-offset lookup separate from legal grapheme split points.
|
||||
struct ProjectedText {
|
||||
text: String,
|
||||
source_boundaries: Vec<(usize, usize)>,
|
||||
grapheme_boundaries: Vec<usize>,
|
||||
}
|
||||
|
||||
/// Replaces halfwidth sound-mark graphemes with equally wide, textwrap-safe placeholders.
|
||||
///
|
||||
/// Source boundaries recover original byte offsets, while grapheme boundaries keep placeholders
|
||||
/// indivisible and preserve leading whitespace as a wrapping opportunity.
|
||||
fn project_halfwidth_sound_marks(text: &str) -> Option<ProjectedText> {
|
||||
if !text.contains(['\u{FF9E}', '\u{FF9F}']) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut projected = String::with_capacity(text.len());
|
||||
let mut source_boundaries = vec![(0, 0)];
|
||||
let mut grapheme_boundaries = vec![0];
|
||||
for (source_start, grapheme) in text.grapheme_indices(/*is_extended*/ true) {
|
||||
if grapheme.contains(['\u{FF9E}', '\u{FF9F}']) {
|
||||
let source_end = source_start + grapheme.len();
|
||||
let content_start = grapheme
|
||||
.find(|ch: char| !ch.is_whitespace())
|
||||
.unwrap_or(grapheme.len());
|
||||
let (whitespace, content) = grapheme.split_at(content_start);
|
||||
for (offset, ch) in whitespace.char_indices() {
|
||||
projected.push(ch);
|
||||
source_boundaries.push((projected.len(), source_start + offset + ch.len_utf8()));
|
||||
grapheme_boundaries.push(projected.len());
|
||||
}
|
||||
|
||||
let width = display_width(content);
|
||||
let projected_start = projected.len();
|
||||
for _ in 0..width / 2 {
|
||||
if projected.len() > projected_start {
|
||||
projected.push('\u{2060}');
|
||||
}
|
||||
projected.push('界');
|
||||
source_boundaries.push((projected.len(), source_end));
|
||||
}
|
||||
if width % 2 == 1 {
|
||||
if projected.len() > projected_start {
|
||||
projected.push('\u{2060}');
|
||||
}
|
||||
projected.push('a');
|
||||
source_boundaries.push((projected.len(), source_end));
|
||||
}
|
||||
} else {
|
||||
for (offset, ch) in grapheme.char_indices() {
|
||||
projected.push(ch);
|
||||
source_boundaries.push((projected.len(), source_start + offset + ch.len_utf8()));
|
||||
}
|
||||
}
|
||||
grapheme_boundaries.push(projected.len());
|
||||
}
|
||||
|
||||
Some(ProjectedText {
|
||||
text: projected,
|
||||
source_boundaries,
|
||||
grapheme_boundaries,
|
||||
})
|
||||
}
|
||||
|
||||
/// Maps a projected byte offset back to the corresponding original-text boundary.
|
||||
fn source_offset(boundaries: &[(usize, usize)], projected_offset: usize) -> usize {
|
||||
boundaries
|
||||
.binary_search_by_key(&projected_offset, |(offset, _)| *offset)
|
||||
.map(|index| boundaries[index].1)
|
||||
.unwrap_or(projected_offset)
|
||||
}
|
||||
|
||||
/// Splits oversized projected words without separating placeholders for one source grapheme.
|
||||
fn break_projected_words<'a>(
|
||||
words: impl Iterator<Item = Word<'a>>,
|
||||
projected: &'a ProjectedText,
|
||||
line_width: usize,
|
||||
) -> Vec<Word<'a>> {
|
||||
let projected_start = projected.text.as_ptr() as usize;
|
||||
let mut pieces = Vec::new();
|
||||
|
||||
for word in words {
|
||||
if display_width(word.word) <= line_width {
|
||||
pieces.push(word);
|
||||
continue;
|
||||
}
|
||||
|
||||
let word_start = word.word.as_ptr() as usize - projected_start;
|
||||
let word_end = word_start + word.word.len();
|
||||
let mut piece_start = word_start;
|
||||
let mut piece_width = 0;
|
||||
let mut atom_start = word_start;
|
||||
let boundary_start = projected
|
||||
.grapheme_boundaries
|
||||
.partition_point(|atom_end| *atom_end <= word_start);
|
||||
|
||||
for atom_end in projected
|
||||
.grapheme_boundaries
|
||||
.iter()
|
||||
.copied()
|
||||
.skip(boundary_start)
|
||||
{
|
||||
if atom_end > word_end {
|
||||
break;
|
||||
}
|
||||
|
||||
let atom_width = display_width(&projected.text[atom_start..atom_end]);
|
||||
if piece_width > 0 && piece_width + atom_width > line_width {
|
||||
pieces.push(Word::from(&projected.text[piece_start..atom_start]));
|
||||
piece_start = atom_start;
|
||||
piece_width = 0;
|
||||
}
|
||||
piece_width += atom_width;
|
||||
atom_start = atom_end;
|
||||
}
|
||||
|
||||
let mut last = Word::from(&projected.text[piece_start..word_end]);
|
||||
last.whitespace = word.whitespace;
|
||||
last.penalty = word.penalty;
|
||||
pieces.push(last);
|
||||
}
|
||||
|
||||
pieces
|
||||
}
|
||||
|
||||
/// Wraps projected text and translates the resulting ranges back to source byte offsets.
|
||||
fn wrap_projected_ranges(
|
||||
projected: &ProjectedText,
|
||||
opts: &Options<'_>,
|
||||
include_trailing_spaces: bool,
|
||||
) -> Vec<Range<usize>> {
|
||||
let line_widths = [
|
||||
opts.width
|
||||
.saturating_sub(display_width(opts.initial_indent)),
|
||||
opts.width
|
||||
.saturating_sub(display_width(opts.subsequent_indent)),
|
||||
];
|
||||
let line_ending = opts.line_ending.as_str();
|
||||
let mut ranges = Vec::new();
|
||||
let mut line_start = 0;
|
||||
|
||||
for line in projected.text.split(line_ending) {
|
||||
let words = opts.word_separator.find_words(line);
|
||||
let split_words = split_words(words, &opts.word_splitter);
|
||||
let mut broken_words = if opts.break_words {
|
||||
break_projected_words(split_words, projected, line_widths[1])
|
||||
} else {
|
||||
split_words.collect()
|
||||
};
|
||||
if opts.break_words && !opts.initial_indent.is_empty() {
|
||||
broken_words.insert(0, Word::from(""));
|
||||
}
|
||||
|
||||
let wrapped_words = opts.wrap_algorithm.wrap(&broken_words, &line_widths);
|
||||
let mut cursor = line_start;
|
||||
for words in wrapped_words {
|
||||
let Some(last_word) = words.last() else {
|
||||
let source = source_offset(&projected.source_boundaries, cursor);
|
||||
ranges.push(source..source + usize::from(include_trailing_spaces));
|
||||
continue;
|
||||
};
|
||||
let len = words
|
||||
.iter()
|
||||
.map(|word| word.word.len() + word.whitespace.len())
|
||||
.sum::<usize>()
|
||||
- last_word.whitespace.len();
|
||||
let end = cursor + len;
|
||||
let trailing_spaces = if include_trailing_spaces {
|
||||
projected.text[end..]
|
||||
.chars()
|
||||
.take_while(|ch| *ch == ' ')
|
||||
.count()
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let source_start = source_offset(&projected.source_boundaries, cursor);
|
||||
let source_end = source_offset(&projected.source_boundaries, end + trailing_spaces);
|
||||
ranges.push(source_start..source_end + usize::from(include_trailing_spaces));
|
||||
cursor = end + last_word.whitespace.len();
|
||||
}
|
||||
line_start += line.len() + line_ending.len();
|
||||
}
|
||||
|
||||
ranges
|
||||
}
|
||||
|
||||
/// Returns byte-ranges into `text` for each wrapped line, including
|
||||
/// trailing whitespace and a +1 sentinel byte. Used by the textarea
|
||||
@@ -44,6 +233,9 @@ where
|
||||
O: Into<Options<'a>>,
|
||||
{
|
||||
let opts = width_or_options.into();
|
||||
if let Some(projected) = project_halfwidth_sound_marks(text) {
|
||||
return wrap_projected_ranges(&projected, &opts, /*include_trailing_spaces*/ true);
|
||||
}
|
||||
let mut lines: Vec<Range<usize>> = Vec::new();
|
||||
let mut cursor = 0usize;
|
||||
for (line_index, line) in textwrap::wrap(text, &opts).iter().enumerate() {
|
||||
@@ -87,6 +279,9 @@ where
|
||||
O: Into<Options<'a>>,
|
||||
{
|
||||
let opts = width_or_options.into();
|
||||
if let Some(projected) = project_halfwidth_sound_marks(text) {
|
||||
return wrap_projected_ranges(&projected, &opts, /*include_trailing_spaces*/ false);
|
||||
}
|
||||
let mut lines: Vec<Range<usize>> = Vec::new();
|
||||
let mut cursor = 0usize;
|
||||
for (line_index, line) in textwrap::wrap(text, &opts).iter().enumerate() {
|
||||
@@ -684,7 +879,7 @@ fn word_wrap_flattened_line<'a>(
|
||||
// Compute first line range with reduced width due to initial indent.
|
||||
let initial_width_available = opts
|
||||
.width
|
||||
.saturating_sub(rt_opts.initial_indent.width())
|
||||
.saturating_sub(line_width(&rt_opts.initial_indent))
|
||||
.max(1);
|
||||
let initial_wrapped = wrap_ranges_trim(flat, opts.clone().width(initial_width_available));
|
||||
let Some(first_line_range) = initial_wrapped.first() else {
|
||||
@@ -713,7 +908,7 @@ fn word_wrap_flattened_line<'a>(
|
||||
let base = base + skip_leading_spaces;
|
||||
let subsequent_width_available = opts
|
||||
.width
|
||||
.saturating_sub(rt_opts.subsequent_indent.width())
|
||||
.saturating_sub(line_width(&rt_opts.subsequent_indent))
|
||||
.max(1);
|
||||
let remaining_wrapped = wrap_ranges_trim(&flat[base..], opts.width(subsequent_width_available));
|
||||
for r in &remaining_wrapped {
|
||||
@@ -758,11 +953,11 @@ fn mixed_url_wrap_line<'a>(
|
||||
) -> Vec<Line<'a>> {
|
||||
let initial_width_available = rt_opts
|
||||
.width
|
||||
.saturating_sub(rt_opts.initial_indent.width())
|
||||
.saturating_sub(line_width(&rt_opts.initial_indent))
|
||||
.max(1);
|
||||
let subsequent_width_available = rt_opts
|
||||
.width
|
||||
.saturating_sub(rt_opts.subsequent_indent.width())
|
||||
.saturating_sub(line_width(&rt_opts.subsequent_indent))
|
||||
.max(1);
|
||||
let ranges = mixed_url_wrap_ranges(flat, initial_width_available, subsequent_width_available);
|
||||
|
||||
@@ -831,12 +1026,14 @@ fn mixed_url_wrap_ranges(
|
||||
0
|
||||
};
|
||||
let empty_line_piece_limit = line_limit.saturating_sub(empty_line_prefix_width).max(1);
|
||||
let mut indivisible = false;
|
||||
if line_start.is_none() && !piece.is_url && piece.width(text) > empty_line_piece_limit {
|
||||
pending.splice(
|
||||
pending_idx..=pending_idx,
|
||||
split_mixed_url_word(text, piece, empty_line_piece_limit),
|
||||
);
|
||||
continue;
|
||||
let split = split_mixed_url_word(text, piece.clone(), empty_line_piece_limit);
|
||||
if split.len() > 1 {
|
||||
pending.splice(pending_idx..=pending_idx, split);
|
||||
continue;
|
||||
}
|
||||
indivisible = true;
|
||||
}
|
||||
|
||||
let piece_width = piece.width(text);
|
||||
@@ -845,6 +1042,7 @@ fn mixed_url_wrap_ranges(
|
||||
.unwrap_or(0);
|
||||
let fits = if line_start.is_none() {
|
||||
piece.is_url
|
||||
|| indivisible
|
||||
|| empty_line_prefix_width + piece_width <= line_limit
|
||||
|| empty_line_prefix_width >= line_limit
|
||||
} else {
|
||||
@@ -894,16 +1092,27 @@ fn split_mixed_url_word(text: &str, word: MixedUrlWord, line_limit: usize) -> Ve
|
||||
return vec![word];
|
||||
}
|
||||
|
||||
let source = Word::from(&text[word.range.clone()]);
|
||||
let mut offset = word.range.start;
|
||||
let mut pieces = Vec::new();
|
||||
for piece in source.break_apart(line_limit.max(1)) {
|
||||
let end = offset + piece.word.len();
|
||||
let mut start = word.range.start;
|
||||
let mut width = 0usize;
|
||||
for (offset, grapheme) in text[word.range.clone()].grapheme_indices(/*is_extended*/ true) {
|
||||
let grapheme_width = display_width(grapheme);
|
||||
if width > 0 && width + grapheme_width > line_limit.max(1) {
|
||||
let end = word.range.start + offset;
|
||||
pieces.push(MixedUrlWord {
|
||||
range: start..end,
|
||||
is_url: false,
|
||||
});
|
||||
start = end;
|
||||
width = 0;
|
||||
}
|
||||
width += grapheme_width;
|
||||
}
|
||||
if start < word.range.end {
|
||||
pieces.push(MixedUrlWord {
|
||||
range: offset..end,
|
||||
range: start..word.range.end,
|
||||
is_url: false,
|
||||
});
|
||||
offset = end;
|
||||
}
|
||||
pieces
|
||||
}
|
||||
@@ -1490,6 +1699,24 @@ them."#
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adaptive_wrap_line_mixed_url_counts_halfwidth_sound_marks() {
|
||||
let line = Line::from("ガパtail https://x.co");
|
||||
let out = adaptive_wrap_line(&line, RtOptions::new(/*width*/ 4));
|
||||
let rendered = out.iter().map(concat_line).collect_vec();
|
||||
|
||||
assert_eq!(rendered, ["ガパ", "tail", "https://x.co"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adaptive_wrap_line_mixed_url_makes_progress_for_an_indivisible_grapheme() {
|
||||
let line = Line::from("ガ https://x.co");
|
||||
let out = adaptive_wrap_line(&line, RtOptions::new(/*width*/ 1));
|
||||
let rendered = out.iter().map(concat_line).collect_vec();
|
||||
|
||||
assert_eq!(rendered, ["ガ", "https://x.co"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn map_owned_wrapped_line_to_range_recovers_on_non_prefix_mismatch() {
|
||||
// Match source chars first, then introduce a non-penalty mismatch.
|
||||
@@ -1553,6 +1780,84 @@ them."#
|
||||
assert_eq!(rebuilt, text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrap_ranges_count_halfwidth_sound_marks_without_changing_byte_offsets() {
|
||||
for (text, width, expected) in [
|
||||
("abガc", 4, &["abガ", "c"][..]),
|
||||
("abガc", 3, &["ab", "ガc"][..]),
|
||||
("゙ab", 2, &["゙a", "b"][..]),
|
||||
("a ゙b", 2, &["a", "゙b"][..]),
|
||||
("a ゚b", 2, &["a", "゚b"][..]),
|
||||
("ガ゙x", 3, &["ガ゙", "x"][..]),
|
||||
("界゙x", 3, &["界゙", "x"][..]),
|
||||
("ガ゙ab", 2, &["ガ゙", "ab"][..]),
|
||||
("界゙ab", 2, &["界゙", "ab"][..]),
|
||||
("abガ゙cd", 2, &["ab", "ガ゙", "cd"][..]),
|
||||
("ab界゙cd", 2, &["ab", "界゙", "cd"][..]),
|
||||
] {
|
||||
let ranges = wrap_ranges_trim(text, Options::new(width));
|
||||
let wrapped = ranges
|
||||
.iter()
|
||||
.map(|range| &text[range.clone()])
|
||||
.collect_vec();
|
||||
assert_eq!(wrapped, expected);
|
||||
}
|
||||
|
||||
for (text, emoji, sound_mark) in [("a👨👩 ゙", "👨👩", "゙"), ("a👍🏻 ゚", "👍🏻", "゚")]
|
||||
{
|
||||
for options in [
|
||||
Options::new(/*width*/ 2),
|
||||
Options::new(/*width*/ 2).word_separator(WordSeparator::AsciiSpace),
|
||||
] {
|
||||
let ranges = wrap_ranges_trim(text, options);
|
||||
let wrapped = ranges
|
||||
.iter()
|
||||
.map(|range| &text[range.clone()])
|
||||
.collect_vec();
|
||||
|
||||
assert_eq!(wrapped, ["a", emoji, sound_mark]);
|
||||
}
|
||||
}
|
||||
|
||||
for grapheme in ["ガ゙", "界゙"] {
|
||||
for width in [1, 2] {
|
||||
let ranges = wrap_ranges(grapheme, Options::new(width));
|
||||
assert_eq!(ranges, std::iter::once(0..grapheme.len() + 1).collect_vec());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrap_ranges_preserve_crlf_source_boundaries_without_splitting_graphemes() {
|
||||
for prefix in ["ガ", "パ"] {
|
||||
let text = format!("{prefix}\r\nnext");
|
||||
|
||||
for word_separator in [
|
||||
WordSeparator::UnicodeBreakProperties,
|
||||
WordSeparator::AsciiSpace,
|
||||
] {
|
||||
for line_ending in [textwrap::LineEnding::LF, textwrap::LineEnding::CRLF] {
|
||||
let options = Options::new(/*width*/ 4)
|
||||
.line_ending(line_ending)
|
||||
.word_separator(word_separator)
|
||||
.wrap_algorithm(textwrap::WrapAlgorithm::FirstFit);
|
||||
let first_end =
|
||||
prefix.len() + usize::from(line_ending == textwrap::LineEnding::LF);
|
||||
let second_start = prefix.len() + "\r\n".len();
|
||||
|
||||
let ranges = wrap_ranges(&text, options.clone());
|
||||
assert_eq!(ranges, [0..first_end + 1, second_start..text.len() + 1]);
|
||||
for range in &ranges {
|
||||
assert!(text.get(range.start..range.end - 1).is_some());
|
||||
}
|
||||
|
||||
let trimmed = wrap_ranges_trim(&text, options);
|
||||
assert_eq!(trimmed, [0..first_end, second_start..text.len()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn map_owned_wrapped_line_to_range_repro_overconsumes_repeated_prefix_patterns() {
|
||||
let text = "- - foo";
|
||||
|
||||
Reference in new issue
Block a user