mirror of
https://github.com/openai/codex.git
synced 2026-11-25 23:30:49 +00:00
Render bidirectional transcript text on terminals without native ordering (#63844)
## Why Terminals that leave bidirectional ordering to the application can display Arabic and Hebrew transcript text in the wrong order, especially when it includes URLs, numbers, or inline code. ## What changed Use the terminal's bidirectional mode report when available on a direct connection, with a fallback for Windows Terminal, Ghostty, and Alacritty. Resolve direction before wrapping and reorder graphemes for display in the live transcript and scrollback. Preserve styling, hyperlink destinations, and logical text for copying. Keep URLs and inline literals left to right, and skip reordering for code blocks, tables, and lines with shell syntax that could be misrepresented. Measure hyperlink columns by painted graphemes so Arabic ligatures do not shift clickable ranges in the transcript or composer. ## Testing Cover agreement between streaming and finalized scrollback, preservation of shell command boundaries, startup probe reply handling, and wrapped composer links following Arabic text. GitOrigin-RevId: 9ffa0f491a93c78fef423acfc6a951cb037abd4d
This commit is contained in:
Generated
+1
@@ -5444,6 +5444,7 @@ dependencies = [
|
||||
"dunce",
|
||||
"futures",
|
||||
"http 1.4.0",
|
||||
"icu_properties",
|
||||
"image",
|
||||
"insta",
|
||||
"itertools 0.14.0",
|
||||
|
||||
@@ -431,6 +431,7 @@ iana-time-zone = "0.1.64"
|
||||
icu_decimal = "2.1"
|
||||
icu_locale_core = "2.1"
|
||||
icu_provider = { version = "2.1", features = ["sync"] }
|
||||
icu_properties = "2.2"
|
||||
ignore = "0.4.30"
|
||||
image = { version = "^0.25.9", default-features = false }
|
||||
include_dir = "0.7.4"
|
||||
|
||||
@@ -88,6 +88,7 @@ diffy = { workspace = true }
|
||||
dirs = { workspace = true }
|
||||
dunce = { workspace = true }
|
||||
http = { workspace = true }
|
||||
icu_properties = { workspace = true }
|
||||
image = { workspace = true, features = ["jpeg", "png", "gif", "webp"] }
|
||||
itertools = { workspace = true }
|
||||
lazy_static = { workspace = true }
|
||||
|
||||
@@ -1600,6 +1600,7 @@ impl App {
|
||||
}
|
||||
|
||||
fn render_chat_widget_frame(&mut self, tui: &mut tui::Tui, screen_size: Size) -> Result<Rect> {
|
||||
self.chat_widget.bidi_layout = tui.terminal.bidi_layout;
|
||||
self.chat_widget
|
||||
.set_sparkle_terminal_focus(tui.is_terminal_focused());
|
||||
if tui.is_owned_screen() {
|
||||
|
||||
@@ -5,8 +5,8 @@ use super::wrapping::visible_prefix;
|
||||
use crate::terminal_hyperlinks::HyperlinkLine;
|
||||
use crate::terminal_hyperlinks::TerminalHyperlink;
|
||||
use crate::terminal_hyperlinks::mark_buffer_hyperlinks;
|
||||
use crate::terminal_hyperlinks::source_text_width;
|
||||
use crate::terminal_hyperlinks::web_links_in_text;
|
||||
use crate::width::display_width;
|
||||
use ratatui::buffer::Buffer;
|
||||
use ratatui::layout::Rect;
|
||||
use ratatui::text::Line;
|
||||
@@ -33,7 +33,7 @@ impl HyperlinkCache {
|
||||
let source_columns = lines
|
||||
.iter()
|
||||
.map(|line| {
|
||||
source_column += display_width(&display_text[previous_start..line.start]);
|
||||
source_column += source_text_width(&display_text[previous_start..line.start]);
|
||||
previous_start = line.start;
|
||||
source_column
|
||||
})
|
||||
@@ -66,7 +66,7 @@ impl HyperlinkCache {
|
||||
area.width,
|
||||
);
|
||||
let visible = text_for_display(raw_visible);
|
||||
let line_end = source_column + display_width(visible.as_ref());
|
||||
let line_end = source_column + source_text_width(visible.as_ref());
|
||||
let first_hyperlink = self
|
||||
.hyperlinks
|
||||
.partition_point(|hyperlink| hyperlink.columns.end <= source_column);
|
||||
|
||||
@@ -138,7 +138,7 @@ fn composer_wrapped_url_fragments_keep_the_complete_destination() {
|
||||
#[test]
|
||||
fn scrolled_url_fragments_keep_the_offscreen_destination() {
|
||||
let url = "https://example.test/alpha/beta/gamma/delta/epsilon";
|
||||
let (_, state, buf) = render(url, /*width*/ 16, /*height*/ 2);
|
||||
let (_, state, buf) = render(&format!("لا\n{url}"), /*width*/ 16, /*height*/ 2);
|
||||
let visible_url = linked_text(&assert_destination(&buf, url));
|
||||
assert!(state.scroll > 0);
|
||||
assert_ne!(visible_url, url);
|
||||
|
||||
@@ -536,6 +536,7 @@ pub(crate) enum ExternalEditorState {
|
||||
/// (which view gets Ctrl+C), while `ChatWidget` owns process-level decisions such as interrupting
|
||||
/// active work, arming the double-press quit shortcut, and requesting shutdown-first exit.
|
||||
pub(crate) struct ChatWidget {
|
||||
pub(crate) bidi_layout: bool,
|
||||
pub(crate) empty_state_animation:
|
||||
std::cell::RefCell<crate::empty_state_animation::EmptyStateAnimation>,
|
||||
pub(crate) daybreak_enabled: bool,
|
||||
|
||||
@@ -124,6 +124,7 @@ impl ChatWidget {
|
||||
effects: local_settings.tui.effects,
|
||||
skills: None,
|
||||
}),
|
||||
bidi_layout: false,
|
||||
transcript: TranscriptState::new(active_cell),
|
||||
raw_output_mode: local_settings.tui.raw_output_mode,
|
||||
config,
|
||||
|
||||
@@ -266,6 +266,7 @@ impl ChatWidget {
|
||||
let active_cell_right_reserve = self.ambient_pet_wrap_reserved_cols();
|
||||
let active_cell_renderable = match &self.transcript.active_cell {
|
||||
Some(cell) => RenderableItem::Owned(Box::new(TranscriptAreaRenderable {
|
||||
bidi_layout: self.bidi_layout,
|
||||
child: cell.as_ref(),
|
||||
// The initial header becomes the first history cell, which has no leading separator.
|
||||
top: if cell.as_any().is::<history_cell::SessionHeaderHistoryCell>() {
|
||||
@@ -300,6 +301,7 @@ impl ChatWidget {
|
||||
flex.push(
|
||||
/*flex*/ 1,
|
||||
RenderableItem::Owned(Box::new(TranscriptAreaRenderable {
|
||||
bidi_layout: self.bidi_layout,
|
||||
child: cell.as_ref(),
|
||||
top: 1,
|
||||
right: active_cell_right_reserve,
|
||||
@@ -312,6 +314,7 @@ impl ChatWidget {
|
||||
flex.push(
|
||||
/*flex*/ 1,
|
||||
RenderableItem::Owned(Box::new(TranscriptAreaRenderable {
|
||||
bidi_layout: self.bidi_layout,
|
||||
child: cell,
|
||||
top: 1,
|
||||
right: active_cell_right_reserve,
|
||||
@@ -466,6 +469,7 @@ impl ChatWidget {
|
||||
}
|
||||
|
||||
struct TranscriptAreaRenderable<'a> {
|
||||
bidi_layout: bool,
|
||||
child: &'a dyn HistoryCell,
|
||||
top: u16,
|
||||
right: u16,
|
||||
@@ -482,7 +486,10 @@ struct PersistentActiveCellLayout<'a> {
|
||||
impl Renderable for TranscriptAreaRenderable<'_> {
|
||||
fn render(&self, area: Rect, buf: &mut Buffer) {
|
||||
let area = self.child_area(area);
|
||||
let lines = self.child.display_hyperlink_lines(area.width);
|
||||
let mut lines = self.child.display_hyperlink_lines(area.width);
|
||||
if self.bidi_layout {
|
||||
crate::terminal_hyperlinks::bidi::paint_rows(&mut lines, usize::from(area.width));
|
||||
}
|
||||
let paragraph = HyperlinkParagraph::new(&lines, Style::default());
|
||||
let y = if area.height == 0 {
|
||||
0
|
||||
|
||||
@@ -314,6 +314,7 @@ fn active_transcript_preserves_clipped_markdown_hyperlinks() {
|
||||
std::path::Path::new("/tmp"),
|
||||
);
|
||||
let renderable = TranscriptAreaRenderable {
|
||||
bidi_layout: false,
|
||||
child: &cell,
|
||||
top: 1,
|
||||
right: 2,
|
||||
|
||||
@@ -147,6 +147,7 @@ where
|
||||
/// The backend used to interface with the terminal
|
||||
backend: B,
|
||||
pub(crate) virtual_image_base: Option<u32>,
|
||||
pub(crate) bidi_layout: bool,
|
||||
/// Holds the results of the current and previous draw calls. The two are compared at the end
|
||||
/// of each draw pass to output the necessary updates to the terminal
|
||||
buffers: [Buffer; 2],
|
||||
@@ -240,6 +241,7 @@ where
|
||||
Self {
|
||||
backend,
|
||||
virtual_image_base: None,
|
||||
bidi_layout: false,
|
||||
buffers: [Buffer::empty(Rect::ZERO), Buffer::empty(Rect::ZERO)],
|
||||
current: 0,
|
||||
hidden_cursor: false,
|
||||
|
||||
@@ -330,6 +330,7 @@ impl HistoryCell for UserHistoryCell {
|
||||
source.right_reserve = 1;
|
||||
source.copy_as_prose |= copy_as_prose;
|
||||
}
|
||||
crate::terminal_hyperlinks::bidi::prepare_message(&mut lines);
|
||||
lines
|
||||
}
|
||||
|
||||
@@ -522,7 +523,8 @@ impl AgentMessageCell {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn new_hyperlink_lines(lines: Vec<HyperlinkLine>, is_first_line: bool) -> Self {
|
||||
pub(crate) fn new_hyperlink_lines(mut lines: Vec<HyperlinkLine>, is_first_line: bool) -> Self {
|
||||
crate::terminal_hyperlinks::bidi::prepare_message(&mut lines);
|
||||
Self {
|
||||
lines,
|
||||
is_first_line,
|
||||
@@ -761,7 +763,9 @@ impl AgentMarkdownCell {
|
||||
markdown,
|
||||
)
|
||||
};
|
||||
normalize_whitespace_only_hyperlink_lines(lines)
|
||||
let mut lines = normalize_whitespace_only_hyperlink_lines(lines);
|
||||
crate::terminal_hyperlinks::bidi::prepare_message(&mut lines);
|
||||
lines
|
||||
};
|
||||
|
||||
if let Some(rendered_lines) = &self.rendered_lines {
|
||||
@@ -825,7 +829,8 @@ impl PartialEq for StreamingAgentTailCell {
|
||||
}
|
||||
|
||||
impl StreamingAgentTailCell {
|
||||
pub(crate) fn new(lines: Vec<HyperlinkLine>, is_first_line: bool) -> Self {
|
||||
pub(crate) fn new(mut lines: Vec<HyperlinkLine>, is_first_line: bool) -> Self {
|
||||
crate::terminal_hyperlinks::bidi::prepare_message(&mut lines);
|
||||
Self {
|
||||
lines,
|
||||
is_first_line,
|
||||
|
||||
@@ -132,7 +132,10 @@ where
|
||||
// - Non-URL lines also flow through adaptive wrapping; behavior is
|
||||
// equivalent to standard wrapping when no URL is present.
|
||||
let wrap_width = area.width.max(1) as usize;
|
||||
let (wrapped, wrapped_rows) = wrap_history_hyperlink_lines(lines, wrap_width, wrap_policy);
|
||||
let (mut wrapped, wrapped_rows) = wrap_history_hyperlink_lines(lines, wrap_width, wrap_policy);
|
||||
if terminal.bidi_layout {
|
||||
crate::terminal_hyperlinks::bidi::paint_rows(&mut wrapped, wrap_width);
|
||||
}
|
||||
let wrapped_lines = wrapped_rows as u16;
|
||||
match mode {
|
||||
InsertHistoryMode::FullScreen => {
|
||||
@@ -951,6 +954,61 @@ mod tests {
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rtl_transcript_stream_matches_finalized_scrollback() {
|
||||
use crate::history_cell::AgentMarkdownCell;
|
||||
use crate::history_cell::HistoryCell;
|
||||
use crate::history_cell::HistoryRenderMode;
|
||||
use crate::history_cell::StreamingAgentTailCell;
|
||||
use crate::history_cell::new_user_prompt;
|
||||
use crate::streaming::controller::StreamController;
|
||||
use crate::terminal_hyperlinks::bidi;
|
||||
use pretty_assertions::assert_eq;
|
||||
let cwd = std::path::Path::new(".");
|
||||
let width = 48;
|
||||
let mut stream =
|
||||
StreamController::new(Some(usize::from(width) - 2), cwd, HistoryRenderMode::Rich);
|
||||
stream.push("افتح `--file.rs` ثم ش");
|
||||
stream.push("غل Codex 123 (مَرْحَبًا)");
|
||||
let preview = stream.current_tail_lines();
|
||||
let tail = StreamingAgentTailCell::new(preview, stream.tail_starts_stream());
|
||||
let mut live = tail.display_hyperlink_lines(width);
|
||||
bidi::paint_rows(&mut live, width.into());
|
||||
let (committed, source) = stream.finalize();
|
||||
let finalized = AgentMarkdownCell::new(source.unwrap(), cwd);
|
||||
let question = "مرحبا https://example.org/?a=1&b=2#help";
|
||||
let prompt = new_user_prompt(question.into(), vec![], vec![], vec![]);
|
||||
let mut lines = prompt.display_hyperlink_lines(width);
|
||||
lines.extend(committed.unwrap().display_hyperlink_lines(width));
|
||||
lines.extend(finalized.display_hyperlink_lines(width));
|
||||
let backend = VT100Backend::new(width, /*height*/ 12);
|
||||
let mut term = crate::custom_terminal::Terminal::with_options(backend).unwrap();
|
||||
term.bidi_layout = true;
|
||||
term.set_viewport_area(Rect::new(
|
||||
/*x*/ 0, /*y*/ 11, width, /*height*/ 1,
|
||||
));
|
||||
let size = term.last_known_screen_size;
|
||||
insert_history_hyperlink_lines_with_mode_and_wrap_policy(
|
||||
&mut term,
|
||||
&lines,
|
||||
InsertHistoryMode::Standard,
|
||||
HistoryLineWrapPolicy::PreWrap,
|
||||
size,
|
||||
)
|
||||
.unwrap();
|
||||
let rows = term
|
||||
.backend()
|
||||
.vt100()
|
||||
.screen()
|
||||
.rows(/*start*/ 0, width)
|
||||
.filter(|row| !row.trim().is_empty())
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(rows.len(), 3);
|
||||
assert_eq!(rows[1], rows[2]);
|
||||
assert_eq!(live[0].line.to_string(), rows[1]);
|
||||
insta::assert_snapshot!(rows[..2].join("\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vt100_user_message_url_wrap_preserves_gutter_and_background() {
|
||||
use crate::history_cell::HistoryCell;
|
||||
|
||||
@@ -136,7 +136,7 @@ pub(crate) struct CopyLine {
|
||||
/// A visual separator inserted between sibling list items, never source content.
|
||||
pub(crate) omit: bool,
|
||||
runs: Vec<(Range<usize>, Vec<Inline>)>,
|
||||
literal_ranges: Vec<Range<usize>>,
|
||||
pub(crate) literal_ranges: Vec<Range<usize>>,
|
||||
}
|
||||
|
||||
/// Keep literal prompt spacing when parsing only changed whitespace, and retain the source
|
||||
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
---
|
||||
source: tui/src/insert_history.rs
|
||||
expression: "rows[..2].join(\"\\n\")"
|
||||
---
|
||||
› ابحرم https://example.org/?a=1&b=2#help
|
||||
• (ابًحَرْمَ) Codex 123 لغش مث --file.rs حتفا
|
||||
@@ -85,6 +85,38 @@ fn zellij_session() -> bool {
|
||||
.any(|key| std::env::var_os(key).is_some())
|
||||
}
|
||||
|
||||
fn direct_stdout() -> bool {
|
||||
std::io::stdout().is_terminal() && !screen_active()
|
||||
}
|
||||
|
||||
fn is_direct_terminal(terminal: &TerminalInfo, term: Option<&str>) -> bool {
|
||||
terminal.multiplexer.is_none()
|
||||
&& !term.is_some_and(|term| {
|
||||
term == "dumb" || term.starts_with("screen") || term.starts_with("tmux")
|
||||
})
|
||||
}
|
||||
|
||||
fn direct_terminal_name() -> Option<TerminalName> {
|
||||
let terminal = terminal_info();
|
||||
(direct_stdout() && is_direct_terminal(&terminal, std::env::var("TERM").ok().as_deref()))
|
||||
.then_some(terminal.name)
|
||||
}
|
||||
|
||||
/// A terminal's explicit bidi mode overrides assumptions about its renderer.
|
||||
/// Silence or an unrecognized mode alone cannot rule out native or partial RTL.
|
||||
pub(crate) fn needs_bidi_layout(implicit_bidi: Option<bool>) -> bool {
|
||||
let Some(name) = direct_terminal_name() else {
|
||||
return false;
|
||||
};
|
||||
if let Some(implicit) = implicit_bidi {
|
||||
return !implicit;
|
||||
}
|
||||
matches!(
|
||||
name,
|
||||
TerminalName::WindowsTerminal | TerminalName::Ghostty | TerminalName::Alacritty
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
pub(crate) fn should_probe_inline_screen() -> bool {
|
||||
terminal_info().multiplexer.is_none() && is_ssh_session()
|
||||
@@ -282,11 +314,7 @@ pub(crate) enum WebLinkDisplay {
|
||||
}
|
||||
|
||||
pub(crate) fn web_link_display(terminal: &TerminalInfo, term: Option<&str>) -> WebLinkDisplay {
|
||||
if terminal.multiplexer.is_some()
|
||||
|| term.is_some_and(|term| {
|
||||
term == "dumb" || term.starts_with("screen") || term.starts_with("tmux")
|
||||
})
|
||||
{
|
||||
if !is_direct_terminal(terminal, term) {
|
||||
return WebLinkDisplay::WithDestination;
|
||||
}
|
||||
match terminal.name {
|
||||
@@ -310,7 +338,7 @@ pub(crate) fn web_link_display(terminal: &TerminalInfo, term: Option<&str>) -> W
|
||||
}
|
||||
|
||||
pub(crate) fn detect_web_link_display() -> WebLinkDisplay {
|
||||
if !std::io::stdout().is_terminal() || screen_active() {
|
||||
if !direct_stdout() {
|
||||
return WebLinkDisplay::WithDestination;
|
||||
}
|
||||
web_link_display(&terminal_info(), std::env::var("TERM").ok().as_deref())
|
||||
|
||||
@@ -73,6 +73,7 @@ mod imp {
|
||||
/// Results from the TUI's one-shot startup terminal probe.
|
||||
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq)]
|
||||
pub(crate) struct StartupProbe {
|
||||
pub(crate) implicit_bidi: Option<bool>,
|
||||
pub(crate) alternate_scroll_enabled: Option<bool>,
|
||||
pub(crate) cursor_position: Option<Position>,
|
||||
pub(crate) default_colors: Option<DefaultColors>,
|
||||
@@ -319,6 +320,12 @@ mod imp {
|
||||
if keyboard_probe == StartupKeyboardEnhancementProbe::Query {
|
||||
query.extend_from_slice(b"\x1B[?u");
|
||||
}
|
||||
// ECMA-48 mode 8 distinguishes terminal-managed (set) from application-managed
|
||||
// (reset) ordering. A multiplexer cannot speak for its attached clients.
|
||||
let probe_bidi = crate::terminal_capabilities::direct_terminal_name().is_some();
|
||||
if probe_bidi {
|
||||
query.extend_from_slice(b"\x1B[8$p");
|
||||
}
|
||||
// Query before DA1 so its reply acts as a barrier even if mode 1007 is unsupported.
|
||||
query.extend_from_slice(b"\x1B[?1007$p");
|
||||
if probe_kitty_graphics {
|
||||
@@ -341,11 +348,13 @@ mod imp {
|
||||
probe_kitty_graphics,
|
||||
&mut buffer,
|
||||
);
|
||||
let (replay, kitty_graphics) = parse_startup_input(&buffer, probe_kitty_graphics);
|
||||
let (replay, kitty_graphics, implicit_bidi) =
|
||||
parse_startup_input(&buffer, probe_kitty_graphics, probe_bidi);
|
||||
crossterm::event::buffer_input(&replay)?;
|
||||
let saw_da1 = find_primary_device_attributes(&buffer).is_some();
|
||||
DA1_SUPPORTED.store(saw_da1, Ordering::Relaxed);
|
||||
result.map(|probe| StartupProbe {
|
||||
implicit_bidi,
|
||||
kitty_graphics,
|
||||
..probe
|
||||
})
|
||||
@@ -715,6 +724,7 @@ mod imp {
|
||||
default_colors: None,
|
||||
keyboard_enhancement_supported: None,
|
||||
prefer_inline_screen: Some(false),
|
||||
implicit_bidi: None,
|
||||
kitty_graphics: false,
|
||||
};
|
||||
let mut saw_supported_keyboard = false;
|
||||
@@ -750,6 +760,7 @@ mod imp {
|
||||
}),
|
||||
keyboard_enhancement_supported: Some(true),
|
||||
prefer_inline_screen: Some(false),
|
||||
implicit_bidi: None,
|
||||
kitty_graphics: false,
|
||||
}
|
||||
);
|
||||
@@ -767,6 +778,7 @@ mod imp {
|
||||
default_colors: None,
|
||||
keyboard_enhancement_supported: None,
|
||||
prefer_inline_screen: None,
|
||||
implicit_bidi: None,
|
||||
kitty_graphics: false,
|
||||
};
|
||||
let mut supported_keyboard = false;
|
||||
@@ -847,14 +859,17 @@ mod imp {
|
||||
}),
|
||||
keyboard_enhancement_supported: Some(true),
|
||||
prefer_inline_screen: Some(false),
|
||||
implicit_bidi: None,
|
||||
kitty_graphics: false,
|
||||
}
|
||||
);
|
||||
let mut expected_replay = vec![b'x'; 2_048];
|
||||
expected_replay.extend_from_slice(b"\x1B[20;10R\x1B[?64;1;2c\x1B[?7u");
|
||||
assert_eq!(
|
||||
parse_startup_input(&buffer, /*probe_kitty_graphics*/ false),
|
||||
(expected_replay, false)
|
||||
parse_startup_input(
|
||||
&buffer, /*probe_kitty_graphics*/ false, /*probe_bidi*/ false
|
||||
),
|
||||
(expected_replay, false, None)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -2,16 +2,21 @@
|
||||
|
||||
const MAX_REPLAYED_OSC_BYTES: usize = 1024;
|
||||
|
||||
/// Return the input to replay and whether the terminal acknowledged the Kitty graphics query.
|
||||
/// Return typeahead, the Kitty graphics acknowledgment, and the reported bidi mode.
|
||||
///
|
||||
/// Keep bounded incomplete OSC prefixes so unread continuations stay parser-framed.
|
||||
pub(super) fn parse_startup_input(input: &[u8], probe_kitty_graphics: bool) -> (Vec<u8>, bool) {
|
||||
pub(super) fn parse_startup_input(
|
||||
input: &[u8],
|
||||
probe_kitty_graphics: bool,
|
||||
probe_bidi: bool,
|
||||
) -> (Vec<u8>, bool, Option<bool>) {
|
||||
const PASTE_START: &[u8] = b"\x1b[200~";
|
||||
const PASTE_END: &[u8] = b"\x1b[201~";
|
||||
const KITTY_REPLY: &[u8] = b"\x1b_Gi=31;";
|
||||
|
||||
let mut replay = Vec::with_capacity(input.len());
|
||||
let mut kitty_graphics = false;
|
||||
let mut implicit_bidi = None;
|
||||
let mut cursor = 0;
|
||||
let mut inside_paste = false;
|
||||
while cursor < input.len() {
|
||||
@@ -22,6 +27,16 @@ pub(super) fn parse_startup_input(input: &[u8], probe_kitty_graphics: bool) -> (
|
||||
cursor += 11;
|
||||
continue;
|
||||
}
|
||||
if probe_bidi
|
||||
&& let Some([0x1b, b'[', b'8', b';', mode @ b'0'..=b'4', b'$', b'y']) =
|
||||
input.get(cursor..cursor + 7)
|
||||
{
|
||||
// DECRPM 0 means unrecognized, 1/3 set, 2/4 reset.
|
||||
implicit_bidi = (*mode != b'0').then_some(matches!(*mode, b'1' | b'3'));
|
||||
cursor += 7;
|
||||
continue;
|
||||
}
|
||||
|
||||
if inside_paste {
|
||||
if input[cursor..].starts_with(PASTE_END) {
|
||||
replay.extend_from_slice(PASTE_END);
|
||||
@@ -78,7 +93,7 @@ pub(super) fn parse_startup_input(input: &[u8], probe_kitty_graphics: bool) -> (
|
||||
replay.push(input[cursor]);
|
||||
cursor += 1;
|
||||
}
|
||||
(replay, kitty_graphics)
|
||||
(replay, kitty_graphics, implicit_bidi)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -5,7 +5,10 @@ use super::parse_startup_input;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn startup_replay_input(input: &[u8]) -> Vec<u8> {
|
||||
parse_startup_input(input, /*probe_kitty_graphics*/ false).0
|
||||
parse_startup_input(
|
||||
input, /*probe_kitty_graphics*/ false, /*probe_bidi*/ false,
|
||||
)
|
||||
.0
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -73,8 +76,30 @@ fn herdr_graphics_reply_selects_previews_without_replaying_the_response_as_keys(
|
||||
] {
|
||||
let input = [paste.as_slice(), reply, b"typed"].concat();
|
||||
assert_eq!(
|
||||
parse_startup_input(&input, /*probe_kitty_graphics*/ true),
|
||||
([paste.as_slice(), b"typed"].concat(), expected)
|
||||
parse_startup_input(
|
||||
&input, /*probe_kitty_graphics*/ true, /*probe_bidi*/ false
|
||||
),
|
||||
([paste.as_slice(), b"typed"].concat(), expected, None)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bidi_replies_interleaved_with_paste_are_consumed_only_when_queried() {
|
||||
for (mode, implicit) in [
|
||||
(0, None),
|
||||
(1, Some(true)),
|
||||
(2, Some(false)),
|
||||
(3, Some(true)),
|
||||
(4, Some(false)),
|
||||
] {
|
||||
let input = format!("typed\x1b[200~a\x1b[8;{mode}$yb\x1b[201~").into_bytes();
|
||||
assert_eq!(
|
||||
parse_startup_input(
|
||||
&input, /*probe_kitty_graphics*/ false, /*probe_bidi*/ true
|
||||
),
|
||||
(b"typed\x1b[200~ab\x1b[201~".to_vec(), false, implicit)
|
||||
);
|
||||
assert_eq!(startup_replay_input(&input), input);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
//! Layout code measures and wraps ordinary ratatui lines. Hyperlink annotations are applied only
|
||||
//! when text reaches a terminal buffer or scrollback writer so OSC 8 bytes never affect geometry.
|
||||
|
||||
pub(crate) mod bidi;
|
||||
mod paragraph;
|
||||
mod source;
|
||||
|
||||
@@ -321,8 +322,16 @@ pub(crate) fn lines_with_sources_eq(left: &[HyperlinkLine], right: &[HyperlinkLi
|
||||
}
|
||||
|
||||
pub(crate) fn source_span_width(span: &Span<'_>) -> usize {
|
||||
span.content
|
||||
.graphemes(/*is_extended*/ true)
|
||||
source_text_width(&span.content)
|
||||
}
|
||||
|
||||
/// Link columns count painted graphemes, even when adjacent letters (lam-alef)
|
||||
/// measure as a single ligature in the whole string.
|
||||
pub(crate) fn source_text_width(text: &str) -> usize {
|
||||
if text.is_ascii() {
|
||||
return display_width(text);
|
||||
}
|
||||
text.graphemes(/*is_extended*/ true)
|
||||
.map(display_width)
|
||||
.sum()
|
||||
}
|
||||
@@ -582,18 +591,21 @@ pub(crate) fn remap_source_wrapped_line(
|
||||
.map(|wrapped| {
|
||||
let line = line_to_static(&wrapped.line);
|
||||
let displayed = line_text(&line);
|
||||
let prefix_columns = display_width(&displayed[..wrapped.prefix_bytes]);
|
||||
let prefix_columns = source_text_width(&displayed[..wrapped.prefix_bytes]);
|
||||
// Some wrapping paths retain a one-past-the-end cursor sentinel. Span slicing already
|
||||
// clips that sentinel to the visible line; keep hyperlink and source projection on the
|
||||
// same bounded range instead of indexing past the flattened text.
|
||||
let range = wrapped.range.start.min(text.len())..wrapped.range.end.min(text.len());
|
||||
source_column += display_width(&text[source_byte..range.start]);
|
||||
let start = source_column;
|
||||
let end = start + display_width(&text[range.clone()]);
|
||||
source_byte = range.end;
|
||||
source_column = end;
|
||||
let hyperlinks =
|
||||
project_hyperlink_columns(&source.hyperlinks, start..end, prefix_columns);
|
||||
let hyperlinks = if source.hyperlinks.is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
source_column += source_text_width(&text[source_byte..range.start]);
|
||||
let start = source_column;
|
||||
let end = start + source_text_width(&text[range.clone()]);
|
||||
source_byte = range.end;
|
||||
source_column = end;
|
||||
project_hyperlink_columns(&source.hyperlinks, start..end, prefix_columns)
|
||||
};
|
||||
HyperlinkLine {
|
||||
line,
|
||||
hyperlinks,
|
||||
@@ -720,15 +732,10 @@ fn push_link_range(line: &mut HyperlinkLine, range: Range<usize>, link: &Termina
|
||||
line.hyperlinks.push(link.with_columns(range));
|
||||
}
|
||||
|
||||
pub(crate) fn web_links_in_text(text: &str) -> Vec<TerminalHyperlink> {
|
||||
let mut links = Vec::new();
|
||||
let mut search_from = 0usize;
|
||||
let mut source_byte = 0usize;
|
||||
let mut source_column = 0usize;
|
||||
for raw_token in text.split_whitespace() {
|
||||
let Some(relative_start) = text[search_from..].find(raw_token) else {
|
||||
continue;
|
||||
};
|
||||
fn web_link_ranges(text: &str) -> impl Iterator<Item = (Range<usize>, String)> + '_ {
|
||||
let mut search_from = 0;
|
||||
text.split_whitespace().filter_map(move |raw_token| {
|
||||
let relative_start = text[search_from..].find(raw_token)?;
|
||||
let raw_start = search_from + relative_start;
|
||||
search_from = raw_start + raw_token.len();
|
||||
let trimmed_start = raw_token
|
||||
@@ -736,17 +743,24 @@ pub(crate) fn web_links_in_text(text: &str) -> Vec<TerminalHyperlink> {
|
||||
.unwrap_or(raw_token.len());
|
||||
let trimmed_end = trailing_url_end(&raw_token[trimmed_start..]) + trimmed_start;
|
||||
if trimmed_start >= trimmed_end {
|
||||
continue;
|
||||
return None;
|
||||
}
|
||||
let candidate = &raw_token[trimmed_start..trimmed_end];
|
||||
let Some(destination) = web_destination(candidate) else {
|
||||
continue;
|
||||
};
|
||||
let candidate_start = raw_start + trimmed_start;
|
||||
let range = raw_start + trimmed_start..raw_start + trimmed_end;
|
||||
let destination = web_destination(&text[range.clone()])?;
|
||||
Some((range, destination))
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn web_links_in_text(text: &str) -> Vec<TerminalHyperlink> {
|
||||
let mut links = Vec::new();
|
||||
let mut source_byte = 0usize;
|
||||
let mut source_column = 0usize;
|
||||
for (range, destination) in web_link_ranges(text) {
|
||||
let candidate_start = range.start;
|
||||
// Measure disjoint prefixes so scanning a draft with many URLs stays linear.
|
||||
source_column += display_width(&text[source_byte..candidate_start]);
|
||||
source_column += source_text_width(&text[source_byte..candidate_start]);
|
||||
source_byte = candidate_start;
|
||||
let end = source_column + display_width(candidate);
|
||||
let end = source_column + source_text_width(&text[range]);
|
||||
links.push(TerminalHyperlink::web(source_column..end, destination));
|
||||
}
|
||||
links
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
//! Visual order for message prose on terminals that leave ordering to the application. Resolve direction on
|
||||
//! the logical paragraph, then permute graphemes only after wrapping. The terminal
|
||||
//! still supplies glyph shaping. Never use the visual line as a copy or reflow source.
|
||||
|
||||
use super::HyperlinkLine;
|
||||
use super::line_text;
|
||||
use super::push_link_range;
|
||||
use super::push_styled_content;
|
||||
use crate::text_formatting::contains_rtl_or_arabic_number;
|
||||
use crate::width::display_width;
|
||||
use icu_properties::CodePointMapData;
|
||||
use icu_properties::props::BidiMirroringGlyph;
|
||||
use ratatui::text::Line;
|
||||
use std::borrow::Cow;
|
||||
use std::sync::Arc;
|
||||
use unicode_bidi::BidiClass;
|
||||
use unicode_bidi::Level;
|
||||
use unicode_bidi::ParagraphBidiInfo;
|
||||
use unicode_bidi::bidi_class;
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
use unicode_width::UnicodeWidthChar;
|
||||
|
||||
pub(crate) fn prepare_message(lines: &mut [HyperlinkLine]) {
|
||||
for source in lines.iter_mut().filter_map(|line| line.source.as_mut()) {
|
||||
source.message = true;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn resolve_paragraphs(lines: &mut [HyperlinkLine]) {
|
||||
for group in lines.chunk_by_mut(|a, b| {
|
||||
matches!(
|
||||
(&a.source, &b.source),
|
||||
(Some(a), Some(b)) if Arc::ptr_eq(&a.text, &b.text)
|
||||
)
|
||||
}) {
|
||||
let Some(source) = &group[0].source else {
|
||||
continue;
|
||||
};
|
||||
// Invisible direction changes can disguise executable syntax. Allow zero-width
|
||||
// nonspacing marks and boundary neutrals (e.g. joiners), which set no direction.
|
||||
if !source.message || source
|
||||
.copy
|
||||
.as_ref()
|
||||
.is_some_and(|copy| copy.code || copy.table.is_some() || copy.code_source.is_some())
|
||||
// Do not move text across shell operators or substitution markers.
|
||||
|| source.text.contains(['\t', ';', '|', '<', '>', '$', '`'])
|
||||
|| !contains_rtl_or_arabic_number(&source.text)
|
||||
|| source.text.chars().any(|c| {
|
||||
c.width() == Some(0) && !matches!(bidi_class(c), BidiClass::NSM | BidiClass::BN)
|
||||
})
|
||||
{
|
||||
continue;
|
||||
}
|
||||
// Treat URLs and literals as strong LTR tokens without changing byte offsets.
|
||||
let mut text = Cow::Borrowed(source.text.as_ref());
|
||||
for (range, _) in super::web_link_ranges(&source.text) {
|
||||
text.to_mut()
|
||||
.replace_range(range.clone(), &"a".repeat(range.len()));
|
||||
}
|
||||
// Exempt URL fragments and query separators, but keep checking literals.
|
||||
if text.contains(['#', '&']) {
|
||||
continue;
|
||||
}
|
||||
for range in source.copy.iter().flat_map(|copy| ©.literal_ranges) {
|
||||
if text.get(range.clone()).is_some() {
|
||||
text.to_mut()
|
||||
.replace_range(range.clone(), &"a".repeat(range.len()));
|
||||
}
|
||||
}
|
||||
// An unquoted URL's & is also a shell operator. An LTR base keeps the
|
||||
// masked URL at level zero, so no text can move across that boundary.
|
||||
let base = source.text.contains('&').then_some(Level::ltr());
|
||||
let levels: Arc<[Level]> = ParagraphBidiInfo::new(&text, base).levels.into();
|
||||
for source in group.iter_mut().filter_map(|line| line.source.as_mut()) {
|
||||
source.bidi = Some(Arc::clone(&levels));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn paint_rows(lines: &mut [HyperlinkLine], width: usize) {
|
||||
resolve_paragraphs(lines);
|
||||
for line in lines {
|
||||
if let Some(source) = &line.source
|
||||
&& let Some(levels) = &source.bidi
|
||||
&& let Some(levels) = levels.get(source.range.clone())
|
||||
&& let Some(visual) = project(line, levels, width)
|
||||
{
|
||||
*line = visual;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn project(line: &HyperlinkLine, levels: &[Level], width: usize) -> Option<HyperlinkLine> {
|
||||
let source = line.source.as_ref()?;
|
||||
// Never reorder across terminal autowrap boundaries (e.g. an oversized URL).
|
||||
if line.width() > width || levels.len() != source.range.len() {
|
||||
return None;
|
||||
}
|
||||
let text = line_text(&line.line);
|
||||
let start = source.prefix_bytes;
|
||||
let body = text.get(start..start + levels.len())?;
|
||||
if Some(body) != source.text.get(source.range.clone()) {
|
||||
return None;
|
||||
}
|
||||
// Keep synthetic gutters and trailing wrap padding outside the bidi run.
|
||||
let end = start + body.trim_end().len();
|
||||
let mut spans = line.line.spans.iter();
|
||||
let mut span = spans.next()?;
|
||||
let mut span_end = span.content.len();
|
||||
let mut column = 0;
|
||||
let mut links = line.hyperlinks.iter().peekable();
|
||||
let mut graphemes = Vec::new();
|
||||
let mut row_levels = Vec::new();
|
||||
for (byte, grapheme) in text.grapheme_indices(/*is_extended*/ true) {
|
||||
while byte >= span_end {
|
||||
span = spans.next()?;
|
||||
span_end += span.content.len();
|
||||
}
|
||||
let level = if (start..end).contains(&byte) {
|
||||
levels[byte - start]
|
||||
} else {
|
||||
Level::ltr()
|
||||
};
|
||||
row_levels.push(level);
|
||||
let cells = display_width(grapheme);
|
||||
while links.peek().is_some_and(|link| link.columns.end <= column) {
|
||||
links.next();
|
||||
}
|
||||
let link = links
|
||||
.peek()
|
||||
.copied()
|
||||
.filter(|link| link.columns.contains(&column));
|
||||
graphemes.push((grapheme, cells, span.style, link));
|
||||
column += cells;
|
||||
}
|
||||
let mut visual = HyperlinkLine::new(Line::default().style(line.line.style));
|
||||
visual.line.alignment = line.line.alignment;
|
||||
column = 0;
|
||||
for index in ParagraphBidiInfo::reorder_visual(&row_levels) {
|
||||
let (grapheme, cells, style, link) = graphemes[index];
|
||||
if cells == 0 {
|
||||
continue;
|
||||
}
|
||||
let mut symbol = Cow::Borrowed(grapheme);
|
||||
if row_levels[index].is_rtl()
|
||||
&& let Some(base) = grapheme.chars().next()
|
||||
&& let Some(mirror) = CodePointMapData::<BidiMirroringGlyph>::new()
|
||||
.get(base)
|
||||
.mirroring_glyph
|
||||
{
|
||||
symbol
|
||||
.to_mut()
|
||||
.replace_range(..base.len_utf8(), mirror.encode_utf8(&mut [0; 4]));
|
||||
}
|
||||
push_styled_content(&mut visual.line.spans, &symbol, style);
|
||||
if let Some(link) = link {
|
||||
push_link_range(&mut visual, column..column + cells, link);
|
||||
}
|
||||
column += cells;
|
||||
}
|
||||
Some(visual)
|
||||
}
|
||||
@@ -23,6 +23,9 @@ pub(crate) enum LineWrapPolicy {
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub(crate) struct LogicalLineSource {
|
||||
pub(crate) text: Arc<str>,
|
||||
pub(crate) message: bool,
|
||||
/// Paragraph embedding levels indexed by logical byte, shared across wrapped message rows.
|
||||
pub(crate) bidi: Option<Arc<[unicode_bidi::Level]>>,
|
||||
pub(crate) copy: Option<Arc<crate::markdown_copy::CopyLine>>,
|
||||
/// Selectable label length and the original body, whose Markdown ranges exclude the label.
|
||||
pub(crate) labelled_body: Option<Arc<(usize, LogicalLineSource)>>,
|
||||
@@ -47,6 +50,8 @@ impl LogicalLineSource {
|
||||
let end = text.len();
|
||||
Self {
|
||||
text: text.into(),
|
||||
message: false,
|
||||
bidi: None,
|
||||
copy: None,
|
||||
labelled_body: None,
|
||||
copy_as_prose: false,
|
||||
@@ -108,6 +113,8 @@ impl LogicalLineSource {
|
||||
let end = displayed.end.clamp(source_start, source_end);
|
||||
Self {
|
||||
text: Arc::clone(&self.text),
|
||||
message: self.message,
|
||||
bidi: self.bidi.clone(),
|
||||
copy: self.copy.clone(),
|
||||
labelled_body: self.labelled_body.clone(),
|
||||
copy_as_prose: self.copy_as_prose,
|
||||
|
||||
@@ -9,7 +9,7 @@ use ratatui::text::Span;
|
||||
use crate::terminal_hyperlinks::HyperlinkLine;
|
||||
use crate::terminal_hyperlinks::LineWrapPolicy;
|
||||
use crate::terminal_hyperlinks::LogicalLineSource;
|
||||
use crate::width::display_width;
|
||||
use crate::terminal_hyperlinks::source_text_width;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct LogicalLine {
|
||||
@@ -66,7 +66,11 @@ impl LogicalLine {
|
||||
);
|
||||
let prefix = slice_line(&line.line, 0..source.prefix_bytes);
|
||||
let prefix_width = prefix.width();
|
||||
let content_width = display_width(&source.text[source.range.clone()]);
|
||||
let content_width = if line.hyperlinks.is_empty() {
|
||||
0
|
||||
} else {
|
||||
source_text_width(&source.text[source.range.clone()])
|
||||
};
|
||||
self.line.line.spans.extend(body.spans);
|
||||
self.line
|
||||
.hyperlinks
|
||||
|
||||
@@ -481,3 +481,31 @@ fn document_link_navigation_preserves_occurrences_across_wraps() {
|
||||
assert_eq!(links, ["first link wraps", "second link"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rtl_transcript_preserves_command_boundaries() {
|
||||
use crate::terminal_hyperlinks::bidi;
|
||||
let paint = |command: &'static str| {
|
||||
let mut lines = prefix_hyperlink_lines(vec![command.into()], "".into(), "".into());
|
||||
bidi::prepare_message(&mut lines);
|
||||
bidi::paint_rows(&mut lines, /*width*/ 80);
|
||||
lines[0].line.to_string()
|
||||
};
|
||||
assert_eq!(
|
||||
paint(": שלום https://example.org/?x=1&make"),
|
||||
": םולש https://example.org/?x=1&make"
|
||||
);
|
||||
for command in [
|
||||
"echo SAFE \u{2067}שלום printf PWNED\u{2069}\u{200f}",
|
||||
": \u{070f} שלום printf PWNED",
|
||||
": שלום; echo SAFE; printf PWNED #",
|
||||
"שלום; echo SAFE; printf PWNED #",
|
||||
"שלום & calc.exe & עולם & ::",
|
||||
"שלום $(touch /tmp/PWNED)",
|
||||
"שלום https://example.org/?a=1&b=2 #",
|
||||
"שלום & https://example.org/#help",
|
||||
"שלום https://example.org/$name#help",
|
||||
] {
|
||||
assert_eq!(paint(command), command);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -594,6 +594,11 @@ pub(crate) fn init() -> Result<InitializedTerminal> {
|
||||
crate::terminal_palette::set_default_colors_from_startup_probe(/*colors*/ None);
|
||||
|
||||
let mut tui = CustomTerminal::with_options_and_cursor_position(backend, cursor_pos)?;
|
||||
#[cfg(unix)]
|
||||
let implicit_bidi = startup_probe.implicit_bidi;
|
||||
#[cfg(not(unix))]
|
||||
let implicit_bidi = None;
|
||||
tui.bidi_layout = terminal_capabilities::needs_bidi_layout(implicit_bidi);
|
||||
tui.virtual_image_base = session.virtual_image_base();
|
||||
let stderr_guard = terminal_stderr::TerminalStderrGuard::install()?;
|
||||
let initialized_terminal = InitializedTerminal {
|
||||
|
||||
Reference in New Issue
Block a user