Lightweight coding agent that runs in your terminal
Rust
feat(tui): syntax highlighting via syntect with theme picker (#11447)
Felipe Couryc4f1af7a86a0
diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lockindex 31bc8d65a7..c910f95442 100644--- a/codex-rs/Cargo.lock+++ b/codex-rs/Cargo.lock@@ -852,6 +852,15 @@ version = "0.5.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3a8241f3ebb85c056b509d4327ad0358fbbba6ffb340bf388f26350aeda225b1"+[[package]]+name = "bincode"+version = "1.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad"+dependencies = [+ "serde",+]+[[package]]name = "bit-set"version = "0.5.3"@@ -2297,6 +2306,7 @@ dependencies = ["strum 0.27.2","strum_macros 0.27.2","supports-color 3.0.2",+ "syntect","tempfile","textwrap 0.16.2","thiserror 2.0.18",@@ -2307,8 +2317,7 @@ dependencies = ["tracing","tracing-appender","tracing-subscriber",- "tree-sitter-bash",- "tree-sitter-highlight",+ "two-face","unicode-segmentation","unicode-width 0.2.1","url",@@ -5157,6 +5166,12 @@ dependencies = ["vcpkg",]+[[package]]+name = "linked-hash-map"+version = "0.5.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f"+[[package]]name = "linux-keyutils"version = "0.2.4"@@ -5964,6 +5979,28 @@ version = "1.70.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"+[[package]]+name = "onig"+version = "6.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "336b9c63443aceef14bea841b899035ae3abe89b7c486aaf4c5bd8aafedac3f0"+dependencies = [+ "bitflags 2.10.0",+ "libc",+ "once_cell",+ "onig_sys",+]++[[package]]+name = "onig_sys"+version = "69.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c7f86c6eef3d6df15f23bcfb6af487cbd2fed4e5581d58d5bf1f5f8b7f6727dc"+dependencies = [+ "cc",+ "pkg-config",+]+[[package]]name = "opaque-debug"version = "0.3.1"@@ -6381,6 +6418,19 @@ version = "0.3.32"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c"+[[package]]+name = "plist"+version = "1.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "740ebea15c5d1428f910cd1a5f52cebf8d25006245ed8ade92702f4943d91e07"+dependencies = [+ "base64 0.22.1",+ "indexmap 2.13.0",+ "quick-xml",+ "serde",+ "time",+]+[[package]]name = "png"version = "0.18.0"@@ -8886,6 +8936,27 @@ dependencies = ["syn 2.0.114",]+[[package]]+name = "syntect"+version = "5.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "656b45c05d95a5704399aeef6bd0ddec7b2b3531b7c9e900abbf7c4d2190c925"+dependencies = [+ "bincode",+ "flate2",+ "fnv",+ "once_cell",+ "onig",+ "plist",+ "regex-syntax 0.8.8",+ "serde",+ "serde_derive",+ "serde_json",+ "thiserror 2.0.18",+ "walkdir",+ "yaml-rust",+]+[[package]]name = "sys-locale"version = "0.3.2"@@ -9622,18 +9693,6 @@ dependencies = ["tree-sitter-language",]-[[package]]-name = "tree-sitter-highlight"-version = "0.25.10"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "adc5f880ad8d8f94e88cb81c3557024cf1a8b75e3b504c50481ed4f5a6006ff3"-dependencies = [- "regex",- "streaming-iterator",- "thiserror 2.0.18",- "tree-sitter",-]-[[package]]name = "tree-sitter-language"version = "0.1.7"@@ -9701,6 +9760,17 @@ dependencies = ["utf-8",]+[[package]]+name = "two-face"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b285c51f8a6ade109ed4566d33ac4fb289fb5d6cf87ed70908a5eaf65e948e34"+dependencies = [+ "serde",+ "serde_derive",+ "syntect",+]+[[package]]name = "type-map"version = "0.5.1"@@ -10965,6 +11035,15 @@ dependencies = ["lzma-sys",]+[[package]]+name = "yaml-rust"+version = "0.4.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85"+dependencies = [+ "linked-hash-map",+]+[[package]]name = "yansi"version = "1.0.1"diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.tomlindex d23ed3c27b..e22dba12c2 100644--- a/codex-rs/Cargo.toml+++ b/codex-rs/Cargo.toml@@ -276,7 +276,7 @@ tracing-subscriber = "0.3.22"tracing-test = "0.2.5"tree-sitter = "0.25.10"tree-sitter-bash = "0.25"-tree-sitter-highlight = "0.25.10"+syntect = "5"ts-rs = "11"tungstenite = { version = "0.27.0", features = ["deflate", "proxy"] }uds_windows = "1.1.0"diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.jsonindex addbcbe313..ed1ae8ddbf 100644--- a/codex-rs/core/config.schema.json+++ b/codex-rs/core/config.schema.json@@ -1400,6 +1400,11 @@"type": "string"},"type": "array"+ },+ "theme": {+ "default": null,+ "description": "Syntax highlighting theme name (kebab-case).\n\nWhen set, overrides automatic light/dark theme detection. Use `/theme` in the TUI or see `$CODEX_HOME/themes` for custom themes.",+ "type": "string"}},"type": "object"diff --git a/codex-rs/core/src/config/edit.rs b/codex-rs/core/src/config/edit.rsindex 0dfb4efd8e..fceb965998 100644--- a/codex-rs/core/src/config/edit.rs+++ b/codex-rs/core/src/config/edit.rs@@ -55,6 +55,14 @@ pub enum ConfigEdit {ClearPath { segments: Vec<String> },}+/// Produces a config edit that sets `[tui] theme = "<name>"`.+pub fn syntax_theme_edit(name: &str) -> ConfigEdit {+ ConfigEdit::SetPath {+ segments: vec!["tui".to_string(), "theme".to_string()],+ value: value(name.to_string()),+ }+}+pub fn status_line_items_edit(items: &[String]) -> ConfigEdit {let mut array = toml_edit::Array::new();for item in items {diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rsindex ddc5aa9cdd..6474ca4bc0 100644--- a/codex-rs/core/src/config/mod.rs+++ b/codex-rs/core/src/config/mod.rs@@ -278,6 +278,9 @@ pub struct Config {/// `current-dir`.pub tui_status_line: Option<Vec<String>>,+ /// Syntax highlighting theme override (kebab-case name).+ pub tui_theme: Option<String>,+/// The directory that should be treated as the current working directory/// for the session. All relative paths inside the business-logic layer are/// resolved against this path.@@ -2120,6 +2123,7 @@ impl Config {.map(|t| t.alternate_screen).unwrap_or_default(),tui_status_line: cfg.tui.as_ref().and_then(|t| t.status_line.clone()),+ tui_theme: cfg.tui.as_ref().and_then(|t| t.theme.clone()),otel: {let t: OtelConfigToml = cfg.otel.unwrap_or_default();let log_user_prompt = t.log_user_prompt.unwrap_or(false);@@ -2518,6 +2522,30 @@ allowed_domains = ["openai.com"]Ok(())}+ #[test]+ fn tui_theme_deserializes_from_toml() {+ let cfg = r#"+[tui]+theme = "dracula"+"#;+ let parsed =+ toml::from_str::<ConfigToml>(cfg).expect("TOML deserialization should succeed");+ assert_eq!(+ parsed.tui.as_ref().and_then(|t| t.theme.as_deref()),+ Some("dracula"),+ );+ }++ #[test]+ fn tui_theme_defaults_to_none() {+ let cfg = r#"+[tui]+"#;+ let parsed =+ toml::from_str::<ConfigToml>(cfg).expect("TOML deserialization should succeed");+ assert_eq!(parsed.tui.as_ref().and_then(|t| t.theme.as_deref()), None);+ }+#[test]fn tui_config_missing_notifications_field_defaults_to_enabled() {let cfg = r#"@@ -2537,6 +2565,7 @@ allowed_domains = ["openai.com"]show_tooltips: true,alternate_screen: AltScreenMode::Auto,status_line: None,+ theme: None,});}@@ -4646,6 +4675,7 @@ model_verbosity = "high"feedback_enabled: true,tui_alternate_screen: AltScreenMode::Auto,tui_status_line: None,+ tui_theme: None,otel: OtelConfig::default(),},o3_profile_config@@ -4768,6 +4798,7 @@ model_verbosity = "high"feedback_enabled: true,tui_alternate_screen: AltScreenMode::Auto,tui_status_line: None,+ tui_theme: None,otel: OtelConfig::default(),};@@ -4888,6 +4919,7 @@ model_verbosity = "high"feedback_enabled: true,tui_alternate_screen: AltScreenMode::Auto,tui_status_line: None,+ tui_theme: None,otel: OtelConfig::default(),};@@ -4994,6 +5026,7 @@ model_verbosity = "high"feedback_enabled: true,tui_alternate_screen: AltScreenMode::Auto,tui_status_line: None,+ tui_theme: None,otel: OtelConfig::default(),};diff --git a/codex-rs/core/src/config/types.rs b/codex-rs/core/src/config/types.rsindex 2e3573f770..678766e807 100644--- a/codex-rs/core/src/config/types.rs+++ b/codex-rs/core/src/config/types.rs@@ -681,6 +681,13 @@ pub struct Tui {/// `current-dir`.#[serde(default)]pub status_line: Option<Vec<String>>,++ /// Syntax highlighting theme name (kebab-case).+ ///+ /// When set, overrides automatic light/dark theme detection.+ /// Use `/theme` in the TUI or see `$CODEX_HOME/themes` for custom themes.+ #[serde(default)]+ pub theme: Option<String>,}const fn default_true() -> bool {diff --git a/codex-rs/deny.toml b/codex-rs/deny.tomlindex e96e6fbd33..29bf6c5880 100644--- a/codex-rs/deny.toml+++ b/codex-rs/deny.toml@@ -75,6 +75,9 @@ ignore = [{ id = "RUSTSEC-2024-0436", reason = "paste is unmaintained; pulled in via ratatui/rmcp/starlark used by tui/execpolicy; no fixed release yet" },# TODO(joshka, nornagon): remove this exception when once we update the ratatui fork to a version that uses lru 0.13+.{ id = "RUSTSEC-2026-0002", reason = "lru 0.12.5 is pulled in via ratatui fork; cannot upgrade until the fork is updated" },+ # TODO(fcoury): remove this exception when syntect drops yaml-rust and bincode, or updates to versions that have fixed the vulnerabilities.+ { id = "RUSTSEC-2024-0320", reason = "yaml-rust is unmaintained; pulled in via syntect v5.3.0 used by codex-tui for syntax highlighting; no fixed release yet" },+ { id = "RUSTSEC-2025-0141", reason = "bincode is unmaintained; pulled in via syntect v5.3.0 used by codex-tui for syntax highlighting; no fixed release yet" },]# If this is true, then cargo deny will use the git executable to fetch advisory database.# If this is false, then it uses a built-in git library.diff --git a/codex-rs/tui/Cargo.toml b/codex-rs/tui/Cargo.tomlindex 683b0828dc..1b0ed9771e 100644--- a/codex-rs/tui/Cargo.toml+++ b/codex-rs/tui/Cargo.toml@@ -93,8 +93,8 @@ toml = { workspace = true }tracing = { workspace = true, features = ["log"] }tracing-appender = { workspace = true }tracing-subscriber = { workspace = true, features = ["env-filter"] }-tree-sitter-bash = { workspace = true }-tree-sitter-highlight = { workspace = true }+syntect = "5"+two-face = { version = "0.5", default-features = false, features = ["syntect-default-onig"] }unicode-segmentation = { workspace = true }unicode-width = { workspace = true }url = { workspace = true }diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rsindex ebbf757523..22ceed1ffa 100644--- a/codex-rs/tui/src/app.rs+++ b/codex-rs/tui/src/app.rs@@ -2605,6 +2605,34 @@ impl App {AppEvent::StatusLineSetupCancelled => {self.chat_widget.cancel_status_line_setup();}+ AppEvent::SyntaxThemeSelected { name } => {+ let edit = codex_core::config::edit::syntax_theme_edit(&name);+ let apply_result = ConfigEditsBuilder::new(&self.config.codex_home)+ .with_edits([edit])+ .apply()+ .await;+ match apply_result {+ Ok(()) => {+ // Ensure the selected theme is active in the current+ // session. The preview callback covers arrow-key+ // navigation, but if the user presses Enter without+ // navigating, the runtime theme must still be applied.+ if let Some(theme) = crate::render::highlight::resolve_theme_by_name(+ &name,+ Some(&self.config.codex_home),+ ) {+ crate::render::highlight::set_syntax_theme(theme);+ }+ self.sync_tui_theme_selection(name);+ }+ Err(err) => {+ self.restore_runtime_theme_from_config();+ tracing::error!(error = %err, "failed to persist theme selection");+ self.chat_widget+ .add_error_message(format!("Failed to save theme: {err}"));+ }+ }+ }}Ok(AppRunControl::Continue)}@@ -2783,6 +2811,29 @@ impl App {self.chat_widget.set_personality(personality);}+ fn sync_tui_theme_selection(&mut self, name: String) {+ self.config.tui_theme = Some(name.clone());+ self.chat_widget.set_tui_theme(Some(name));+ }++ fn restore_runtime_theme_from_config(&self) {+ if let Some(name) = self.config.tui_theme.as_deref()+ && let Some(theme) =+ crate::render::highlight::resolve_theme_by_name(name, Some(&self.config.codex_home))+ {+ crate::render::highlight::set_syntax_theme(theme);+ return;+ }++ let auto_theme_name = crate::render::highlight::adaptive_default_theme_name();+ if let Some(theme) = crate::render::highlight::resolve_theme_by_name(+ auto_theme_name,+ Some(&self.config.codex_home),+ ) {+ crate::render::highlight::set_syntax_theme(theme);+ }+ }+fn personality_label(personality: Personality) -> &'static str {match personality {Personality::None => "None",@@ -3655,6 +3706,19 @@ mod tests {Ok(())}+ #[tokio::test]+ async fn sync_tui_theme_selection_updates_chat_widget_config_copy() {+ let mut app = make_test_app().await;++ app.sync_tui_theme_selection("dracula".to_string());++ assert_eq!(app.config.tui_theme.as_deref(), Some("dracula"));+ assert_eq!(+ app.chat_widget.config_ref().tui_theme.as_deref(),+ Some("dracula")+ );+ }+#[tokio::test]async fn backtrack_selection_with_duplicate_history_targets_unique_turn() {let (mut app, _app_event_rx, mut op_rx) = make_test_app_with_channels().await;diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rsindex 159cda88f4..60c25fcc4e 100644--- a/codex-rs/tui/src/app_event.rs+++ b/codex-rs/tui/src/app_event.rs@@ -360,6 +360,11 @@ pub(crate) enum AppEvent {},/// Dismiss the status-line setup UI without changing config.StatusLineSetupCancelled,++ /// Apply a user-confirmed syntax theme selection.+ SyntaxThemeSelected {+ name: String,+ },}/// The exit strategy requested by the UI layer.diff --git a/codex-rs/tui/src/bottom_pane/list_selection_view.rs b/codex-rs/tui/src/bottom_pane/list_selection_view.rsindex 14f94ca6f4..ad40c1660f 100644--- a/codex-rs/tui/src/bottom_pane/list_selection_view.rs+++ b/codex-rs/tui/src/bottom_pane/list_selection_view.rs@@ -33,9 +33,76 @@ use super::selection_popup_common::render_rows_stable_col_widths;use super::selection_popup_common::render_rows_with_col_width_mode;use unicode_width::UnicodeWidthStr;+/// Minimum list width (in content columns) required before the side-by-side+/// layout is activated. Keeps the list usable even when sharing horizontal+/// space with the side content panel.+const MIN_LIST_WIDTH_FOR_SIDE: u16 = 40;++/// Horizontal gap (in columns) between the list area and the side content+/// panel when side-by-side layout is active.+const SIDE_CONTENT_GAP: u16 = 2;++/// Shared menu-surface horizontal inset (2 cells per side) used by selection popups.+const MENU_SURFACE_HORIZONTAL_INSET: u16 = 4;++/// Controls how the side content panel is sized relative to the popup width.+///+/// When the computed side width falls below `side_content_min_width` or the+/// remaining list area would be narrower than [`MIN_LIST_WIDTH_FOR_SIDE`], the+/// side-by-side layout is abandoned and the stacked fallback is used instead.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum SideContentWidth {+ /// Fixed number of columns. `Fixed(0)` disables side content entirely.+ Fixed(u16),+ /// Exact 50/50 split of the content area (minus the inter-column gap).+ Half,+}++impl Default for SideContentWidth {+ fn default() -> Self {+ Self::Fixed(0)+ }+}++/// Returns the popup content width after subtracting the shared menu-surface+/// horizontal inset (2 columns on each side).+pub(crate) fn popup_content_width(total_width: u16) -> u16 {+ total_width.saturating_sub(MENU_SURFACE_HORIZONTAL_INSET)+}++/// Returns side-by-side layout widths as `(list_width, side_width)` when the+/// layout can fit. Returns `None` when the side panel is disabled/too narrow or+/// when the remaining list width would become unusably small.+pub(crate) fn side_by_side_layout_widths(+ content_width: u16,+ side_content_width: SideContentWidth,+ side_content_min_width: u16,+) -> Option<(u16, u16)> {+ let side_width = match side_content_width {+ SideContentWidth::Fixed(0) => return None,+ SideContentWidth::Fixed(width) => width,+ SideContentWidth::Half => content_width.saturating_sub(SIDE_CONTENT_GAP) / 2,+ };+ if side_width < side_content_min_width {+ return None;+ }+ let list_width = content_width.saturating_sub(SIDE_CONTENT_GAP + side_width);+ (list_width >= MIN_LIST_WIDTH_FOR_SIDE).then_some((list_width, side_width))+}+/// One selectable item in the generic selection list.pub(crate) type SelectionAction = Box<dyn Fn(&AppEventSender) + Send + Sync>;+/// Callback invoked whenever the highlighted item changes (arrow keys, search+/// filter, number-key jump). Receives the *actual* index into the unfiltered+/// `items` list and the event sender. Used by the theme picker for live preview.+pub(crate) type OnSelectionChangedCallback =+ Option<Box<dyn Fn(usize, &AppEventSender) + Send + Sync>>;++/// Callback invoked when the picker is dismissed without accepting (Esc or+/// Ctrl+C). Used by the theme picker to restore the pre-open theme.+pub(crate) type OnCancelCallback = Option<Box<dyn Fn(&AppEventSender) + Send + Sync>>;+/// One row in a [`ListSelectionView`] selection list.////// This is the source-of-truth model for row state before filtering and@@ -79,6 +146,28 @@ pub(crate) struct SelectionViewParams {pub col_width_mode: ColumnWidthMode,pub header: Box<dyn Renderable>,pub initial_selected_idx: Option<usize>,++ /// Rich content rendered beside (wide terminals) or below (narrow terminals)+ /// the list items, inside the bordered menu surface. Used by the theme picker+ /// to show a syntax-highlighted preview.+ pub side_content: Box<dyn Renderable>,++ /// Width mode for side content when side-by-side layout is active.+ pub side_content_width: SideContentWidth,++ /// Minimum side panel width required before side-by-side layout activates.+ pub side_content_min_width: u16,++ /// Optional fallback content rendered when side-by-side does not fit.+ /// When absent, `side_content` is reused.+ pub stacked_side_content: Option<Box<dyn Renderable>>,++ /// Called when the highlighted item changes (navigation, filter, number-key).+ /// Receives the *actual* item index, not the filtered/visible index.+ pub on_selection_changed: OnSelectionChangedCallback,++ /// Called when the picker is dismissed via Esc/Ctrl+C without selecting.+ pub on_cancel: OnCancelCallback,}impl Default for SelectionViewParams {@@ -95,6 +184,12 @@ impl Default for SelectionViewParams {col_width_mode: ColumnWidthMode::AutoVisible,header: Box::new(()),initial_selected_idx: None,+ side_content: Box::new(()),+ side_content_width: SideContentWidth::default(),+ side_content_min_width: 0,+ stacked_side_content: None,+ on_selection_changed: None,+ on_cancel: None,}}}@@ -120,6 +215,16 @@ pub(crate) struct ListSelectionView {last_selected_actual_idx: Option<usize>,header: Box<dyn Renderable>,initial_selected_idx: Option<usize>,+ side_content: Box<dyn Renderable>,+ side_content_width: SideContentWidth,+ side_content_min_width: u16,+ stacked_side_content: Option<Box<dyn Renderable>>,++ /// Called when the highlighted item changes (navigation, filter, number-key).+ on_selection_changed: OnSelectionChangedCallback,++ /// Called when the picker is dismissed via Esc/Ctrl+C without selecting.+ on_cancel: OnCancelCallback,}impl ListSelectionView {@@ -161,6 +266,12 @@ impl ListSelectionView {last_selected_actual_idx: None,header,initial_selected_idx: params.initial_selected_idx,+ side_content: params.side_content,+ side_content_width: params.side_content_width,+ side_content_min_width: params.side_content_min_width,+ stacked_side_content: params.stacked_side_content,+ on_selection_changed: params.on_selection_changed,+ on_cancel: params.on_cancel,};s.apply_filter();s@@ -174,11 +285,15 @@ impl ListSelectionView {MAX_POPUP_ROWS.min(len.max(1))}- fn apply_filter(&mut self) {- let previously_selected = self- .state+ fn selected_actual_idx(&self) -> Option<usize> {+ self.state.selected_idx.and_then(|visible_idx| self.filtered_indices.get(visible_idx).copied())+ }++ fn apply_filter(&mut self) {+ let previously_selected = self+ .selected_actual_idx().or_else(|| {(!self.is_searchable).then(|| self.items.iter().position(|item| item.is_current))@@ -222,6 +337,13 @@ impl ListSelectionView {let visible = Self::max_visible_rows(len);self.state.clamp_selection(len);self.state.ensure_visible(len, visible);++ // Notify the callback when filtering changes the selected actual item+ // so live preview stays in sync (e.g. typing in the theme picker).+ let new_actual = self.selected_actual_idx();+ if new_actual != previously_selected {+ self.fire_selection_changed();+ }}fn build_rows(&self) -> Vec<GenericDisplayRow> {@@ -273,19 +395,35 @@ impl ListSelectionView {}fn move_up(&mut self) {+ let before = self.selected_actual_idx();let len = self.visible_len();self.state.move_up_wrap(len);let visible = Self::max_visible_rows(len);self.state.ensure_visible(len, visible);self.skip_disabled_up();+ if self.selected_actual_idx() != before {+ self.fire_selection_changed();+ }}fn move_down(&mut self) {+ let before = self.selected_actual_idx();let len = self.visible_len();self.state.move_down_wrap(len);let visible = Self::max_visible_rows(len);self.state.ensure_visible(len, visible);self.skip_disabled_down();+ if self.selected_actual_idx() != before {+ self.fire_selection_changed();+ }+ }++ fn fire_selection_changed(&self) {+ if let Some(cb) = &self.on_selection_changed+ && let Some(actual) = self.selected_actual_idx()+ {+ cb(actual, &self.app_event_tx);+ }}fn accept(&mut self) {@@ -310,6 +448,9 @@ impl ListSelectionView {self.complete = true;}} else if selected_item.is_none() {+ if let Some(cb) = &self.on_cancel {+ cb(&self.app_event_tx);+ }self.complete = true;}}@@ -328,6 +469,63 @@ impl ListSelectionView {total_width.saturating_sub(2)}+ fn clear_to_terminal_bg(buf: &mut Buffer, area: Rect) {+ let buf_area = buf.area();+ let min_x = area.x.max(buf_area.x);+ let min_y = area.y.max(buf_area.y);+ let max_x = area+ .x+ .saturating_add(area.width)+ .min(buf_area.x.saturating_add(buf_area.width));+ let max_y = area+ .y+ .saturating_add(area.height)+ .min(buf_area.y.saturating_add(buf_area.height));+ for y in min_y..max_y {+ for x in min_x..max_x {+ buf[(x, y)]+ .set_symbol(" ")+ .set_style(ratatui::style::Style::reset());+ }+ }+ }++ fn force_bg_to_terminal_bg(buf: &mut Buffer, area: Rect) {+ let buf_area = buf.area();+ let min_x = area.x.max(buf_area.x);+ let min_y = area.y.max(buf_area.y);+ let max_x = area+ .x+ .saturating_add(area.width)+ .min(buf_area.x.saturating_add(buf_area.width));+ let max_y = area+ .y+ .saturating_add(area.height)+ .min(buf_area.y.saturating_add(buf_area.height));+ for y in min_y..max_y {+ for x in min_x..max_x {+ buf[(x, y)].set_bg(ratatui::style::Color::Reset);+ }+ }+ }++ fn stacked_side_content(&self) -> &dyn Renderable {+ self.stacked_side_content+ .as_deref()+ .unwrap_or_else(|| self.side_content.as_ref())+ }++ /// Returns `Some(side_width)` when the content area is wide enough for a+ /// side-by-side layout (list + gap + side panel), `None` otherwise.+ fn side_layout_width(&self, content_width: u16) -> Option<u16> {+ side_by_side_layout_widths(+ content_width,+ self.side_content_width,+ self.side_content_min_width,+ )+ .map(|(_, side_width)| side_width)+ }+fn skip_disabled_down(&mut self) {let len = self.visible_len();for _ in 0..len {@@ -469,6 +667,9 @@ impl BottomPaneView for ListSelectionView {}fn on_ctrl_c(&mut self) -> CancellationEvent {+ if let Some(cb) = &self.on_cancel {+ cb(&self.app_event_tx);+ }self.complete = true;CancellationEvent::Handled}@@ -476,38 +677,59 @@ impl BottomPaneView for ListSelectionView {impl Renderable for ListSelectionView {fn desired_height(&self, width: u16) -> u16 {- // Measure wrapped height for up to MAX_POPUP_ROWS items at the given width.- // Build the same display rows used by the renderer so wrapping math matches.+ // Inner content width after menu surface horizontal insets (2 per side).+ let inner_width = popup_content_width(width);++ // When side-by-side is active, measure the list at the reduced width+ // that accounts for the gap and side panel.+ let effective_rows_width = if let Some(side_w) = self.side_layout_width(inner_width) {+ Self::rows_width(width).saturating_sub(SIDE_CONTENT_GAP + side_w)+ } else {+ Self::rows_width(width)+ };++ // Measure wrapped height for up to MAX_POPUP_ROWS items.let rows = self.build_rows();- let rows_width = Self::rows_width(width);let rows_height = match self.col_width_mode {ColumnWidthMode::AutoVisible => measure_rows_height(&rows,&self.state,MAX_POPUP_ROWS,- rows_width.saturating_add(1),+ effective_rows_width.saturating_add(1),),ColumnWidthMode::AutoAllRows => measure_rows_height_stable_col_widths(&rows,&self.state,MAX_POPUP_ROWS,- rows_width.saturating_add(1),+ effective_rows_width.saturating_add(1),),ColumnWidthMode::Fixed => measure_rows_height_with_col_width_mode(&rows,&self.state,MAX_POPUP_ROWS,- rows_width.saturating_add(1),+ effective_rows_width.saturating_add(1),ColumnWidthMode::Fixed,),};- // Subtract 4 for the padding on the left and right of the header.- let mut height = self.header.desired_height(width.saturating_sub(4));+ let mut height = self.header.desired_height(inner_width);height = height.saturating_add(rows_height + 3);if self.is_searchable {height = height.saturating_add(1);}++ // Side content: when the terminal is wide enough the panel sits beside+ // the list and shares vertical space; otherwise it stacks below.+ if self.side_layout_width(inner_width).is_some() {+ // Side-by-side — side content shares list rows vertically so it+ // doesn't add to total height.+ } else {+ let side_h = self.stacked_side_content().desired_height(inner_width);+ if side_h > 0 {+ height = height.saturating_add(1 + side_h);+ }+ }+if let Some(note) = &self.footer_note {let note_width = width.saturating_sub(2);let note_lines = wrap_styled_line(note, note_width);@@ -538,41 +760,60 @@ impl Renderable for ListSelectionView {// Paint the shared menu surface and then layout inside the returned inset.let content_area = render_menu_surface(outer_content_area, buf);- let header_height = self- .header- // Subtract 4 for the padding on the left and right of the header.- .desired_height(outer_content_area.width.saturating_sub(4));+ let inner_width = popup_content_width(outer_content_area.width);+ let side_w = self.side_layout_width(inner_width);++ // When side-by-side is active, shrink the list to make room.+ let full_rows_width = Self::rows_width(outer_content_area.width);+ let effective_rows_width = if let Some(sw) = side_w {+ full_rows_width.saturating_sub(SIDE_CONTENT_GAP + sw)+ } else {+ full_rows_width+ };++ let header_height = self.header.desired_height(inner_width);let rows = self.build_rows();- let rows_width = Self::rows_width(outer_content_area.width);let rows_height = match self.col_width_mode {ColumnWidthMode::AutoVisible => measure_rows_height(&rows,&self.state,MAX_POPUP_ROWS,- rows_width.saturating_add(1),+ effective_rows_width.saturating_add(1),),ColumnWidthMode::AutoAllRows => measure_rows_height_stable_col_widths(&rows,&self.state,MAX_POPUP_ROWS,- rows_width.saturating_add(1),+ effective_rows_width.saturating_add(1),),ColumnWidthMode::Fixed => measure_rows_height_with_col_width_mode(&rows,&self.state,MAX_POPUP_ROWS,- rows_width.saturating_add(1),+ effective_rows_width.saturating_add(1),ColumnWidthMode::Fixed,),};- let [header_area, _, search_area, list_area] = Layout::vertical([++ // Stacked (fallback) side content height — only used when not side-by-side.+ let stacked_side_h = if side_w.is_none() {+ self.stacked_side_content().desired_height(inner_width)+ } else {+ 0+ };+ let stacked_gap = if stacked_side_h > 0 { 1 } else { 0 };++ let [header_area, _, search_area, list_area, _, stacked_side_area] = Layout::vertical([Constraint::Max(header_height),Constraint::Max(1),Constraint::Length(if self.is_searchable { 1 } else { 0 }),Constraint::Length(rows_height),+ Constraint::Length(stacked_gap),+ Constraint::Length(stacked_side_h),]).areas(content_area);+ // -- Header --if header_area.height < header_height {let [header_area, elision_area] =Layout::vertical([Constraint::Fill(1), Constraint::Length(1)]).areas(header_area);@@ -585,6 +826,7 @@ impl Renderable for ListSelectionView {self.header.render(header_area, buf);}+ // -- Search bar --if self.is_searchable {Line::from(self.search_query.clone()).render(search_area, buf);let query_span: Span<'static> = if self.search_query.is_empty() {@@ -598,11 +840,12 @@ impl Renderable for ListSelectionView {Line::from(query_span).render(search_area, buf);}+ // -- List rows --if list_area.height > 0 {let render_area = Rect {x: list_area.x.saturating_sub(2),y: list_area.y,- width: rows_width.max(1),+ width: effective_rows_width.max(1),height: list_area.height,};match self.col_width_mode {@@ -634,6 +877,53 @@ impl Renderable for ListSelectionView {};}+ // -- Side content (preview panel) --+ if let Some(sw) = side_w {+ // Side-by-side: render to the right half of the popup content+ // area so preview content can center vertically in that panel.+ let side_x = content_area.x + content_area.width - sw;+ let side_area = Rect::new(side_x, content_area.y, sw, content_area.height);++ // Clear the menu-surface background behind the side panel so the+ // preview appears on the terminal's own background.+ let clear_x = side_x.saturating_sub(SIDE_CONTENT_GAP);+ let clear_w = outer_content_area+ .x+ .saturating_add(outer_content_area.width)+ .saturating_sub(clear_x);+ Self::clear_to_terminal_bg(+ buf,+ Rect::new(+ clear_x,+ outer_content_area.y,+ clear_w,+ outer_content_area.height,+ ),+ );+ self.side_content.render(side_area, buf);+ Self::force_bg_to_terminal_bg(+ buf,+ Rect::new(+ clear_x,+ outer_content_area.y,+ clear_w,+ outer_content_area.height,+ ),+ );+ } else if stacked_side_area.height > 0 {+ // Stacked fallback: render below the list (same as old footer_content).+ let clear_height = (outer_content_area.y + outer_content_area.height)+ .saturating_sub(stacked_side_area.y);+ let clear_area = Rect::new(+ outer_content_area.x,+ stacked_side_area.y,+ outer_content_area.width,+ clear_height,+ );+ Self::clear_to_terminal_bg(buf, clear_area);+ self.stacked_side_content().render(stacked_side_area, buf);+ }+if footer_area.height > 0 {let [note_area, hint_area] = Layout::vertical([Constraint::Length(note_height),@@ -683,9 +973,33 @@ mod tests {use crossterm::event::KeyCode;use insta::assert_snapshot;use pretty_assertions::assert_eq;+ use ratatui::buffer::Buffer;use ratatui::layout::Rect;+ use ratatui::style::Color;+ use ratatui::style::Style;use tokio::sync::mpsc::unbounded_channel;+ struct MarkerRenderable {+ marker: &'static str,+ height: u16,+ }++ impl Renderable for MarkerRenderable {+ fn render(&self, area: Rect, buf: &mut Buffer) {+ for y in area.y..area.y.saturating_add(area.height) {+ for x in area.x..area.x.saturating_add(area.width) {+ if x < buf.area().width && y < buf.area().height {+ buf[(x, y)].set_symbol(self.marker);+ }+ }+ }+ }++ fn desired_height(&self, _width: u16) -> u16 {+ self.height+ }+ }+fn make_selection_view(subtitle: Option<&str>) -> ListSelectionView {let (tx_raw, _rx) = unbounded_channel::<AppEvent>();let tx = AppEventSender::new(tx_raw);@@ -722,7 +1036,10 @@ mod tests {}fn render_lines_with_width(view: &ListSelectionView, width: u16) -> String {- let height = view.desired_height(width);+ render_lines_in_area(view, width, view.desired_height(width))+ }++ fn render_lines_in_area(view: &ListSelectionView, width: u16, height: u16) -> String {let area = Rect::new(0, 0, width, height);let mut buf = Buffer::empty(area);view.render(area, &mut buf);@@ -808,6 +1125,20 @@ mod tests {assert_snapshot!("list_selection_spacing_with_subtitle", render_lines(&view));}+ #[test]+ fn theme_picker_subtitle_uses_fallback_text_in_94x35_terminal() {+ let (tx_raw, _rx) = unbounded_channel::<AppEvent>();+ let tx = AppEventSender::new(tx_raw);+ let home = dirs::home_dir().expect("home directory should be available");+ let codex_home = home.join(".codex");+ let params =+ crate::theme_picker::build_theme_picker_params(None, Some(&codex_home), Some(94));+ let view = ListSelectionView::new(params, tx);++ let rendered = render_lines_in_area(&view, 94, 35);+ assert!(rendered.contains("Move up/down to live preview themes"));+ }+#[test]fn snapshot_footer_note_wraps() {let (tx_raw, _rx) = unbounded_channel::<AppEvent>();@@ -871,6 +1202,66 @@ mod tests {);}+ #[test]+ fn enter_with_no_matches_triggers_cancel_callback() {+ let (tx_raw, mut rx) = unbounded_channel::<AppEvent>();+ let tx = AppEventSender::new(tx_raw);+ let mut view = ListSelectionView::new(+ SelectionViewParams {+ items: vec![SelectionItem {+ name: "Read Only".to_string(),+ dismiss_on_select: true,+ ..Default::default()+ }],+ is_searchable: true,+ on_cancel: Some(Box::new(|tx: &_| {+ tx.send(AppEvent::OpenApprovalsPopup);+ })),+ ..Default::default()+ },+ tx,+ );+ view.set_search_query("no-matches".to_string());++ view.handle_key_event(KeyEvent::from(KeyCode::Enter));++ assert!(view.is_complete());+ match rx.try_recv() {+ Ok(AppEvent::OpenApprovalsPopup) => {}+ Ok(other) => panic!("expected OpenApprovalsPopup cancel event, got {other:?}"),+ Err(err) => panic!("expected cancel callback event, got {err}"),+ }+ }++ #[test]+ fn move_down_without_selection_change_does_not_fire_callback() {+ let (tx_raw, mut rx) = unbounded_channel::<AppEvent>();+ let tx = AppEventSender::new(tx_raw);+ let mut view = ListSelectionView::new(+ SelectionViewParams {+ items: vec![SelectionItem {+ name: "Only choice".to_string(),+ dismiss_on_select: true,+ ..Default::default()+ }],+ on_selection_changed: Some(Box::new(|_idx, tx: &_| {+ tx.send(AppEvent::OpenApprovalsPopup);+ })),+ ..Default::default()+ },+ tx,+ );++ while rx.try_recv().is_ok() {}++ view.handle_key_event(KeyEvent::from(KeyCode::Down));++ assert!(+ rx.try_recv().is_err(),+ "moving down in a single-item list should not fire on_selection_changed",+ );+ }+#[test]fn wraps_long_option_without_overflowing_columns() {let (tx_raw, _rx) = unbounded_channel::<AppEvent>();@@ -1159,4 +1550,194 @@ mod tests {"fixed description column changed across scroll:\nbefore:\n{before_scroll}\nafter:\n{after_scroll}");}++ #[test]+ fn side_layout_width_half_uses_exact_split() {+ let (tx_raw, _rx) = unbounded_channel::<AppEvent>();+ let tx = AppEventSender::new(tx_raw);+ let view = ListSelectionView::new(+ SelectionViewParams {+ items: vec![SelectionItem {+ name: "Item 1".to_string(),+ dismiss_on_select: true,+ ..Default::default()+ }],+ side_content: Box::new(MarkerRenderable {+ marker: "W",+ height: 1,+ }),+ side_content_width: SideContentWidth::Half,+ side_content_min_width: 10,+ ..Default::default()+ },+ tx,+ );++ let content_width: u16 = 120;+ let expected = content_width.saturating_sub(SIDE_CONTENT_GAP) / 2;+ assert_eq!(view.side_layout_width(content_width), Some(expected));+ }++ #[test]+ fn side_layout_width_half_falls_back_when_list_would_be_too_narrow() {+ let (tx_raw, _rx) = unbounded_channel::<AppEvent>();+ let tx = AppEventSender::new(tx_raw);+ let view = ListSelectionView::new(+ SelectionViewParams {+ items: vec![SelectionItem {+ name: "Item 1".to_string(),+ dismiss_on_select: true,+ ..Default::default()+ }],+ side_content: Box::new(MarkerRenderable {+ marker: "W",+ height: 1,+ }),+ side_content_width: SideContentWidth::Half,+ side_content_min_width: 50,+ ..Default::default()+ },+ tx,+ );++ assert_eq!(view.side_layout_width(80), None);+ }++ #[test]+ fn stacked_side_content_is_used_when_side_by_side_does_not_fit() {+ let (tx_raw, _rx) = unbounded_channel::<AppEvent>();+ let tx = AppEventSender::new(tx_raw);+ let view = ListSelectionView::new(+ SelectionViewParams {+ title: Some("Debug".to_string()),+ items: vec![SelectionItem {+ name: "Item 1".to_string(),+ dismiss_on_select: true,+ ..Default::default()+ }],+ side_content: Box::new(MarkerRenderable {+ marker: "W",+ height: 1,+ }),+ stacked_side_content: Some(Box::new(MarkerRenderable {+ marker: "N",+ height: 1,+ })),+ side_content_width: SideContentWidth::Half,+ side_content_min_width: 60,+ ..Default::default()+ },+ tx,+ );++ let rendered = render_lines_with_width(&view, 70);+ assert!(+ rendered.contains('N'),+ "expected stacked marker to be rendered:\n{rendered}"+ );+ assert!(+ !rendered.contains('W'),+ "wide marker should not render in stacked mode:\n{rendered}"+ );+ }++ #[test]+ fn side_content_clearing_resets_symbols_and_style() {+ let (tx_raw, _rx) = unbounded_channel::<AppEvent>();+ let tx = AppEventSender::new(tx_raw);+ let view = ListSelectionView::new(+ SelectionViewParams {+ title: Some("Debug".to_string()),+ items: vec![SelectionItem {+ name: "Item 1".to_string(),+ dismiss_on_select: true,+ ..Default::default()+ }],+ side_content: Box::new(MarkerRenderable {+ marker: "W",+ height: 1,+ }),+ side_content_width: SideContentWidth::Half,+ side_content_min_width: 10,+ ..Default::default()+ },+ tx,+ );++ let width = 120;+ let height = view.desired_height(width);+ let area = Rect::new(0, 0, width, height);+ let mut buf = Buffer::empty(area);+ for y in 0..height {+ for x in 0..width {+ buf[(x, y)]+ .set_symbol("X")+ .set_style(Style::default().bg(Color::Red));+ }+ }+ view.render(area, &mut buf);++ let cell = &buf[(width - 1, 0)];+ assert_eq!(cell.symbol(), " ");+ let style = cell.style();+ assert_eq!(style.fg, Some(Color::Reset));+ assert_eq!(style.bg, Some(Color::Reset));+ assert_eq!(style.underline_color, Some(Color::Reset));++ let mut saw_marker = false;+ for y in 0..height {+ for x in 0..width {+ let cell = &buf[(x, y)];+ if cell.symbol() == "W" {+ saw_marker = true;+ assert_eq!(cell.style().bg, Some(Color::Reset));+ }+ }+ }+ assert!(+ saw_marker,+ "expected side marker renderable to draw into buffer"+ );+ }++ #[test]+ fn side_content_clearing_handles_non_zero_buffer_origin() {+ let (tx_raw, _rx) = unbounded_channel::<AppEvent>();+ let tx = AppEventSender::new(tx_raw);+ let view = ListSelectionView::new(+ SelectionViewParams {+ title: Some("Debug".to_string()),+ items: vec![SelectionItem {+ name: "Item 1".to_string(),+ dismiss_on_select: true,+ ..Default::default()+ }],+ side_content: Box::new(MarkerRenderable {+ marker: "W",+ height: 1,+ }),+ side_content_width: SideContentWidth::Half,+ side_content_min_width: 10,+ ..Default::default()+ },+ tx,+ );++ let width = 120;+ let height = view.desired_height(width);+ let area = Rect::new(0, 20, width, height);+ let mut buf = Buffer::empty(area);+ for y in area.y..area.y + height {+ for x in area.x..area.x + width {+ buf[(x, y)]+ .set_symbol("X")+ .set_style(Style::default().bg(Color::Red));+ }+ }+ view.render(area, &mut buf);++ let cell = &buf[(area.x + width - 1, area.y)];+ assert_eq!(cell.symbol(), " ");+ assert_eq!(cell.style().bg, Some(Color::Reset));+ }}diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rsindex 234bb8b728..9c7b940f0e 100644--- a/codex-rs/tui/src/bottom_pane/mod.rs+++ b/codex-rs/tui/src/bottom_pane/mod.rs@@ -78,6 +78,9 @@ mod slash_commands;pub(crate) use footer::CollaborationModeIndicator;pub(crate) use list_selection_view::ColumnWidthMode;pub(crate) use list_selection_view::SelectionViewParams;+pub(crate) use list_selection_view::SideContentWidth;+pub(crate) use list_selection_view::popup_content_width;+pub(crate) use list_selection_view::side_by_side_layout_widths;mod feedback_view;pub(crate) use feedback_view::FeedbackAudience;pub(crate) use feedback_view::feedback_disabled_params;diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rsindex 9bfddd18e4..ba7013c3c1 100644--- a/codex-rs/tui/src/chatwidget.rs+++ b/codex-rs/tui/src/chatwidget.rs@@ -3482,6 +3482,9 @@ impl ChatWidget {SlashCommand::Statusline => {self.open_status_line_setup();}+ SlashCommand::Theme => {+ self.open_theme_picker();+ }SlashCommand::Ps => {self.add_ps_output();}@@ -4431,6 +4434,20 @@ impl ChatWidget {self.bottom_pane.show_view(Box::new(view));}+ fn open_theme_picker(&mut self) {+ let codex_home = codex_core::config::find_codex_home().ok();+ let terminal_width = self+ .last_rendered_width+ .get()+ .and_then(|width| u16::try_from(width).ok());+ let params = crate::theme_picker::build_theme_picker_params(+ self.config.tui_theme.as_deref(),+ codex_home.as_deref(),+ terminal_width,+ );+ self.bottom_pane.show_selection_view(params);+ }+/// Parses configured status-line ids into known items and collects unknown ids.////// Unknown ids are deduplicated in insertion order for warning messages.@@ -6338,6 +6355,11 @@ impl ChatWidget {self.config.personality = Some(personality);}+ /// Set the syntax theme override in the widget's config copy.+ pub(crate) fn set_tui_theme(&mut self, theme: Option<String>) {+ self.config.tui_theme = theme;+ }+/// Set the model in the widget's config copy and stored collaboration mode.pub(crate) fn set_model(&mut self, model: &str) {self.current_collaboration_mode =diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_modal_exec.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_modal_exec.snapindex 1c6a3ef136..055a6292f1 100644--- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_modal_exec.snap+++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_modal_exec.snap@@ -27,6 +27,9 @@ Buffer {x: 73, y: 4, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,x: 2, y: 5, fg: Reset, bg: Reset, underline: Reset, modifier: ITALIC,x: 7, y: 5, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,+ x: 4, y: 7, fg: Rgb(137, 180, 250), bg: Reset, underline: Reset, modifier: NONE,+ x: 8, y: 7, fg: Rgb(205, 214, 244), bg: Reset, underline: Reset, modifier: NONE,+ x: 20, y: 7, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,x: 0, y: 9, fg: Cyan, bg: Reset, underline: Reset, modifier: BOLD,x: 21, y: 9, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,x: 48, y: 10, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,diff --git a/codex-rs/tui/src/diff_render.rs b/codex-rs/tui/src/diff_render.rsindex 6fdf3a43f5..aa0481d044 100644--- a/codex-rs/tui/src/diff_render.rs+++ b/codex-rs/tui/src/diff_render.rs@@ -1,3 +1,23 @@+//! Renders unified diffs with line numbers, gutter signs, and optional syntax+//! highlighting.+//!+//! Each `FileChange` variant (Add / Delete / Update) is rendered as a block of+//! diff lines, each prefixed by a right-aligned line number, a gutter sign+//! (`+` / `-` / ` `), and the content text. When a recognized file extension+//! is present, the content text is syntax-highlighted using+//! [`crate::render::highlight`].+//!+//! **Highlighting strategy for `Update` diffs:** the renderer highlights each+//! hunk as a single concatenated block rather than line-by-line. This+//! preserves syntect's parser state across consecutive lines within a hunk+//! (important for multi-line strings, block comments, etc.). Cross-hunk state+//! is intentionally *not* preserved because hunks are visually separated and+//! re-synchronize at context boundaries anyway.+//!+//! **Wrapping:** long lines are hard-wrapped at the available column width.+//! Syntax-highlighted spans are split at character boundaries with styles+//! preserved across the split so that no color information is lost.+use diffy::Hunk;use ratatui::buffer::Buffer;use ratatui::layout::Rect;@@ -12,8 +32,15 @@ use std::collections::HashMap;use std::path::Path;use std::path::PathBuf;+use unicode_width::UnicodeWidthChar;++/// Display width of a tab character in columns.+const TAB_WIDTH: usize = 4;+use crate::exec_command::relativize_to_home;use crate::render::Insets;+use crate::render::highlight::exceeds_highlight_limits;+use crate::render::highlight::highlight_code_to_styled_spans;use crate::render::line_utils::prefix_lines;use crate::render::renderable::ColumnRenderable;use crate::render::renderable::InsetRenderable;@@ -21,8 +48,13 @@ use crate::render::renderable::Renderable;use codex_core::git_info::get_git_repo_root;use codex_protocol::protocol::FileChange;-// Internal representation for diff line rendering-enum DiffLineType {+/// Classifies a diff line for gutter sign rendering and style selection.+///+/// `Insert` renders with a `+` sign and green text, `Delete` with `-` and red+/// text (plus dim overlay when syntax-highlighted), and `Context` with a space+/// and default styling.+#[derive(Clone, Copy)]+pub(crate) enum DiffLineType {Insert,Delete,Context,@@ -42,13 +74,13 @@ impl DiffSummary {impl Renderable for FileChange {fn render(&self, area: Rect, buf: &mut Buffer) {let mut lines = vec![];- render_change(self, &mut lines, area.width as usize);+ render_change(self, &mut lines, area.width as usize, None);Paragraph::new(lines).render(area, buf);}fn desired_height(&self, width: u16) -> u16 {let mut lines = vec![];- render_change(self, &mut lines, width as usize);+ render_change(self, &mut lines, width as usize, None);lines.len() as u16}}@@ -185,47 +217,100 @@ fn render_changes_block(rows: Vec<Row>, wrap_cols: usize, cwd: &Path) -> Vec<RtLout.push(RtLine::from(header));}+ // For renames, use the destination extension for highlighting — the+ // diff content reflects the new file, not the old one.+ let lang_path = r.move_path.as_deref().unwrap_or(&r.path);+ let lang = detect_lang_for_path(lang_path);let mut lines = vec![];- render_change(&r.change, &mut lines, wrap_cols - 4);+ render_change(&r.change, &mut lines, wrap_cols - 4, lang.as_deref());out.extend(prefix_lines(lines, " ".into(), " ".into()));}out}-fn render_change(change: &FileChange, out: &mut Vec<RtLine<'static>>, width: usize) {+/// Detect the programming language for a file path by its extension.+/// Returns the raw extension string for `normalize_lang` / `find_syntax`+/// to resolve downstream.+fn detect_lang_for_path(path: &Path) -> Option<String> {+ let ext = path.extension()?.to_str()?;+ Some(ext.to_string())+}++fn render_change(+ change: &FileChange,+ out: &mut Vec<RtLine<'static>>,+ width: usize,+ lang: Option<&str>,+) {match change {FileChange::Add { content } => {+ // Pre-highlight the entire file content as a whole.+ let syntax_lines = lang.and_then(|l| highlight_code_to_styled_spans(content, l));let line_number_width = line_number_width(content.lines().count());for (i, raw) in content.lines().enumerate() {- out.extend(push_wrapped_diff_line(- i + 1,- DiffLineType::Insert,- raw,- width,- line_number_width,- ));+ let syn = syntax_lines.as_ref().and_then(|sl| sl.get(i));+ if let Some(spans) = syn {+ out.extend(push_wrapped_diff_line_with_syntax(+ i + 1,+ DiffLineType::Insert,+ raw,+ width,+ line_number_width,+ spans,+ ));+ } else {+ out.extend(push_wrapped_diff_line(+ i + 1,+ DiffLineType::Insert,+ raw,+ width,+ line_number_width,+ ));+ }}}FileChange::Delete { content } => {+ let syntax_lines = lang.and_then(|l| highlight_code_to_styled_spans(content, l));let line_number_width = line_number_width(content.lines().count());for (i, raw) in content.lines().enumerate() {- out.extend(push_wrapped_diff_line(- i + 1,- DiffLineType::Delete,- raw,- width,- line_number_width,- ));+ let syn = syntax_lines.as_ref().and_then(|sl| sl.get(i));+ if let Some(spans) = syn {+ out.extend(push_wrapped_diff_line_with_syntax(+ i + 1,+ DiffLineType::Delete,+ raw,+ width,+ line_number_width,+ spans,+ ));+ } else {+ out.extend(push_wrapped_diff_line(+ i + 1,+ DiffLineType::Delete,+ raw,+ width,+ line_number_width,+ ));+ }}}FileChange::Update { unified_diff, .. } => {if let Ok(patch) = diffy::Patch::from_str(unified_diff) {let mut max_line_number = 0;+ let mut total_diff_bytes: usize = 0;+ let mut total_diff_lines: usize = 0;for h in patch.hunks() {let mut old_ln = h.old_range().start();let mut new_ln = h.new_range().start();for l in h.lines() {+ let text = match l {+ diffy::Line::Insert(t)+ | diffy::Line::Delete(t)+ | diffy::Line::Context(t) => t,+ };+ total_diff_bytes += text.len();+ total_diff_lines += 1;match l {diffy::Line::Insert(_) => {max_line_number = max_line_number.max(new_ln);@@ -243,6 +328,16 @@ fn render_change(change: &FileChange, out: &mut Vec<RtLine<'static>>, width: usi}}}++ // Skip per-line syntax highlighting when the patch is too+ // large — avoids thousands of parser initializations that+ // would stall rendering on big diffs.+ let diff_lang = if exceeds_highlight_limits(total_diff_bytes, total_diff_lines) {+ None+ } else {+ lang+ };+let line_number_width = line_number_width(max_line_number);let mut is_first_hunk = true;for h in patch.hunks() {@@ -253,41 +348,93 @@ fn render_change(change: &FileChange, out: &mut Vec<RtLine<'static>>, width: usi}is_first_hunk = false;+ // Highlight each hunk as a single block so syntect parser+ // state is preserved across consecutive lines.+ let hunk_syntax_lines = diff_lang.and_then(|language| {+ let hunk_text: String = h+ .lines()+ .iter()+ .map(|line| match line {+ diffy::Line::Insert(text)+ | diffy::Line::Delete(text)+ | diffy::Line::Context(text) => *text,+ })+ .collect();+ let syntax_lines = highlight_code_to_styled_spans(&hunk_text, language)?;+ (syntax_lines.len() == h.lines().len()).then_some(syntax_lines)+ });+let mut old_ln = h.old_range().start();let mut new_ln = h.new_range().start();- for l in h.lines() {+ for (line_idx, l) in h.lines().iter().enumerate() {+ let syntax_spans = hunk_syntax_lines+ .as_ref()+ .and_then(|syntax_lines| syntax_lines.get(line_idx));match l {diffy::Line::Insert(text) => {let s = text.trim_end_matches('\n');- out.extend(push_wrapped_diff_line(- new_ln,- DiffLineType::Insert,- s,- width,- line_number_width,- ));+ if let Some(syn) = syntax_spans {+ out.extend(push_wrapped_diff_line_with_syntax(+ new_ln,+ DiffLineType::Insert,+ s,+ width,+ line_number_width,+ syn,+ ));+ } else {+ out.extend(push_wrapped_diff_line(+ new_ln,+ DiffLineType::Insert,+ s,+ width,+ line_number_width,+ ));+ }new_ln += 1;}diffy::Line::Delete(text) => {let s = text.trim_end_matches('\n');- out.extend(push_wrapped_diff_line(- old_ln,- DiffLineType::Delete,- s,- width,- line_number_width,- ));+ if let Some(syn) = syntax_spans {+ out.extend(push_wrapped_diff_line_with_syntax(+ old_ln,+ DiffLineType::Delete,+ s,+ width,+ line_number_width,+ syn,+ ));+ } else {+ out.extend(push_wrapped_diff_line(+ old_ln,+ DiffLineType::Delete,+ s,+ width,+ line_number_width,+ ));+ }old_ln += 1;}diffy::Line::Context(text) => {let s = text.trim_end_matches('\n');- out.extend(push_wrapped_diff_line(- new_ln,- DiffLineType::Context,- s,- width,- line_number_width,- ));+ if let Some(syn) = syntax_spans {+ out.extend(push_wrapped_diff_line_with_syntax(+ new_ln,+ DiffLineType::Context,+ s,+ width,+ line_number_width,+ syn,+ ));+ } else {+ out.extend(push_wrapped_diff_line(+ new_ln,+ DiffLineType::Context,+ s,+ width,+ line_number_width,+ ));+ }old_ln += 1;new_ln += 1;}@@ -342,68 +489,213 @@ pub(crate) fn calculate_add_remove_from_diff(diff: &str) -> (usize, usize) {}}-fn push_wrapped_diff_line(+/// Render a single diff line (no syntax highlighting) as one or more wrapped+/// ratatui `Line`s. The first output line carries the gutter sign; continuation+/// lines are indented under the line number column.+pub(crate) fn push_wrapped_diff_line(+ line_number: usize,+ kind: DiffLineType,+ text: &str,+ width: usize,+ line_number_width: usize,+) -> Vec<RtLine<'static>> {+ push_wrapped_diff_line_inner(line_number, kind, text, width, line_number_width, None)+}++/// Render a single diff line with pre-computed syntax spans. The sign character+/// uses the diff color; content gets syntax colors with a dim overlay for delete+/// lines.+pub(crate) fn push_wrapped_diff_line_with_syntax(+ line_number: usize,+ kind: DiffLineType,+ text: &str,+ width: usize,+ line_number_width: usize,+ syntax_spans: &[RtSpan<'static>],+) -> Vec<RtLine<'static>> {+ push_wrapped_diff_line_inner(+ line_number,+ kind,+ text,+ width,+ line_number_width,+ Some(syntax_spans),+ )+}++fn push_wrapped_diff_line_inner(line_number: usize,kind: DiffLineType,text: &str,width: usize,line_number_width: usize,+ syntax_spans: Option<&[RtSpan<'static>]>,) -> Vec<RtLine<'static>> {let ln_str = line_number.to_string();- let mut remaining_text: &str = text;// Reserve a fixed number of spaces (equal to the widest line number plus a// trailing spacer) so the sign column stays aligned across the diff block.let gutter_width = line_number_width.max(1);let prefix_cols = gutter_width + 1;- let mut first = true;let (sign_char, line_style) = match kind {DiffLineType::Insert => ('+', style_add()),DiffLineType::Delete => ('-', style_del()),DiffLineType::Context => (' ', style_context()),};- let mut lines: Vec<RtLine<'static>> = Vec::new();- loop {- // Fit the content for the current terminal row:- // compute how many columns are available after the prefix, then split- // at a UTF-8 character boundary so this row's chunk fits exactly.+ // When we have syntax spans, compose them with the diff style for a richer+ // view. The sign character keeps the diff color; content gets syntax colors+ // with an overlay modifier for delete lines (dim).+ if let Some(syn_spans) = syntax_spans {+ let gutter = format!("{ln_str:>gutter_width$} ");+ let sign = format!("{sign_char}");+ let dim_overlay = matches!(kind, DiffLineType::Delete);++ // Apply dim overlay to syntax spans if this is a delete line.+ let styled: Vec<RtSpan<'static>> = syn_spans+ .iter()+ .map(|sp| {+ let mut style = sp.style;+ if dim_overlay {+ style.add_modifier |= Modifier::DIM;+ }+ RtSpan::styled(sp.content.clone().into_owned(), style)+ })+ .collect();++ // Determine how many display columns remain for content after the+ // gutter and sign character.let available_content_cols = width.saturating_sub(prefix_cols + 1).max(1);- let split_at_byte_index = remaining_text- .char_indices()- .nth(available_content_cols)- .map(|(i, _)| i)- .unwrap_or_else(|| remaining_text.len());- let (chunk, rest) = remaining_text.split_at(split_at_byte_index);- remaining_text = rest;-- if first {- // Build gutter (right-aligned line number plus spacer) as a dimmed span++ // Wrap the styled content spans to fit within the available columns.+ let wrapped_chunks = wrap_styled_spans(&styled, available_content_cols);++ let mut lines: Vec<RtLine<'static>> = Vec::new();+ for (i, chunk) in wrapped_chunks.into_iter().enumerate() {+ let mut row_spans: Vec<RtSpan<'static>> = Vec::new();+ if i == 0 {+ // First line: gutter + sign + content+ row_spans.push(RtSpan::styled(gutter.clone(), style_gutter()));+ row_spans.push(RtSpan::styled(sign.clone(), line_style));+ } else {+ // Continuation: empty gutter + two-space indent (matches+ // the plain-text wrapping continuation style).+ let cont_gutter = format!("{:gutter_width$} ", "");+ row_spans.push(RtSpan::styled(cont_gutter, style_gutter()));+ }+ row_spans.extend(chunk);+ lines.push(RtLine::from(row_spans));+ }+ return lines;+ }++ let available_content_cols = width.saturating_sub(prefix_cols + 1).max(1);+ let styled = vec![RtSpan::styled(text.to_string(), line_style)];+ let wrapped_chunks = wrap_styled_spans(&styled, available_content_cols);++ let mut lines: Vec<RtLine<'static>> = Vec::new();+ for (i, chunk) in wrapped_chunks.into_iter().enumerate() {+ let mut row_spans: Vec<RtSpan<'static>> = Vec::new();+ if i == 0 {let gutter = format!("{ln_str:>gutter_width$} ");- // Content with a sign ('+'/'-'/' ') styled per diff kind- let content = format!("{sign_char}{chunk}");- lines.push(RtLine::from(vec![- RtSpan::styled(gutter, style_gutter()),- RtSpan::styled(content, line_style),- ]));- first = false;+ let sign = format!("{sign_char}");+ row_spans.push(RtSpan::styled(gutter, style_gutter()));+ row_spans.push(RtSpan::styled(sign, line_style));} else {- // Continuation lines keep a space for the sign column so content aligns- let gutter = format!("{:gutter_width$} ", "");- lines.push(RtLine::from(vec![- RtSpan::styled(gutter, style_gutter()),- RtSpan::styled(chunk.to_string(), line_style),- ]));- }- if remaining_text.is_empty() {- break;+ let cont_gutter = format!("{:gutter_width$} ", "");+ row_spans.push(RtSpan::styled(cont_gutter, style_gutter()));}+ row_spans.extend(chunk);+ lines.push(RtLine::from(row_spans));}+lines}-fn line_number_width(max_line_number: usize) -> usize {+/// Split styled spans into chunks that fit within `max_cols` display columns.+///+/// Returns one `Vec<RtSpan>` per output line. Styles are preserved across+/// split boundaries so that wrapping never loses syntax coloring.+///+/// The algorithm walks characters using their Unicode display width (with tabs+/// expanded to [`TAB_WIDTH`] columns). When a character would overflow the+/// current line, the accumulated text is flushed and a new line begins. A+/// single character wider than the remaining space forces a line break *before*+/// the character so that progress is always made (avoiding infinite loops on+/// CJK characters or tabs at the end of a line).+fn wrap_styled_spans(spans: &[RtSpan<'static>], max_cols: usize) -> Vec<Vec<RtSpan<'static>>> {+ let mut result: Vec<Vec<RtSpan<'static>>> = Vec::new();+ let mut current_line: Vec<RtSpan<'static>> = Vec::new();+ let mut col: usize = 0;++ for span in spans {+ let style = span.style;+ let text = span.content.as_ref();+ let mut remaining = text;++ while !remaining.is_empty() {+ // Accumulate characters until we fill the line.+ let mut byte_end = 0;+ let mut chars_col = 0;++ for ch in remaining.chars() {+ // Tabs have no Unicode width; treat them as TAB_WIDTH columns.+ let w = ch.width().unwrap_or(if ch == '\t' { TAB_WIDTH } else { 0 });+ if col + chars_col + w > max_cols {+ // Adding this character would exceed the line width.+ // Break here; if this is the first character in `remaining`+ // we will flush/start a new line in the `byte_end == 0`+ // branch below before consuming it.+ break;+ }+ byte_end += ch.len_utf8();+ chars_col += w;+ }++ if byte_end == 0 {+ // Single character wider than remaining space — force onto a+ // new line so we make progress.+ if !current_line.is_empty() {+ result.push(std::mem::take(&mut current_line));+ }+ // Take at least one character to avoid an infinite loop.+ let Some(ch) = remaining.chars().next() else {+ break;+ };+ let ch_len = ch.len_utf8();+ current_line.push(RtSpan::styled(remaining[..ch_len].to_string(), style));+ // Use fallback width 1 (not 0) so this branch always advances+ // even if `ch` has unknown/zero display width.+ col = ch.width().unwrap_or(if ch == '\t' { TAB_WIDTH } else { 1 });+ remaining = &remaining[ch_len..];+ continue;+ }++ let (chunk, rest) = remaining.split_at(byte_end);+ current_line.push(RtSpan::styled(chunk.to_string(), style));+ col += chars_col;+ remaining = rest;++ // If we exactly filled or exceeded the line, start a new one.+ // Do not gate on !remaining.is_empty() — the next span in the+ // outer loop may still have content that must start on a fresh line.+ if col >= max_cols {+ result.push(std::mem::take(&mut current_line));+ col = 0;+ }+ }+ }++ // Push the last line (always at least one, even if empty).+ if !current_line.is_empty() || result.is_empty() {+ result.push(current_line);+ }++ result+}++pub(crate) fn line_number_width(max_line_number: usize) -> usize {if max_line_number == 0 {1} else {@@ -454,6 +746,19 @@ mod tests {assert_snapshot!(name, terminal.backend());}+ fn display_width(text: &str) -> usize {+ text.chars()+ .map(|ch| ch.width().unwrap_or(if ch == '\t' { TAB_WIDTH } else { 0 }))+ .sum()+ }++ fn line_display_width(line: &RtLine<'static>) -> usize {+ line.spans+ .iter()+ .map(|span| display_width(span.content.as_ref()))+ .sum()+ }+fn snapshot_lines_text(name: &str, lines: &[RtLine<'static>]) {// Convert Lines to plain text rows and trim trailing spaces so it's// easier to validate indentation visually in snapshots.@@ -471,6 +776,71 @@ mod tests {assert_snapshot!(name, text);}+ fn diff_gallery_changes() -> HashMap<PathBuf, FileChange> {+ let mut changes: HashMap<PathBuf, FileChange> = HashMap::new();++ let rust_original =+ "fn greet(name: &str) {\n println!(\"hello\");\n println!(\"bye\");\n}\n";+ let rust_modified = "fn greet(name: &str) {\n println!(\"hello {name}\");\n println!(\"emoji: 🚀✨ and CJK: 你好世界\");\n}\n";+ let rust_patch = diffy::create_patch(rust_original, rust_modified).to_string();+ changes.insert(+ PathBuf::from("src/lib.rs"),+ FileChange::Update {+ unified_diff: rust_patch,+ move_path: None,+ },+ );++ let py_original = "def add(a, b):\n\treturn a + b\n\nprint(add(1, 2))\n";+ let py_modified = "def add(a, b):\n\treturn a + b + 42\n\nprint(add(1, 2))\n";+ let py_patch = diffy::create_patch(py_original, py_modified).to_string();+ changes.insert(+ PathBuf::from("scripts/calc.txt"),+ FileChange::Update {+ unified_diff: py_patch,+ move_path: Some(PathBuf::from("scripts/calc.py")),+ },+ );++ changes.insert(+ PathBuf::from("assets/banner.txt"),+ FileChange::Add {+ content: "HEADER\tVALUE\nrocket\t🚀\ncity\t東京\n".to_string(),+ },+ );+ changes.insert(+ PathBuf::from("examples/new_sample.rs"),+ FileChange::Add {+ content: "pub fn greet(name: &str) {\n println!(\"Hello, {name}!\");\n}\n"+ .to_string(),+ },+ );++ changes.insert(+ PathBuf::from("tmp/obsolete.log"),+ FileChange::Delete {+ content: "old line 1\nold line 2\nold line 3\n".to_string(),+ },+ );+ changes.insert(+ PathBuf::from("legacy/old_script.py"),+ FileChange::Delete {+ content: "def legacy(x):\n return x + 1\nprint(legacy(3))\n".to_string(),+ },+ );++ changes+ }++ fn snapshot_diff_gallery(name: &str, width: u16, height: u16) {+ let lines = create_diff_summary(+ &diff_gallery_changes(),+ &PathBuf::from("/"),+ usize::from(width),+ );+ snapshot_lines(name, lines, width, height);+ }+#[test]fn display_path_prefers_cwd_without_git_repo() {let cwd = if cfg!(windows) {@@ -694,4 +1064,367 @@ mod tests {snapshot_lines("apply_update_block_relativizes_path", lines, 80, 10);}++ #[test]+ fn ui_snapshot_syntax_highlighted_insert_wraps() {+ // A long Rust line that exceeds 80 cols with syntax highlighting should+ // wrap to multiple output lines rather than being clipped.+ let long_rust = "fn very_long_function_name(arg_one: String, arg_two: String, arg_three: String, arg_four: String) -> Result<String, Box<dyn std::error::Error>> { Ok(arg_one) }";++ let syntax_spans =+ highlight_code_to_styled_spans(long_rust, "rust").expect("rust highlighting");+ let spans = &syntax_spans[0];++ let lines = push_wrapped_diff_line_with_syntax(+ 1,+ DiffLineType::Insert,+ long_rust,+ 80,+ line_number_width(1),+ spans,+ );++ assert!(+ lines.len() > 1,+ "syntax-highlighted long line should wrap to multiple lines, got {}",+ lines.len()+ );++ snapshot_lines("syntax_highlighted_insert_wraps", lines, 90, 10);+ }++ #[test]+ fn ui_snapshot_syntax_highlighted_insert_wraps_text() {+ let long_rust = "fn very_long_function_name(arg_one: String, arg_two: String, arg_three: String, arg_four: String) -> Result<String, Box<dyn std::error::Error>> { Ok(arg_one) }";++ let syntax_spans =+ highlight_code_to_styled_spans(long_rust, "rust").expect("rust highlighting");+ let spans = &syntax_spans[0];++ let lines = push_wrapped_diff_line_with_syntax(+ 1,+ DiffLineType::Insert,+ long_rust,+ 80,+ line_number_width(1),+ spans,+ );++ snapshot_lines_text("syntax_highlighted_insert_wraps_text", &lines);+ }++ #[test]+ fn ui_snapshot_diff_gallery_80x24() {+ snapshot_diff_gallery("diff_gallery_80x24", 80, 24);+ }++ #[test]+ fn ui_snapshot_diff_gallery_94x35() {+ snapshot_diff_gallery("diff_gallery_94x35", 94, 35);+ }++ #[test]+ fn ui_snapshot_diff_gallery_120x40() {+ snapshot_diff_gallery("diff_gallery_120x40", 120, 40);+ }++ #[test]+ fn add_diff_uses_path_extension_for_highlighting() {+ let mut changes: HashMap<PathBuf, FileChange> = HashMap::new();+ changes.insert(+ PathBuf::from("highlight_add.rs"),+ FileChange::Add {+ content: "pub fn sum(a: i32, b: i32) -> i32 { a + b }\n".to_string(),+ },+ );++ let lines = create_diff_summary(&changes, &PathBuf::from("/"), 80);+ let has_rgb = lines.iter().any(|line| {+ line.spans+ .iter()+ .any(|s| matches!(s.style.fg, Some(ratatui::style::Color::Rgb(..))))+ });+ assert!(+ has_rgb,+ "add diff for .rs file should produce syntax-highlighted (RGB) spans"+ );+ }++ #[test]+ fn delete_diff_uses_path_extension_for_highlighting() {+ let mut changes: HashMap<PathBuf, FileChange> = HashMap::new();+ changes.insert(+ PathBuf::from("highlight_delete.py"),+ FileChange::Delete {+ content: "def scale(x):\n return x * 2\n".to_string(),+ },+ );++ let lines = create_diff_summary(&changes, &PathBuf::from("/"), 80);+ let has_rgb = lines.iter().any(|line| {+ line.spans+ .iter()+ .any(|s| matches!(s.style.fg, Some(ratatui::style::Color::Rgb(..))))+ });+ assert!(+ has_rgb,+ "delete diff for .py file should produce syntax-highlighted (RGB) spans"+ );+ }++ #[test]+ fn detect_lang_for_common_paths() {+ // Standard extensions are detected.+ assert!(detect_lang_for_path(Path::new("foo.rs")).is_some());+ assert!(detect_lang_for_path(Path::new("bar.py")).is_some());+ assert!(detect_lang_for_path(Path::new("app.tsx")).is_some());++ // Extensionless files return None.+ assert!(detect_lang_for_path(Path::new("Makefile")).is_none());+ assert!(detect_lang_for_path(Path::new("randomfile")).is_none());+ }++ #[test]+ fn wrap_styled_spans_single_line() {+ // Content that fits in one line should produce exactly one chunk.+ let spans = vec![RtSpan::raw("short")];+ let result = wrap_styled_spans(&spans, 80);+ assert_eq!(result.len(), 1);+ }++ #[test]+ fn wrap_styled_spans_splits_long_content() {+ // Content wider than max_cols should produce multiple chunks.+ let long_text = "a".repeat(100);+ let spans = vec![RtSpan::raw(long_text)];+ let result = wrap_styled_spans(&spans, 40);+ assert!(+ result.len() >= 3,+ "100 chars at 40 cols should produce at least 3 lines, got {}",+ result.len()+ );+ }++ #[test]+ fn wrap_styled_spans_flushes_at_span_boundary() {+ // When span A fills exactly to max_cols and span B follows, the line+ // must be flushed before B starts. Otherwise B's first character lands+ // on an already-full line, producing over-width output.+ let style_a = Style::default().fg(Color::Red);+ let style_b = Style::default().fg(Color::Blue);+ let spans = vec![+ RtSpan::styled("aaaa", style_a), // 4 cols, fills line exactly at max_cols=4+ RtSpan::styled("bb", style_b), // should start on a new line+ ];+ let result = wrap_styled_spans(&spans, 4);+ assert_eq!(+ result.len(),+ 2,+ "span ending exactly at max_cols should flush before next span: {result:?}"+ );+ // First line should only contain the 'a' span.+ let first_width: usize = result[0].iter().map(|s| s.content.chars().count()).sum();+ assert!(+ first_width <= 4,+ "first line should be at most 4 cols wide, got {first_width}"+ );+ }++ #[test]+ fn wrap_styled_spans_preserves_styles() {+ // Verify that styles survive split boundaries.+ let style = Style::default().fg(Color::Green);+ let text = "x".repeat(50);+ let spans = vec![RtSpan::styled(text, style)];+ let result = wrap_styled_spans(&spans, 20);+ for chunk in &result {+ for span in chunk {+ assert_eq!(span.style, style, "style should be preserved across wraps");+ }+ }+ }++ #[test]+ fn wrap_styled_spans_tabs_have_visible_width() {+ // A tab should count as TAB_WIDTH columns, not zero.+ // With max_cols=8, a tab (4 cols) + "abcde" (5 cols) = 9 cols → must wrap.+ let spans = vec![RtSpan::raw("\tabcde")];+ let result = wrap_styled_spans(&spans, 8);+ assert!(+ result.len() >= 2,+ "tab + 5 chars should exceed 8 cols and wrap, got {} line(s): {result:?}",+ result.len()+ );+ }++ #[test]+ fn wrap_styled_spans_wraps_before_first_overflowing_char() {+ let spans = vec![RtSpan::raw("abcd\t界")];+ let result = wrap_styled_spans(&spans, 5);++ let line_text: Vec<String> = result+ .iter()+ .map(|line| {+ line.iter()+ .map(|span| span.content.as_ref())+ .collect::<String>()+ })+ .collect();+ assert_eq!(line_text, vec!["abcd", "\t", "界"]);++ let line_width = |line: &[RtSpan<'static>]| -> usize {+ line.iter()+ .flat_map(|span| span.content.chars())+ .map(|ch| ch.width().unwrap_or(if ch == '\t' { TAB_WIDTH } else { 0 }))+ .sum()+ };+ for line in &result {+ assert!(+ line_width(line) <= 5,+ "wrapped line exceeded width 5: {line:?}"+ );+ }+ }++ #[test]+ fn fallback_wrapping_uses_display_width_for_tabs_and_wide_chars() {+ let width = 8;+ let lines = push_wrapped_diff_line(+ 1,+ DiffLineType::Insert,+ "abcd\t界🙂",+ width,+ line_number_width(1),+ );++ assert!(lines.len() >= 2, "expected wrapped output, got {lines:?}");+ for line in &lines {+ assert!(+ line_display_width(line) <= width,+ "fallback wrapped line exceeded width {width}: {line:?}"+ );+ }+ }++ #[test]+ fn large_update_diff_skips_highlighting() {+ // Build a patch large enough to exceed MAX_HIGHLIGHT_LINES (10_000).+ // Without the pre-check this would attempt 10k+ parser initializations.+ let line_count = 10_500;+ let original: String = (0..line_count).map(|i| format!("line {i}\n")).collect();+ let modified: String = (0..line_count)+ .map(|i| {+ if i % 2 == 0 {+ format!("line {i} changed\n")+ } else {+ format!("line {i}\n")+ }+ })+ .collect();+ let patch = diffy::create_patch(&original, &modified).to_string();++ let mut changes: HashMap<PathBuf, FileChange> = HashMap::new();+ changes.insert(+ PathBuf::from("huge.rs"),+ FileChange::Update {+ unified_diff: patch,+ move_path: None,+ },+ );++ // Should complete quickly (no per-line parser init). If guardrails+ // are bypassed this would be extremely slow.+ let lines = create_diff_summary(&changes, &PathBuf::from("/"), 80);++ // The diff rendered without timing out — the guardrails prevented+ // thousands of per-line parser initializations. Verify we actually+ // got output (the patch is non-empty).+ assert!(+ lines.len() > 100,+ "expected many output lines from large diff, got {}",+ lines.len(),+ );++ // No span should contain an RGB foreground color (syntax themes+ // produce RGB; plain diff styles only use named Color variants).+ for line in &lines {+ for span in &line.spans {+ if let Some(ratatui::style::Color::Rgb(..)) = span.style.fg {+ panic!(+ "large diff should not have syntax-highlighted spans, \+ got RGB color in style {:?} for {:?}",+ span.style, span.content,+ );+ }+ }+ }+ }++ #[test]+ fn rename_diff_uses_destination_extension_for_highlighting() {+ // A rename from an unknown extension to .rs should highlight as Rust.+ // Without the fix, detect_lang_for_path uses the source path (.xyzzy),+ // which has no syntax definition, so highlighting is skipped.+ let original = "fn main() {}\n";+ let modified = "fn main() { println!(\"hi\"); }\n";+ let patch = diffy::create_patch(original, modified).to_string();++ let mut changes: HashMap<PathBuf, FileChange> = HashMap::new();+ changes.insert(+ PathBuf::from("foo.xyzzy"),+ FileChange::Update {+ unified_diff: patch,+ move_path: Some(PathBuf::from("foo.rs")),+ },+ );++ let lines = create_diff_summary(&changes, &PathBuf::from("/"), 80);+ let has_rgb = lines.iter().any(|line| {+ line.spans+ .iter()+ .any(|s| matches!(s.style.fg, Some(ratatui::style::Color::Rgb(..))))+ });+ assert!(+ has_rgb,+ "rename from .xyzzy to .rs should produce syntax-highlighted (RGB) spans"+ );+ }++ #[test]+ fn update_diff_preserves_multiline_highlight_state_within_hunk() {+ let original = "fn demo() {\n let s = \"hello\";\n}\n";+ let modified = "fn demo() {\n let s = \"hello\nworld\";\n}\n";+ let patch = diffy::create_patch(original, modified).to_string();++ let mut changes: HashMap<PathBuf, FileChange> = HashMap::new();+ changes.insert(+ PathBuf::from("demo.rs"),+ FileChange::Update {+ unified_diff: patch,+ move_path: None,+ },+ );++ let expected_multiline =+ highlight_code_to_styled_spans(" let s = \"hello\nworld\";\n", "rust")+ .expect("rust highlighting");+ let expected_style = expected_multiline+ .get(1)+ .and_then(|line| {+ line.iter()+ .find(|span| span.content.as_ref().contains("world"))+ })+ .map(|span| span.style)+ .expect("expected highlighted span for second multiline string line");++ let lines = create_diff_summary(&changes, &PathBuf::from("/"), 120);+ let actual_style = lines+ .iter()+ .flat_map(|line| line.spans.iter())+ .find(|span| span.content.as_ref().contains("world"))+ .map(|span| span.style)+ .expect("expected rendered diff span containing 'world'");++ assert_eq!(actual_style, expected_style);+ }}diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rsindex c44b5eb751..87d7089591 100644--- a/codex-rs/tui/src/lib.rs+++ b/codex-rs/tui/src/lib.rs@@ -105,6 +105,7 @@ mod streaming;mod style;mod terminal_palette;mod text_formatting;+mod theme_picker;mod tooltips;mod tui;mod ui_consts;@@ -545,6 +546,7 @@ async fn run_ratatui_app(} else {initial_config};+let mut missing_session_exit = |id_str: &str, action: &str| {error!("Error finding conversation path: {id_str}");restore();@@ -693,7 +695,7 @@ async fn run_ratatui_app(None => None,};- let config = match &session_selection {+ let mut config = match &session_selection {resume_picker::SessionSelection::Resume(_) | resume_picker::SessionSelection::Fork(_) => {load_config_or_exit_with_fallback_cwd(cli_kv_overrides.clone(),@@ -705,6 +707,17 @@ async fn run_ratatui_app(}_ => config,};++ // Configure syntax highlighting theme from the final config — onboarding+ // and resume/fork can both reload config with a different tui_theme, so+ // this must happen after the last possible reload.+ if let Some(w) = crate::render::highlight::set_theme_override(+ config.tui_theme.clone(),+ find_codex_home().ok(),+ ) {+ config.startup_warnings.push(w);+ }+set_default_client_residency_requirement(config.enforce_residency.value());let active_profile = config.active_profile.clone();let should_show_trust_screen = should_show_trust_screen(&config);@@ -1186,6 +1199,50 @@ trust_level = "untrusted"Ok(())}+ /// Regression: theme must be configured from the *final* config.+ ///+ /// `run_ratatui_app` can reload config during onboarding and again+ /// during session resume/fork. The syntax theme override (stored in+ /// a `OnceLock`) must use the final config's `tui_theme`, not the+ /// initial one — otherwise users resuming a thread in a project with+ /// a different theme get the wrong highlighting.+ ///+ /// We verify the invariant indirectly: `validate_theme_name` (the+ /// pure validation core of `set_theme_override`) must be called with+ /// the *final* config's theme, and its warning must land in the+ /// final config's `startup_warnings`.+ #[tokio::test]+ async fn theme_warning_uses_final_config() -> std::io::Result<()> {+ use crate::render::highlight::validate_theme_name;++ let temp_dir = TempDir::new()?;++ // initial_config has a valid theme — no warning.+ let initial_config = build_config(&temp_dir).await?;+ assert!(initial_config.tui_theme.is_none());++ // Simulate resume/fork reload: the final config has an invalid theme.+ let mut config = build_config(&temp_dir).await?;+ config.tui_theme = Some("bogus-theme".into());++ // Theme override must use the final config (not initial_config).+ // This mirrors the real call site in run_ratatui_app.+ if let Some(w) = validate_theme_name(config.tui_theme.as_deref(), Some(temp_dir.path())) {+ config.startup_warnings.push(w);+ }++ assert_eq!(+ config.startup_warnings.len(),+ 1,+ "warning from final config's invalid theme should be present"+ );+ assert!(+ config.startup_warnings[0].contains("bogus-theme"),+ "warning should reference the final config's theme name"+ );+ Ok(())+ }+#[tokio::test]async fn read_session_cwd_falls_back_to_session_meta() -> std::io::Result<()> {let temp_dir = TempDir::new()?;diff --git a/codex-rs/tui/src/markdown_render.rs b/codex-rs/tui/src/markdown_render.rsindex 35b0e8f5fe..ba8b47d5ed 100644--- a/codex-rs/tui/src/markdown_render.rs+++ b/codex-rs/tui/src/markdown_render.rs@@ -1,3 +1,4 @@+use crate::render::highlight::highlight_code_to_lines;use crate::render::line_utils::line_to_static;use crate::wrapping::RtOptions;use crate::wrapping::adaptive_wrap_line;@@ -99,6 +100,8 @@ wherepending_marker_line: bool,in_paragraph: bool,in_code_block: bool,+ code_block_lang: Option<String>,+ code_block_buffer: String,wrap_width: Option<usize>,current_line_content: Option<Line<'static>>,current_initial_indent: Vec<Span<'static>>,@@ -124,6 +127,8 @@ wherepending_marker_line: false,in_paragraph: false,in_code_block: false,+ code_block_lang: None,+ code_block_buffer: String::new(),wrap_width,current_line_content: None,current_initial_indent: Vec::new(),@@ -278,6 +283,16 @@ whereself.push_line(Line::default());}self.pending_marker_line = false;++ // When inside a fenced code block with a known language, accumulate+ // text into the buffer for batch highlighting in end_codeblock().+ // Append verbatim — pulldown-cmark text events already contain the+ // original line breaks, so inserting separators would double them.+ if self.in_code_block && self.code_block_lang.is_some() {+ self.code_block_buffer.push_str(&text);+ return;+ }+if self.in_code_block && !self.needs_newline {let has_content = self.current_line_content@@ -394,12 +409,25 @@ whereself.needs_newline = false;}- fn start_codeblock(&mut self, _lang: Option<String>, indent: Option<Span<'static>>) {+ fn start_codeblock(&mut self, lang: Option<String>, indent: Option<Span<'static>>) {self.flush_current_line();if !self.text.lines.is_empty() {self.push_blank_line();}self.in_code_block = true;++ // Extract the language token from the info string. CommonMark info+ // strings can contain metadata after the language, separated by commas,+ // spaces, or other delimiters (e.g. "rust,no_run", "rust title=demo").+ // Take only the first token so the syntax lookup succeeds.+ let lang = lang+ .as_deref()+ .and_then(|s| s.split([',', ' ', '\t']).next())+ .filter(|s| !s.is_empty())+ .map(std::string::ToString::to_string);+ self.code_block_lang = lang;+ self.code_block_buffer.clear();+self.indent_stack.push(IndentContext::new(vec![indent.unwrap_or_default()],None,@@ -409,6 +437,20 @@ where}fn end_codeblock(&mut self) {+ // If we buffered code for a known language, syntax-highlight it now.+ if let Some(lang) = self.code_block_lang.take() {+ let code = std::mem::take(&mut self.code_block_buffer);+ if !code.is_empty() {+ let highlighted = highlight_code_to_lines(&code, &lang);+ for hl_line in highlighted {+ self.push_line(Line::default());+ for span in hl_line.spans {+ self.push_span(span);+ }+ }+ }+ }+self.needs_newline = true;self.in_code_block = false;self.indent_stack.pop();@@ -689,4 +731,39 @@ mod tests {"expected full URL-like token in one rendered line, got: {lines:?}");}++ #[test]+ fn fenced_code_info_string_with_metadata_highlights() {+ // CommonMark info strings like "rust,no_run" or "rust title=demo"+ // contain metadata after the language token. The language must be+ // extracted (first word / comma-separated token) so highlighting works.+ for info in &["rust,no_run", "rust no_run", "rust title=\"demo\""] {+ let markdown = format!("```{info}\nfn main() {{}}\n```\n");+ let rendered = render_markdown_text(&markdown);+ let has_rgb = rendered.lines.iter().any(|line| {+ line.spans+ .iter()+ .any(|s| matches!(s.style.fg, Some(ratatui::style::Color::Rgb(..))))+ });+ assert!(+ has_rgb,+ "info string \"{info}\" should still produce syntax highlighting"+ );+ }+ }++ #[test]+ fn crlf_code_block_no_extra_blank_lines() {+ // pulldown-cmark can split CRLF code blocks into multiple Text events.+ // The buffer must concatenate them verbatim — no inserted separators.+ let markdown = "```rust\r\nfn main() {}\r\n line2\r\n```\r\n";+ let rendered = render_markdown_text(markdown);+ let lines = lines_to_strings(&rendered);+ // Should be exactly two code lines; no spurious blank line between them.+ assert_eq!(+ lines,+ vec!["fn main() {}".to_string(), " line2".to_string()],+ "CRLF code block should not produce extra blank lines: {lines:?}"+ );+ }}diff --git a/codex-rs/tui/src/markdown_render_tests.rs b/codex-rs/tui/src/markdown_render_tests.rsindex c549699695..68daaaab7f 100644--- a/codex-rs/tui/src/markdown_render_tests.rs+++ b/codex-rs/tui/src/markdown_render_tests.rs@@ -652,10 +652,83 @@ fn link() {}#[test]-fn code_block_unhighlighted() {+fn code_block_known_lang_has_syntax_colors() {let text = render_markdown_text("```rust\nfn main() {}\n```\n");- let expected = Text::from_iter([Line::from_iter(["", "fn main() {}"])]);- assert_eq!(text, expected);+ let content: Vec<String> = text+ .lines+ .iter()+ .map(|l| {+ l.spans+ .iter()+ .map(|s| s.content.clone())+ .collect::<String>()+ })+ .collect();+ // Content should be preserved; ignore trailing empty line from highlighting.+ let content: Vec<&str> = content+ .iter()+ .map(std::string::String::as_str)+ .filter(|s| !s.is_empty())+ .collect();+ assert_eq!(content, vec!["fn main() {}"]);++ // At least one span should have non-default style (syntax highlighting).+ let has_colored_span = text+ .lines+ .iter()+ .flat_map(|l| l.spans.iter())+ .any(|sp| sp.style.fg.is_some());+ assert!(has_colored_span, "expected syntax-highlighted spans with color");+}++#[test]+fn code_block_unknown_lang_plain() {+ let text = render_markdown_text("```xyzlang\nhello world\n```\n");+ let content: Vec<String> = text+ .lines+ .iter()+ .map(|l| {+ l.spans+ .iter()+ .map(|s| s.content.clone())+ .collect::<String>()+ })+ .collect();+ let content: Vec<&str> = content+ .iter()+ .map(std::string::String::as_str)+ .filter(|s| !s.is_empty())+ .collect();+ assert_eq!(content, vec!["hello world"]);++ // No syntax coloring for unknown language — all spans have default style.+ let has_colored_span = text+ .lines+ .iter()+ .flat_map(|l| l.spans.iter())+ .any(|sp| sp.style.fg.is_some());+ assert!(!has_colored_span, "expected no syntax coloring for unknown lang");+}++#[test]+fn code_block_no_lang_plain() {+ let text = render_markdown_text("```\nno lang specified\n```\n");+ let content: Vec<String> = text+ .lines+ .iter()+ .map(|l| {+ l.spans+ .iter()+ .map(|s| s.content.clone())+ .collect::<String>()+ })+ .collect();+ let content: Vec<&str> = content+ .iter()+ .map(std::string::String::as_str)+ .filter(|s| !s.is_empty())+ .collect();+ assert_eq!(content, vec!["no lang specified"]);}#[test]@@ -721,16 +794,25 @@ Here is a code block that shows another fenced block:.collect::<String>()}).collect();+ // Filter empty trailing lines for stability; the code block may or may+ // not emit a trailing blank depending on the highlighting path.+ let trimmed: Vec<&str> = {+ let mut v: Vec<&str> = lines.iter().map(std::string::String::as_str).collect();+ while v.last() == Some(&"") {+ v.pop();+ }+ v+ };assert_eq!(- lines,+ trimmed,vec![- "Here is a code block that shows another fenced block:".to_string(),- String::new(),- "```md".to_string(),- "# Inside fence".to_string(),- "- bullet".to_string(),- "- `inline code`".to_string(),- "```".to_string(),+ "Here is a code block that shows another fenced block:",+ "",+ "```md",+ "# Inside fence",+ "- bullet",+ "- `inline code`",+ "```",]);}@@ -993,3 +1075,36 @@ fn nested_item_continuation_paragraph_is_indented() {]);assert_eq!(text, expected);}++#[test]+fn code_block_preserves_trailing_blank_lines() {+ // A fenced code block with an intentional trailing blank line must keep it.+ let md = "```rust\nfn main() {}\n\n```\n";+ let text = render_markdown_text(md);+ let content: Vec<String> = text+ .lines+ .iter()+ .map(|l| {+ l.spans+ .iter()+ .map(|s| s.content.clone())+ .collect::<String>()+ })+ .collect();+ // Should have: "fn main() {}" then "" (the blank line).+ // Filter only to content lines (skip leading/trailing empty from rendering).+ assert!(+ content.iter().any(|c| c == "fn main() {}"),+ "expected code line, got {content:?}"+ );+ // The trailing blank line inside the fence should be preserved.+ let code_start = content.iter().position(|c| c == "fn main() {}").unwrap();+ assert!(+ content.len() > code_start + 1,+ "expected a line after 'fn main() {{}}' but content ends: {content:?}"+ );+ assert_eq!(+ content[code_start + 1], "",+ "trailing blank line inside code fence was lost: {content:?}"+ );+}diff --git a/codex-rs/tui/src/render/highlight.rs b/codex-rs/tui/src/render/highlight.rsindex e6d200cc3d..b0898ffe0a 100644--- a/codex-rs/tui/src/render/highlight.rs+++ b/codex-rs/tui/src/render/highlight.rs@@ -1,154 +1,574 @@+//! Syntax highlighting engine for the TUI.+//!+//! Wraps [syntect] with the [two_face] grammar and theme bundles to provide+//! ~250-language syntax highlighting and 32 bundled color themes. The module+//! owns four process-global singletons:+//!+//! | Singleton | Type | Purpose |+//! |---|---|---|+//! | `SYNTAX_SET` | `OnceLock<SyntaxSet>` | Grammar database, immutable after init |+//! | `THEME` | `OnceLock<RwLock<Theme>>` | Active color theme, swappable at runtime |+//! | `THEME_OVERRIDE` | `OnceLock<Option<String>>` | Persisted user preference (write-once) |+//! | `CODEX_HOME` | `OnceLock<Option<PathBuf>>` | Root for custom `.tmTheme` discovery |+//!+//! **Lifecycle:** call [`set_theme_override`] once at startup (after the final+//! config is resolved) to persist the user preference and seed the `THEME`+//! lock. After that, [`set_syntax_theme`] and [`current_syntax_theme`] can+//! swap/snapshot the theme for live preview. All highlighting functions read+//! the theme via `theme_lock()`.+//!+//! **Guardrails:** inputs exceeding 512 KB or 10 000 lines are rejected early+//! (returns `None`) to prevent pathological CPU/memory usage. Callers must+//! fall back to plain unstyled text.++use ratatui::style::Color as RtColor;+use ratatui::style::Modifier;use ratatui::style::Style;-use ratatui::style::Stylize;use ratatui::text::Line;use ratatui::text::Span;+use std::path::Path;+use std::path::PathBuf;use std::sync::OnceLock;-use tree_sitter_highlight::Highlight;-use tree_sitter_highlight::HighlightConfiguration;-use tree_sitter_highlight::HighlightEvent;-use tree_sitter_highlight::Highlighter;--// Ref: https://github.com/tree-sitter/tree-sitter-bash/blob/master/queries/highlights.scm-#[derive(Copy, Clone)]-enum BashHighlight {- Comment,- Constant,- Embedded,- Function,- Keyword,- Number,- Operator,- Property,- String,-}--impl BashHighlight {- const ALL: [Self; 9] = [- Self::Comment,- Self::Constant,- Self::Embedded,- Self::Function,- Self::Keyword,- Self::Number,- Self::Operator,- Self::Property,- Self::String,- ];-- const fn as_str(self) -> &'static str {- match self {- Self::Comment => "comment",- Self::Constant => "constant",- Self::Embedded => "embedded",- Self::Function => "function",- Self::Keyword => "keyword",- Self::Number => "number",- Self::Operator => "operator",- Self::Property => "property",- Self::String => "string",- }- }-- fn style(self) -> Style {- match self {- Self::Comment | Self::Operator | Self::String => Style::default().dim(),- _ => Style::default(),- }- }-}--static HIGHLIGHT_CONFIG: OnceLock<HighlightConfiguration> = OnceLock::new();--fn highlight_names() -> &'static [&'static str] {- static NAMES: OnceLock<[&'static str; BashHighlight::ALL.len()]> = OnceLock::new();- NAMES- .get_or_init(|| BashHighlight::ALL.map(BashHighlight::as_str))- .as_slice()-}--fn highlight_config() -> &'static HighlightConfiguration {- HIGHLIGHT_CONFIG.get_or_init(|| {- let language = tree_sitter_bash::LANGUAGE.into();- #[expect(clippy::expect_used)]- let mut config = HighlightConfiguration::new(- language,- "bash",- tree_sitter_bash::HIGHLIGHT_QUERY,- "",- "",- )- .expect("load bash highlight query");- config.configure(highlight_names());- config- })+use std::sync::RwLock;+use syntect::easy::HighlightLines;+use syntect::highlighting::FontStyle;+use syntect::highlighting::Style as SyntectStyle;+use syntect::highlighting::Theme;+use syntect::highlighting::ThemeSet;+use syntect::parsing::SyntaxReference;+use syntect::parsing::SyntaxSet;+use syntect::util::LinesWithEndings;+use two_face::theme::EmbeddedThemeName;++// -- Global singletons -------------------------------------------------------++static SYNTAX_SET: OnceLock<SyntaxSet> = OnceLock::new();+static THEME: OnceLock<RwLock<Theme>> = OnceLock::new();+static THEME_OVERRIDE: OnceLock<Option<String>> = OnceLock::new();+static CODEX_HOME: OnceLock<Option<PathBuf>> = OnceLock::new();++fn syntax_set() -> &'static SyntaxSet {+ SYNTAX_SET.get_or_init(two_face::syntax::extra_newlines)}-fn highlight_for(highlight: Highlight) -> BashHighlight {- BashHighlight::ALL[highlight.0]+/// Set the user-configured syntax theme override and codex home path.+///+/// Call this with the **final resolved config** (after onboarding, resume, and+/// fork reloads complete). The first call persists `name` and `codex_home` in+/// `OnceLock`s used by startup/default theme resolution.+///+/// Subsequent calls cannot change the persisted `OnceLock` values, but they+/// still update the runtime theme immediately for live preview flows.+///+/// Returns a warning message when the configured theme name cannot be+/// resolved to a bundled theme or a custom `.tmTheme` file on disk.+/// The caller should surface this via `Config::startup_warnings` so it+/// appears as a `⚠` banner in the TUI.+pub(crate) fn set_theme_override(+ name: Option<String>,+ codex_home: Option<PathBuf>,+) -> Option<String> {+ let mut warning = validate_theme_name(name.as_deref(), codex_home.as_deref());+ let override_set_ok = THEME_OVERRIDE.set(name.clone()).is_ok();+ let codex_home_set_ok = CODEX_HOME.set(codex_home.clone()).is_ok();+ if THEME.get().is_some() {+ set_syntax_theme(resolve_theme_with_override(+ name.as_deref(),+ codex_home.as_deref(),+ ));+ }+ if !override_set_ok || !codex_home_set_ok {+ let duplicate_msg = "Ignoring duplicate or late syntax theme override persistence; runtime theme was updated from the latest override, but persisted override config can only be initialized once.";+ tracing::warn!("{duplicate_msg}");+ if warning.is_none() {+ warning = Some(duplicate_msg.to_string());+ }+ }+ warning}-fn push_segment(lines: &mut Vec<Line<'static>>, segment: &str, style: Option<Style>) {- for (i, part) in segment.split('\n').enumerate() {- if i > 0 {- lines.push(Line::from(""));+/// Check whether a theme name resolves to a bundled theme or a custom+/// `.tmTheme` file. Returns a user-facing warning when it does not.+pub(crate) fn validate_theme_name(name: Option<&str>, codex_home: Option<&Path>) -> Option<String> {+ let name = name?;+ let custom_theme_path_display = codex_home+ .map(|home| custom_theme_path(name, home).display().to_string())+ .unwrap_or_else(|| format!("$CODEX_HOME/themes/{name}.tmTheme"));+ // Bundled themes always resolve.+ if parse_theme_name(name).is_some() {+ return None;+ }+ // Custom themes must parse successfully; an unreadable/invalid file should+ // still surface a startup warning so users can diagnose configuration issues.+ if let Some(home) = codex_home {+ let custom_path = custom_theme_path(name, home);+ if custom_path.is_file() {+ if load_custom_theme(name, home).is_some() {+ return None;+ }+ return Some(format!(+ "Syntax theme \"{name}\" was found at {custom_theme_path_display} \+ but could not be parsed. Falling back to auto-detection."+ ));}- if part.is_empty() {- continue;+ }+ Some(format!(+ "Unknown syntax theme \"{name}\", falling back to auto-detection. \+ Use a bundled name or place a .tmTheme file at \+ {custom_theme_path_display}"+ ))+}++/// Map a kebab-case theme name to the corresponding `EmbeddedThemeName`.+fn parse_theme_name(name: &str) -> Option<EmbeddedThemeName> {+ match name {+ "ansi" => Some(EmbeddedThemeName::Ansi),+ "base16" => Some(EmbeddedThemeName::Base16),+ "base16-eighties-dark" => Some(EmbeddedThemeName::Base16EightiesDark),+ "base16-mocha-dark" => Some(EmbeddedThemeName::Base16MochaDark),+ "base16-ocean-dark" => Some(EmbeddedThemeName::Base16OceanDark),+ "base16-ocean-light" => Some(EmbeddedThemeName::Base16OceanLight),+ "base16-256" => Some(EmbeddedThemeName::Base16_256),+ "catppuccin-frappe" => Some(EmbeddedThemeName::CatppuccinFrappe),+ "catppuccin-latte" => Some(EmbeddedThemeName::CatppuccinLatte),+ "catppuccin-macchiato" => Some(EmbeddedThemeName::CatppuccinMacchiato),+ "catppuccin-mocha" => Some(EmbeddedThemeName::CatppuccinMocha),+ "coldark-cold" => Some(EmbeddedThemeName::ColdarkCold),+ "coldark-dark" => Some(EmbeddedThemeName::ColdarkDark),+ "dark-neon" => Some(EmbeddedThemeName::DarkNeon),+ "dracula" => Some(EmbeddedThemeName::Dracula),+ "github" => Some(EmbeddedThemeName::Github),+ "gruvbox-dark" => Some(EmbeddedThemeName::GruvboxDark),+ "gruvbox-light" => Some(EmbeddedThemeName::GruvboxLight),+ "inspired-github" => Some(EmbeddedThemeName::InspiredGithub),+ "1337" => Some(EmbeddedThemeName::Leet),+ "monokai-extended" => Some(EmbeddedThemeName::MonokaiExtended),+ "monokai-extended-bright" => Some(EmbeddedThemeName::MonokaiExtendedBright),+ "monokai-extended-light" => Some(EmbeddedThemeName::MonokaiExtendedLight),+ "monokai-extended-origin" => Some(EmbeddedThemeName::MonokaiExtendedOrigin),+ "nord" => Some(EmbeddedThemeName::Nord),+ "one-half-dark" => Some(EmbeddedThemeName::OneHalfDark),+ "one-half-light" => Some(EmbeddedThemeName::OneHalfLight),+ "solarized-dark" => Some(EmbeddedThemeName::SolarizedDark),+ "solarized-light" => Some(EmbeddedThemeName::SolarizedLight),+ "sublime-snazzy" => Some(EmbeddedThemeName::SublimeSnazzy),+ "two-dark" => Some(EmbeddedThemeName::TwoDark),+ "zenburn" => Some(EmbeddedThemeName::Zenburn),+ _ => None,+ }+}++/// Build the expected path for a custom theme file.+fn custom_theme_path(name: &str, codex_home: &Path) -> PathBuf {+ codex_home.join("themes").join(format!("{name}.tmTheme"))+}++/// Try to load a custom `.tmTheme` file from `{codex_home}/themes/{name}.tmTheme`.+fn load_custom_theme(name: &str, codex_home: &Path) -> Option<Theme> {+ ThemeSet::get_theme(custom_theme_path(name, codex_home)).ok()+}++fn adaptive_default_theme_selection() -> (EmbeddedThemeName, &'static str) {+ match crate::terminal_palette::default_bg() {+ Some(bg) if crate::color::is_light(bg) => {+ (EmbeddedThemeName::CatppuccinLatte, "catppuccin-latte")}- let span = match style {- Some(style) => Span::styled(part.to_string(), style),- None => part.to_string().into(),- };- if let Some(last) = lines.last_mut() {- last.spans.push(span);+ _ => (EmbeddedThemeName::CatppuccinMocha, "catppuccin-mocha"),+ }+}++fn adaptive_default_embedded_theme_name() -> EmbeddedThemeName {+ adaptive_default_theme_selection().0+}++/// Return the kebab-case name of the adaptive default syntax theme selected+/// from terminal background lightness.+pub(crate) fn adaptive_default_theme_name() -> &'static str {+ adaptive_default_theme_selection().1+}++/// Build the theme from current override/auto-detection settings.+/// Extracted from the old `theme()` init closure so it can be reused.+fn resolve_theme_with_override(name: Option<&str>, codex_home: Option<&Path>) -> Theme {+ let ts = two_face::theme::extra();++ // Honor user-configured theme if valid.+ if let Some(name) = name {+ // 1. Try bundled theme by kebab-case name.+ if let Some(theme_name) = parse_theme_name(name) {+ return ts.get(theme_name).clone();+ }+ // 2. Try loading {CODEX_HOME}/themes/{name}.tmTheme from disk.+ if let Some(home) = codex_home+ && let Some(theme) = load_custom_theme(name, home)+ {+ return theme;}+ tracing::warn!("unknown syntax theme \"{name}\", falling back to auto-detection");}++ ts.get(adaptive_default_embedded_theme_name()).clone()}-/// Convert a bash script into per-line styled content using tree-sitter's-/// bash highlight query. The highlighter is streamed so multi-line content is-/// split into `Line`s while preserving style boundaries.-pub(crate) fn highlight_bash_to_lines(script: &str) -> Vec<Line<'static>> {- let mut highlighter = Highlighter::new();- let iterator =- match highlighter.highlight(highlight_config(), script.as_bytes(), None, |_| None) {- Ok(iter) => iter,- Err(_) => return vec![script.to_string().into()],- };+/// Build the theme from current override/auto-detection settings.+/// Extracted from the old `theme()` init closure so it can be reused.+fn build_default_theme() -> Theme {+ let name = THEME_OVERRIDE.get().and_then(|name| name.as_deref());+ let codex_home = CODEX_HOME+ .get()+ .and_then(|codex_home| codex_home.as_deref());+ resolve_theme_with_override(name, codex_home)+}- let mut lines: Vec<Line<'static>> = vec![Line::from("")];- let mut highlight_stack: Vec<Highlight> = Vec::new();+fn theme_lock() -> &'static RwLock<Theme> {+ THEME.get_or_init(|| RwLock::new(build_default_theme()))+}- for event in iterator {- match event {- Ok(HighlightEvent::HighlightStart(highlight)) => highlight_stack.push(highlight),- Ok(HighlightEvent::HighlightEnd) => {- highlight_stack.pop();- }- Ok(HighlightEvent::Source { start, end }) => {- if start == end {- continue;+/// Swap the active syntax theme at runtime (for live preview).+pub(crate) fn set_syntax_theme(theme: Theme) {+ let mut guard = match theme_lock().write() {+ Ok(guard) => guard,+ Err(poisoned) => poisoned.into_inner(),+ };+ *guard = theme;+}++/// Clone the current syntax theme (e.g. to save for cancel-restore).+pub(crate) fn current_syntax_theme() -> Theme {+ match theme_lock().read() {+ Ok(theme) => theme.clone(),+ Err(poisoned) => poisoned.into_inner().clone(),+ }+}++/// Return the configured kebab-case theme name when it resolves; otherwise+/// return the adaptive auto-detected default theme name.+///+/// This intentionally reflects persisted configuration/default selection, not+/// transient runtime swaps applied via `set_syntax_theme`.+pub(crate) fn configured_theme_name() -> String {+ // Explicit user override?+ if let Some(Some(name)) = THEME_OVERRIDE.get() {+ if parse_theme_name(name).is_some() {+ return name.clone();+ }+ if let Some(Some(home)) = CODEX_HOME.get()+ && load_custom_theme(name, home).is_some()+ {+ return name.clone();+ }+ }+ adaptive_default_theme_name().to_string()+}++/// Resolve a theme name to a `Theme` (bundled or custom). Returns `None`+/// when the name is unknown and no matching `.tmTheme` file exists.+pub(crate) fn resolve_theme_by_name(name: &str, codex_home: Option<&Path>) -> Option<Theme> {+ let ts = two_face::theme::extra();+ // Bundled theme?+ if let Some(embedded) = parse_theme_name(name) {+ return Some(ts.get(embedded).clone());+ }+ // Custom .tmTheme file?+ if let Some(home) = codex_home+ && let Some(theme) = load_custom_theme(name, home)+ {+ return Some(theme);+ }+ None+}++/// A theme available in the picker, either bundled or loaded from a custom+/// `.tmTheme` file under `{CODEX_HOME}/themes/`.+pub(crate) struct ThemeEntry {+ /// Kebab-case identifier used for config persistence and theme resolution.+ pub name: String,+ /// `true` when this entry was discovered from a `.tmTheme` file on disk+ /// rather than the embedded two-face bundle.+ pub is_custom: bool,+}++/// List all available theme names: bundled themes + custom `.tmTheme` files+/// found in `{codex_home}/themes/`.+pub(crate) fn list_available_themes(codex_home: Option<&Path>) -> Vec<ThemeEntry> {+ let mut entries: Vec<ThemeEntry> = BUILTIN_THEME_NAMES+ .iter()+ .map(|name| ThemeEntry {+ name: name.to_string(),+ is_custom: false,+ })+ .collect();++ // Discover custom themes on disk, deduplicating against builtins.+ if let Some(home) = codex_home {+ let themes_dir = home.join("themes");+ if let Ok(read_dir) = std::fs::read_dir(&themes_dir) {+ for entry in read_dir.flatten() {+ let path = entry.path();+ if path.extension().and_then(|e| e.to_str()) == Some("tmTheme")+ && let Some(stem) = path.file_stem().and_then(|s| s.to_str())+ {+ let name = stem.to_string();+ let is_valid_theme = ThemeSet::get_theme(&path).is_ok();+ if is_valid_theme && !entries.iter().any(|e| e.name == name) {+ entries.push(ThemeEntry {+ name,+ is_custom: true,+ });+ }}- let style = highlight_stack.last().map(|h| highlight_for(*h).style());- push_segment(&mut lines, &script[start..end], style);}- Err(_) => return vec![script.to_string().into()],}}- if lines.is_empty() {- vec![Line::from("")]+ // Keep picker ordering stable across platforms/filesystems.+ entries.sort_by(|a, b| (a.is_custom, a.name.as_str()).cmp(&(b.is_custom, b.name.as_str())));++ entries+}++/// All 32 bundled theme names in kebab-case, ordered alphabetically.+const BUILTIN_THEME_NAMES: &[&str] = &[+ "1337",+ "ansi",+ "base16",+ "base16-256",+ "base16-eighties-dark",+ "base16-mocha-dark",+ "base16-ocean-dark",+ "base16-ocean-light",+ "catppuccin-frappe",+ "catppuccin-latte",+ "catppuccin-macchiato",+ "catppuccin-mocha",+ "coldark-cold",+ "coldark-dark",+ "dark-neon",+ "dracula",+ "github",+ "gruvbox-dark",+ "gruvbox-light",+ "inspired-github",+ "monokai-extended",+ "monokai-extended-bright",+ "monokai-extended-light",+ "monokai-extended-origin",+ "nord",+ "one-half-dark",+ "one-half-light",+ "solarized-dark",+ "solarized-light",+ "sublime-snazzy",+ "two-dark",+ "zenburn",+];++// -- Style conversion (syntect -> ratatui) ------------------------------------++/// Convert a syntect `Style` to a ratatui `Style`.+///+/// Syntax highlighting themes inherently produce RGB colors, so we allow+/// `Color::Rgb` here despite the project-wide preference for ANSI colors.+#[allow(clippy::disallowed_methods)]+fn convert_style(syn_style: SyntectStyle) -> Style {+ let mut rt_style = Style::default();++ // Map foreground color when visible.+ let fg = syn_style.foreground;+ if fg.a > 0 {+ rt_style = rt_style.fg(RtColor::Rgb(fg.r, fg.g, fg.b));+ }+ // Intentionally skip background to avoid overwriting terminal bg.++ if syn_style.font_style.contains(FontStyle::BOLD) {+ rt_style.add_modifier |= Modifier::BOLD;+ }+ // Intentionally skip italic — many terminals render it poorly or not at all.+ // Intentionally skip underline — themes like Dracula use underline on type+ // scopes (entity.name.type, support.class) which produces distracting+ // underlines on type/module names in terminal output.++ rt_style+}++// -- Syntax lookup ------------------------------------------------------------++/// Try to find a syntect `SyntaxReference` for the given language identifier.+///+/// two-face's extended syntax set (~250 languages) resolves most names and+/// extensions directly. We only patch the few aliases it cannot handle.+fn find_syntax(lang: &str) -> Option<&'static SyntaxReference> {+ let ss = syntax_set();++ // Aliases that two-face does not resolve on its own.+ let patched = match lang {+ "golang" => "go",+ "python3" => "python",+ "shell" => "bash",+ _ => lang,+ };++ // Try by token (matches file_extensions case-insensitively).+ if let Some(s) = ss.find_syntax_by_token(patched) {+ return Some(s);+ }+ // Try by exact syntax name (e.g. "Rust", "Python").+ if let Some(s) = ss.find_syntax_by_name(patched) {+ return Some(s);+ }+ // Try case-insensitive name match (e.g. "rust" -> "Rust").+ let lower = patched.to_ascii_lowercase();+ if let Some(s) = ss+ .syntaxes()+ .iter()+ .find(|s| s.name.to_ascii_lowercase() == lower)+ {+ return Some(s);+ }+ // Try raw input as file extension.+ if let Some(s) = ss.find_syntax_by_extension(lang) {+ return Some(s);+ }+ None+}++// -- Guardrail constants ------------------------------------------------------++/// Skip highlighting for inputs larger than 512 KB to avoid excessive memory+/// and CPU usage. Callers fall back to plain unstyled text.+const MAX_HIGHLIGHT_BYTES: usize = 512 * 1024;++/// Skip highlighting for inputs with more than 10,000 lines.+const MAX_HIGHLIGHT_LINES: usize = 10_000;++/// Check whether an input exceeds the safe highlighting limits.+///+/// Callers that highlight content in a loop (e.g. per diff-line) should+/// pre-check the aggregate size with this function and skip highlighting+/// entirely when it returns `true`.+pub(crate) fn exceeds_highlight_limits(total_bytes: usize, total_lines: usize) -> bool {+ total_bytes > MAX_HIGHLIGHT_BYTES || total_lines > MAX_HIGHLIGHT_LINES+}++// -- Core highlighting --------------------------------------------------------++/// Parse `code` using syntect for `lang` and return per-line styled spans.+/// Each inner Vec represents one source line. Returns None when the language+/// is not recognized or the input exceeds safety limits.+fn highlight_to_line_spans(code: &str, lang: &str) -> Option<Vec<Vec<Span<'static>>>> {+ // Empty input has nothing to highlight; fall back to the plain text path+ // which correctly produces a single empty Line.+ if code.is_empty() {+ return None;+ }++ // Bail out early for oversized inputs to avoid excessive resource usage.+ // Count actual lines (not newline bytes) to avoid an off-by-one when+ // the input does not end with a newline.+ if code.len() > MAX_HIGHLIGHT_BYTES || code.lines().count() > MAX_HIGHLIGHT_LINES {+ return None;+ }++ let syntax = find_syntax(lang)?;+ let theme_guard = match theme_lock().read() {+ Ok(theme_guard) => theme_guard,+ Err(poisoned) => poisoned.into_inner(),+ };+ let mut h = HighlightLines::new(syntax, &theme_guard);+ let mut lines: Vec<Vec<Span<'static>>> = Vec::new();++ for line in LinesWithEndings::from(code) {+ let ranges = h.highlight_line(line, syntax_set()).ok()?;+ let mut spans: Vec<Span<'static>> = Vec::new();+ for (style, text) in ranges {+ // Strip trailing line endings (LF and CR) since we handle line+ // breaks ourselves. CRLF inputs would otherwise leave a stray \r.+ let text = text.trim_end_matches(['\n', '\r']);+ if text.is_empty() {+ continue;+ }+ spans.push(Span::styled(text.to_string(), convert_style(style)));+ }+ if spans.is_empty() {+ spans.push(Span::raw(String::new()));+ }+ lines.push(spans);+ }++ Some(lines)+}++// -- Public API ---------------------------------------------------------------++/// Highlight code in any supported language, returning styled ratatui `Line`s.+///+/// Falls back to plain unstyled text when the language is not recognized or the+/// input exceeds safety guardrails. Callers can always render the result+/// directly -- the fallback path produces equivalent plain-text lines.+///+/// Used by `markdown_render` for fenced code blocks and by `exec_cell` for bash+/// command highlighting.+pub(crate) fn highlight_code_to_lines(code: &str, lang: &str) -> Vec<Line<'static>> {+ if let Some(line_spans) = highlight_to_line_spans(code, lang) {+ line_spans.into_iter().map(Line::from).collect()} else {- lines+ // Fallback: plain text, one Line per source line.+ // Use `lines()` instead of `split('\n')` to avoid a phantom trailing+ // empty element when the input ends with '\n' (as pulldown-cmark emits).+ let mut result: Vec<Line<'static>> =+ code.lines().map(|l| Line::from(l.to_string())).collect();+ if result.is_empty() {+ result.push(Line::from(String::new()));+ }+ result}}+/// Backward-compatible wrapper for bash highlighting used by exec cells.+pub(crate) fn highlight_bash_to_lines(script: &str) -> Vec<Line<'static>> {+ highlight_code_to_lines(script, "bash")+}++/// Highlight code and return per-line styled spans for diff integration.+///+/// Returns `None` when the language is unrecognized or the input exceeds+/// guardrails. The caller (`diff_render`) uses this signal to fall back to+/// plain diff coloring.+///+/// Each inner `Vec<Span>` corresponds to one source line. Styles are derived+/// from the active theme but backgrounds are intentionally omitted so the+/// terminal's own background shows through.+pub(crate) fn highlight_code_to_styled_spans(+ code: &str,+ lang: &str,+) -> Option<Vec<Vec<Span<'static>>>> {+ highlight_to_line_spans(code, lang)+}+#[cfg(test)]mod tests {use super::*;use pretty_assertions::assert_eq;- use ratatui::style::Modifier;+ fn write_minimal_tmtheme(path: &Path) {+ // Minimal valid .tmTheme plist (enough for syntect to parse).+ std::fs::write(+ path,+ r#"<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0"><dict>+<key>name</key><string>Test</string>+<key>settings</key><array><dict>+<key>settings</key><dict>+<key>foreground</key><string>#FFFFFF</string>+<key>background</key><string>#000000</string>+</dict></dict></array>+</dict></plist>"#,+ )+ .unwrap();+ }++ /// Reconstruct plain text from highlighted Lines.fn reconstructed(lines: &[Line<'static>]) -> String {lines.iter()@@ -162,75 +582,514 @@ mod tests {.join("\n")}- fn dimmed_tokens(lines: &[Line<'static>]) -> Vec<String> {- lines- .iter()- .flat_map(|l| l.spans.iter())- .filter(|sp| sp.style.add_modifier.contains(Modifier::DIM))- .map(|sp| sp.content.clone().into_owned())- .map(|token| token.trim().to_string())- .filter(|token| !token.is_empty())- .collect()+ #[test]+ fn highlight_rust_has_keyword_style() {+ let code = "fn main() {}";+ let lines = highlight_code_to_lines(code, "rust");+ assert_eq!(reconstructed(&lines), code);++ // The `fn` keyword should have a non-default style (some color).+ let fn_span = lines[0].spans.iter().find(|sp| sp.content.as_ref() == "fn");+ assert!(fn_span.is_some(), "expected a span containing 'fn'");+ let style = fn_span.map(|s| s.style).unwrap_or_default();+ assert!(+ style.fg.is_some() || style.add_modifier != Modifier::empty(),+ "expected fn keyword to have non-default style, got {style:?}"+ );}#[test]- fn dims_expected_bash_operators() {- let s = "echo foo && bar || baz | qux & (echo hi)";- let lines = highlight_bash_to_lines(s);- assert_eq!(reconstructed(&lines), s);+ fn highlight_unknown_lang_falls_back() {+ let code = "some random text";+ let lines = highlight_code_to_lines(code, "xyzlang");+ assert_eq!(reconstructed(&lines), code);+ // Should be plain text with no styling.+ for line in &lines {+ for span in &line.spans {+ assert_eq!(+ span.style,+ Style::default(),+ "expected default style for unknown language"+ );+ }+ }+ }- let dimmed = dimmed_tokens(&lines);- assert!(dimmed.contains(&"&&".to_string()));- assert!(dimmed.contains(&"|".to_string()));- assert!(!dimmed.contains(&"echo".to_string()));+ #[test]+ fn fallback_trailing_newline_no_phantom_line() {+ // pulldown-cmark sends code block text ending with '\n'.+ // The fallback path (unknown language) must not produce a phantom+ // empty trailing line from that newline.+ let code = "hello world\n";+ let lines = highlight_code_to_lines(code, "xyzlang");+ assert_eq!(+ lines.len(),+ 1,+ "trailing newline should not produce phantom blank line, got {lines:?}"+ );+ assert_eq!(reconstructed(&lines), "hello world");}#[test]- fn dims_redirects_and_strings() {- let s = "echo \"hi\" > out.txt; echo 'ok'";- let lines = highlight_bash_to_lines(s);- assert_eq!(reconstructed(&lines), s);+ fn highlight_empty_string() {+ let lines = highlight_code_to_lines("", "rust");+ assert_eq!(lines.len(), 1);+ assert_eq!(reconstructed(&lines), "");+ }- let dimmed = dimmed_tokens(&lines);- assert!(dimmed.contains(&">".to_string()));- assert!(dimmed.contains(&"\"hi\"".to_string()));- assert!(dimmed.contains(&"'ok'".to_string()));+ #[test]+ fn highlight_bash_preserves_content() {+ let script = "echo \"hello world\" && ls -la | grep foo";+ let lines = highlight_bash_to_lines(script);+ assert_eq!(reconstructed(&lines), script);}#[test]- fn highlights_command_and_strings() {- let s = "echo \"hi\"";- let lines = highlight_bash_to_lines(s);- let mut echo_style = None;- let mut string_style = None;- for span in &lines[0].spans {- let text = span.content.as_ref();- if text == "echo" {- echo_style = Some(span.style);- }- if text == "\"hi\"" {- string_style = Some(span.style);+ fn highlight_crlf_strips_carriage_return() {+ // Windows-style \r\n line endings must not leave a trailing \r in+ // span text — that would propagate into rendered code blocks.+ let code = "fn main() {\r\n println!(\"hi\");\r\n}\r\n";+ let lines = highlight_code_to_lines(code, "rust");+ for (i, line) in lines.iter().enumerate() {+ for span in &line.spans {+ assert!(+ !span.content.contains('\r'),+ "line {i} span {:?} contains \\r",+ span.content,+ );}}- let echo_style = echo_style.expect("echo span missing");- let string_style = string_style.expect("string span missing");- assert!(echo_style.fg.is_none());- assert!(!echo_style.add_modifier.contains(Modifier::DIM));- assert!(string_style.add_modifier.contains(Modifier::DIM));}#[test]- fn highlights_heredoc_body_as_string() {- let s = "cat <<EOF\nheredoc body\nEOF";- let lines = highlight_bash_to_lines(s);- let body_line = &lines[1];- let mut body_style = None;- for span in &body_line.spans {- if span.content.as_ref() == "heredoc body" {- body_style = Some(span.style);- }+ #[allow(clippy::disallowed_methods)]+ fn style_conversion_correctness() {+ let syn = SyntectStyle {+ foreground: syntect::highlighting::Color {+ r: 255,+ g: 128,+ b: 0,+ a: 255,+ },+ background: syntect::highlighting::Color {+ r: 0,+ g: 0,+ b: 0,+ a: 255,+ },+ font_style: FontStyle::BOLD | FontStyle::ITALIC,+ };+ let rt = convert_style(syn);+ assert_eq!(rt.fg, Some(RtColor::Rgb(255, 128, 0)));+ // Background is intentionally skipped.+ assert_eq!(rt.bg, None);+ assert!(rt.add_modifier.contains(Modifier::BOLD));+ // Italic is intentionally suppressed.+ assert!(!rt.add_modifier.contains(Modifier::ITALIC));+ assert!(!rt.add_modifier.contains(Modifier::UNDERLINED));+ }++ #[test]+ #[allow(clippy::disallowed_methods)]+ fn convert_style_suppresses_underline() {+ // Dracula (and other themes) set FontStyle::UNDERLINE on type scopes,+ // producing distracting underlines on type names in terminal output.+ // convert_style must suppress underline, just like it suppresses italic.+ let syn = SyntectStyle {+ foreground: syntect::highlighting::Color {+ r: 100,+ g: 200,+ b: 150,+ a: 255,+ },+ background: syntect::highlighting::Color {+ r: 0,+ g: 0,+ b: 0,+ a: 0,+ },+ font_style: FontStyle::UNDERLINE,+ };+ let rt = convert_style(syn);+ assert!(+ !rt.add_modifier.contains(Modifier::UNDERLINED),+ "convert_style should suppress UNDERLINE from themes — \+ themes like Dracula use underline on type scopes which \+ looks wrong in terminal output"+ );+ }++ #[test]+ fn highlight_multiline_python() {+ let code = "def hello():\n print(\"hi\")\n return 42";+ let lines = highlight_code_to_lines(code, "python");+ assert_eq!(reconstructed(&lines), code);+ assert_eq!(lines.len(), 3);+ }++ #[test]+ fn highlight_code_to_styled_spans_returns_none_for_unknown() {+ assert!(highlight_code_to_styled_spans("x", "xyzlang").is_none());+ }++ #[test]+ fn highlight_code_to_styled_spans_returns_some_for_known() {+ let result = highlight_code_to_styled_spans("let x = 1;", "rust");+ assert!(result.is_some());+ let spans = result.unwrap_or_default();+ assert!(!spans.is_empty());+ }++ #[test]+ fn highlight_markdown_preserves_content() {+ let code = "```sh\nprintf 'fenced within fenced\\n'\n```";+ let lines = highlight_code_to_lines(code, "markdown");+ let result = reconstructed(&lines);+ assert_eq!(+ result, code,+ "markdown highlighting must preserve content exactly"+ );+ }++ #[test]+ fn highlight_large_input_falls_back() {+ // Input exceeding MAX_HIGHLIGHT_BYTES should return None (plain text+ // fallback) rather than attempting to parse.+ let big = "x".repeat(MAX_HIGHLIGHT_BYTES + 1);+ let result = highlight_code_to_styled_spans(&big, "rust");+ assert!(result.is_none(), "oversized input should fall back to None");+ }++ #[test]+ fn highlight_many_lines_falls_back() {+ // Input exceeding MAX_HIGHLIGHT_LINES should return None.+ let many_lines = "let x = 1;\n".repeat(MAX_HIGHLIGHT_LINES + 1);+ let result = highlight_code_to_styled_spans(&many_lines, "rust");+ assert!(result.is_none(), "too many lines should fall back to None");+ }++ #[test]+ fn highlight_many_lines_no_trailing_newline_falls_back() {+ // A snippet with exactly MAX_HIGHLIGHT_LINES+1 lines but no trailing+ // newline has only MAX_HIGHLIGHT_LINES newline bytes. The guard must+ // count actual lines, not newline bytes, to catch this.+ let mut code = "let x = 1;\n".repeat(MAX_HIGHLIGHT_LINES);+ code.push_str("let x = 1;"); // line MAX_HIGHLIGHT_LINES+1, no trailing \n+ assert_eq!(code.lines().count(), MAX_HIGHLIGHT_LINES + 1);+ let result = highlight_code_to_styled_spans(&code, "rust");+ assert!(+ result.is_none(),+ "MAX_HIGHLIGHT_LINES+1 lines without trailing newline should fall back"+ );+ }++ #[test]+ fn find_syntax_resolves_languages_and_aliases() {+ // Languages resolved directly by two-face's extended syntax set.+ let languages = [+ "javascript",+ "typescript",+ "tsx",+ "python",+ "ruby",+ "rust",+ "go",+ "c",+ "cpp",+ "yaml",+ "bash",+ "kotlin",+ "markdown",+ "sql",+ "lua",+ "zig",+ "swift",+ "java",+ "elixir",+ "haskell",+ "scala",+ "dart",+ "r",+ "perl",+ "php",+ "html",+ "css",+ "json",+ "toml",+ "xml",+ "dockerfile",+ ];+ for lang in languages {+ assert!(+ find_syntax(lang).is_some(),+ "find_syntax({lang:?}) returned None"+ );+ }+ // Common file extensions.+ let extensions = [+ "rs", "py", "js", "ts", "rb", "go", "sh", "md", "yml", "kt", "ex", "hs", "pl", "php",+ "css", "html",+ ];+ for ext in extensions {+ assert!(+ find_syntax(ext).is_some(),+ "find_syntax({ext:?}) returned None"+ );+ }+ // Patched aliases that two-face cannot resolve on its own.+ for alias in ["golang", "python3", "shell"] {+ assert!(+ find_syntax(alias).is_some(),+ "find_syntax({alias:?}) returned None — patched alias broken"+ );+ }+ }++ #[test]+ fn parse_theme_name_covers_all_variants() {+ let known = [+ ("ansi", EmbeddedThemeName::Ansi),+ ("base16", EmbeddedThemeName::Base16),+ (+ "base16-eighties-dark",+ EmbeddedThemeName::Base16EightiesDark,+ ),+ ("base16-mocha-dark", EmbeddedThemeName::Base16MochaDark),+ ("base16-ocean-dark", EmbeddedThemeName::Base16OceanDark),+ ("base16-ocean-light", EmbeddedThemeName::Base16OceanLight),+ ("base16-256", EmbeddedThemeName::Base16_256),+ ("catppuccin-frappe", EmbeddedThemeName::CatppuccinFrappe),+ ("catppuccin-latte", EmbeddedThemeName::CatppuccinLatte),+ (+ "catppuccin-macchiato",+ EmbeddedThemeName::CatppuccinMacchiato,+ ),+ ("catppuccin-mocha", EmbeddedThemeName::CatppuccinMocha),+ ("coldark-cold", EmbeddedThemeName::ColdarkCold),+ ("coldark-dark", EmbeddedThemeName::ColdarkDark),+ ("dark-neon", EmbeddedThemeName::DarkNeon),+ ("dracula", EmbeddedThemeName::Dracula),+ ("github", EmbeddedThemeName::Github),+ ("gruvbox-dark", EmbeddedThemeName::GruvboxDark),+ ("gruvbox-light", EmbeddedThemeName::GruvboxLight),+ ("inspired-github", EmbeddedThemeName::InspiredGithub),+ ("1337", EmbeddedThemeName::Leet),+ ("monokai-extended", EmbeddedThemeName::MonokaiExtended),+ (+ "monokai-extended-bright",+ EmbeddedThemeName::MonokaiExtendedBright,+ ),+ (+ "monokai-extended-light",+ EmbeddedThemeName::MonokaiExtendedLight,+ ),+ (+ "monokai-extended-origin",+ EmbeddedThemeName::MonokaiExtendedOrigin,+ ),+ ("nord", EmbeddedThemeName::Nord),+ ("one-half-dark", EmbeddedThemeName::OneHalfDark),+ ("one-half-light", EmbeddedThemeName::OneHalfLight),+ ("solarized-dark", EmbeddedThemeName::SolarizedDark),+ ("solarized-light", EmbeddedThemeName::SolarizedLight),+ ("sublime-snazzy", EmbeddedThemeName::SublimeSnazzy),+ ("two-dark", EmbeddedThemeName::TwoDark),+ ("zenburn", EmbeddedThemeName::Zenburn),+ ];+ for (kebab, expected) in &known {+ assert_eq!(+ parse_theme_name(kebab),+ Some(*expected),+ "parse_theme_name({kebab:?}) did not return expected variant"+ );+ }+ }++ #[test]+ fn parse_theme_name_returns_none_for_unknown() {+ assert_eq!(parse_theme_name("nonexistent-theme"), None);+ assert_eq!(parse_theme_name(""), None);+ }++ #[test]+ fn load_custom_theme_from_tmtheme_file() {+ let dir = tempfile::tempdir().unwrap();+ let themes_dir = dir.path().join("themes");+ std::fs::create_dir(&themes_dir).unwrap();+ write_minimal_tmtheme(&themes_dir.join("test-custom.tmTheme"));+ let theme = load_custom_theme("test-custom", dir.path());+ assert!(theme.is_some(), "should load .tmTheme from themes dir");+ }++ #[test]+ fn load_custom_theme_returns_none_for_missing() {+ let dir = tempfile::tempdir().unwrap();+ assert!(load_custom_theme("nonexistent", dir.path()).is_none());+ }++ #[test]+ fn validate_theme_name_none_for_bundled() {+ // Bundled themes should never produce a warning.+ assert!(validate_theme_name(Some("dracula"), None).is_none());+ assert!(validate_theme_name(Some("nord"), Some(Path::new("/nonexistent"))).is_none());+ }++ #[test]+ fn validate_theme_name_none_when_no_override() {+ assert!(validate_theme_name(None, None).is_none());+ }++ #[test]+ fn validate_theme_name_warns_for_missing_custom() {+ let dir = tempfile::tempdir().unwrap();+ let warning = validate_theme_name(Some("my-fancy"), Some(dir.path()));+ assert!(warning.is_some(), "should warn when theme file is absent");+ let msg = warning.unwrap();+ assert!(+ msg.contains("my-fancy"),+ "warning should mention the theme name"+ );+ }++ #[test]+ fn validate_theme_name_none_when_custom_file_is_valid() {+ let dir = tempfile::tempdir().unwrap();+ let themes_dir = dir.path().join("themes");+ std::fs::create_dir(&themes_dir).unwrap();+ write_minimal_tmtheme(&themes_dir.join("my-fancy.tmTheme"));+ assert!(+ validate_theme_name(Some("my-fancy"), Some(dir.path())).is_none(),+ "should not warn when custom .tmTheme file parses successfully"+ );+ }++ #[test]+ fn validate_theme_name_warns_when_custom_file_is_invalid() {+ let dir = tempfile::tempdir().unwrap();+ let themes_dir = dir.path().join("themes");+ std::fs::create_dir(&themes_dir).unwrap();+ std::fs::write(themes_dir.join("my-fancy.tmTheme"), "placeholder").unwrap();+ let warning = validate_theme_name(Some("my-fancy"), Some(dir.path()));+ assert!(+ warning.is_some(),+ "should warn when custom .tmTheme exists but cannot be parsed"+ );+ assert!(+ warning+ .as_deref()+ .is_some_and(|msg| msg.contains("could not be parsed")),+ "warning should explain that the theme file is invalid"+ );+ }++ #[test]+ fn list_available_themes_excludes_invalid_custom_files() {+ let dir = tempfile::tempdir().unwrap();+ let themes_dir = dir.path().join("themes");+ std::fs::create_dir(&themes_dir).unwrap();+ write_minimal_tmtheme(&themes_dir.join("valid-custom.tmTheme"));+ std::fs::write(themes_dir.join("broken-custom.tmTheme"), "not a plist").unwrap();++ let entries = list_available_themes(Some(dir.path()));++ assert!(+ entries+ .iter()+ .any(|entry| entry.name == "valid-custom" && entry.is_custom),+ "expected valid custom theme to be listed"+ );+ assert!(+ !entries+ .iter()+ .any(|entry| entry.name == "broken-custom" && entry.is_custom),+ "expected invalid custom theme to be excluded from list"+ );+ }++ #[test]+ fn list_available_themes_returns_stable_sorted_order() {+ let dir = tempfile::tempdir().unwrap();+ let themes_dir = dir.path().join("themes");+ std::fs::create_dir(&themes_dir).unwrap();+ write_minimal_tmtheme(&themes_dir.join("zzz-custom.tmTheme"));+ write_minimal_tmtheme(&themes_dir.join("aaa-custom.tmTheme"));+ write_minimal_tmtheme(&themes_dir.join("mmm-custom.tmTheme"));++ let entries = list_available_themes(Some(dir.path()));+ let actual: Vec<(bool, String)> = entries+ .iter()+ .map(|entry| (entry.is_custom, entry.name.clone()))+ .collect();++ let mut expected = actual.clone();+ expected.sort_by(|a, b| (a.0, a.1.as_str()).cmp(&(b.0, b.1.as_str())));++ assert_eq!(+ actual, expected,+ "theme entries should be stable and sorted (builtins first, then custom by name)"+ );+ }++ #[test]+ fn parse_theme_name_is_exhaustive() {+ use two_face::theme::EmbeddedLazyThemeSet;++ // Every variant in the embedded set must be reachable via parse_theme_name.+ let all_variants = EmbeddedLazyThemeSet::theme_names();++ // Guard: if two-face adds themes, this test forces us to update the mapping.+ assert_eq!(+ all_variants.len(),+ 32,+ "two-face theme count changed — update parse_theme_name"+ );++ // Build the set of variants reachable through our kebab-case mapping.+ let kebab_names = [+ "ansi",+ "base16",+ "base16-eighties-dark",+ "base16-mocha-dark",+ "base16-ocean-dark",+ "base16-ocean-light",+ "base16-256",+ "catppuccin-frappe",+ "catppuccin-latte",+ "catppuccin-macchiato",+ "catppuccin-mocha",+ "coldark-cold",+ "coldark-dark",+ "dark-neon",+ "dracula",+ "github",+ "gruvbox-dark",+ "gruvbox-light",+ "inspired-github",+ "1337",+ "monokai-extended",+ "monokai-extended-bright",+ "monokai-extended-light",+ "monokai-extended-origin",+ "nord",+ "one-half-dark",+ "one-half-light",+ "solarized-dark",+ "solarized-light",+ "sublime-snazzy",+ "two-dark",+ "zenburn",+ ];+ let mapped: Vec<EmbeddedThemeName> = kebab_names+ .iter()+ .map(|k| parse_theme_name(k).unwrap_or_else(|| panic!("unmapped kebab name: {k}")))+ .collect();++ // Every variant from two-face must appear in our mapped set.+ for variant in all_variants {+ assert!(+ mapped.contains(variant),+ "EmbeddedThemeName::{variant:?} has no kebab-case mapping in parse_theme_name"+ );}- let body_style = body_style.expect("missing heredoc span");- assert!(body_style.add_modifier.contains(Modifier::DIM));}}diff --git a/codex-rs/tui/src/slash_command.rs b/codex-rs/tui/src/slash_command.rsindex 16e767f802..55fc01e90f 100644--- a/codex-rs/tui/src/slash_command.rs+++ b/codex-rs/tui/src/slash_command.rs@@ -37,6 +37,7 @@ pub enum SlashCommand {Status,DebugConfig,Statusline,+ Theme,Mcp,Apps,Logout,@@ -75,6 +76,7 @@ impl SlashCommand {SlashCommand::Status => "show current session configuration and token usage",SlashCommand::DebugConfig => "show config layers and requirement sources for debugging",SlashCommand::Statusline => "configure which items appear in the status line",+ SlashCommand::Theme => "choose a syntax highlighting theme",SlashCommand::Ps => "list background terminals",SlashCommand::Clean => "stop all background terminals",SlashCommand::MemoryDrop => "DO NOT USE",@@ -155,6 +157,7 @@ impl SlashCommand {SlashCommand::Collab => true,SlashCommand::Agent => true,SlashCommand::Statusline => false,+ SlashCommand::Theme => false,}}diff --git a/codex-rs/tui/src/snapshots/codex_tui__diff_render__tests__diff_gallery_120x40.snap b/codex-rs/tui/src/snapshots/codex_tui__diff_render__tests__diff_gallery_120x40.snapnew file mode 100644index 0000000000..07985926c4--- /dev/null+++ b/codex-rs/tui/src/snapshots/codex_tui__diff_render__tests__diff_gallery_120x40.snap@@ -0,0 +1,44 @@+---+source: tui/src/diff_render.rs+expression: terminal.backend()+---+"• Edited 6 files (+9 -9) "+" └ assets/banner.txt (+3 -0) "+" 1 +HEADER VALUE "+" 2 +rocket 🚀 " Hidden by multi-width symbols: [(15, " ")]+" 3 +city 東京 " Hidden by multi-width symbols: [(13, " "), (15, " ")]+" "+" └ examples/new_sample.rs (+3 -0) "+" 1 +pub fn greet(name: &str) { "+" 2 + println!("Hello, {name}!"); "+" 3 +} "+" "+" └ legacy/old_script.py (+0 -3) "+" 1 -def legacy(x): "+" 2 - return x + 1 "+" 3 -print(legacy(3)) "+" "+" └ scripts/calc.txt → scripts/calc.py (+1 -1) "+" 1 def add(a, b): "+" 2 - return a + b "+" 2 + return a + b + 42 "+" 3 "+" 4 print(add(1, 2)) "+" "+" └ src/lib.rs (+2 -2) "+" 1 fn greet(name: &str) { "+" 2 - println!("hello"); "+" 3 - println!("bye"); "+" 2 + println!("hello {name}"); "+" 3 + println!("emoji: 🚀✨ and CJK: 你好世界"); " Hidden by multi-width symbols: [(29, " "), (31, " "), (43, " "), (45, " "), (47, " "), (49, " ")]+" 4 } "+" "+" └ tmp/obsolete.log (+0 -3) "+" 1 -old line 1 "+" 2 -old line 2 "+" 3 -old line 3 "+" "+" "+" "+" "+" "diff --git a/codex-rs/tui/src/snapshots/codex_tui__diff_render__tests__diff_gallery_80x24.snap b/codex-rs/tui/src/snapshots/codex_tui__diff_render__tests__diff_gallery_80x24.snapnew file mode 100644index 0000000000..b3da476a2d--- /dev/null+++ b/codex-rs/tui/src/snapshots/codex_tui__diff_render__tests__diff_gallery_80x24.snap@@ -0,0 +1,28 @@+---+source: tui/src/diff_render.rs+expression: terminal.backend()+---+"• Edited 6 files (+9 -9) "+" └ assets/banner.txt (+3 -0) "+" 1 +HEADER VALUE "+" 2 +rocket 🚀 " Hidden by multi-width symbols: [(15, " ")]+" 3 +city 東京 " Hidden by multi-width symbols: [(13, " "), (15, " ")]+" "+" └ examples/new_sample.rs (+3 -0) "+" 1 +pub fn greet(name: &str) { "+" 2 + println!("Hello, {name}!"); "+" 3 +} "+" "+" └ legacy/old_script.py (+0 -3) "+" 1 -def legacy(x): "+" 2 - return x + 1 "+" 3 -print(legacy(3)) "+" "+" └ scripts/calc.txt → scripts/calc.py (+1 -1) "+" 1 def add(a, b): "+" 2 - return a + b "+" 2 + return a + b + 42 "+" 3 "+" 4 print(add(1, 2)) "+" "+" └ src/lib.rs (+2 -2) "diff --git a/codex-rs/tui/src/snapshots/codex_tui__diff_render__tests__diff_gallery_94x35.snap b/codex-rs/tui/src/snapshots/codex_tui__diff_render__tests__diff_gallery_94x35.snapnew file mode 100644index 0000000000..9eaffa6c91--- /dev/null+++ b/codex-rs/tui/src/snapshots/codex_tui__diff_render__tests__diff_gallery_94x35.snap@@ -0,0 +1,39 @@+---+source: tui/src/diff_render.rs+expression: terminal.backend()+---+"• Edited 6 files (+9 -9) "+" └ assets/banner.txt (+3 -0) "+" 1 +HEADER VALUE "+" 2 +rocket 🚀 " Hidden by multi-width symbols: [(15, " ")]+" 3 +city 東京 " Hidden by multi-width symbols: [(13, " "), (15, " ")]+" "+" └ examples/new_sample.rs (+3 -0) "+" 1 +pub fn greet(name: &str) { "+" 2 + println!("Hello, {name}!"); "+" 3 +} "+" "+" └ legacy/old_script.py (+0 -3) "+" 1 -def legacy(x): "+" 2 - return x + 1 "+" 3 -print(legacy(3)) "+" "+" └ scripts/calc.txt → scripts/calc.py (+1 -1) "+" 1 def add(a, b): "+" 2 - return a + b "+" 2 + return a + b + 42 "+" 3 "+" 4 print(add(1, 2)) "+" "+" └ src/lib.rs (+2 -2) "+" 1 fn greet(name: &str) { "+" 2 - println!("hello"); "+" 3 - println!("bye"); "+" 2 + println!("hello {name}"); "+" 3 + println!("emoji: 🚀✨ and CJK: 你好世界"); " Hidden by multi-width symbols: [(29, " "), (31, " "), (43, " "), (45, " "), (47, " "), (49, " ")]+" 4 } "+" "+" └ tmp/obsolete.log (+0 -3) "+" 1 -old line 1 "+" 2 -old line 2 "+" 3 -old line 3 "diff --git a/codex-rs/tui/src/snapshots/codex_tui__diff_render__tests__syntax_highlighted_insert_wraps.snap b/codex-rs/tui/src/snapshots/codex_tui__diff_render__tests__syntax_highlighted_insert_wraps.snapnew file mode 100644index 0000000000..ed0ff00518--- /dev/null+++ b/codex-rs/tui/src/snapshots/codex_tui__diff_render__tests__syntax_highlighted_insert_wraps.snap@@ -0,0 +1,14 @@+---+source: tui/src/diff_render.rs+expression: terminal.backend()+---+"1 +fn very_long_function_name(arg_one: String, arg_two: String, arg_three: Strin "+" g, arg_four: String) -> Result<String, Box<dyn std::error::Error>> { Ok(arg_o "+" ne) } "+" "+" "+" "+" "+" "+" "+" "diff --git a/codex-rs/tui/src/snapshots/codex_tui__diff_render__tests__syntax_highlighted_insert_wraps_text.snap b/codex-rs/tui/src/snapshots/codex_tui__diff_render__tests__syntax_highlighted_insert_wraps_text.snapnew file mode 100644index 0000000000..4555b79028--- /dev/null+++ b/codex-rs/tui/src/snapshots/codex_tui__diff_render__tests__syntax_highlighted_insert_wraps_text.snap@@ -0,0 +1,7 @@+---+source: tui/src/diff_render.rs+expression: text+---+1 +fn very_long_function_name(arg_one: String, arg_two: String, arg_three: Strin+ g, arg_four: String) -> Result<String, Box<dyn std::error::Error>> { Ok(arg_o+ ne) }diff --git a/codex-rs/tui/src/theme_picker.rs b/codex-rs/tui/src/theme_picker.rsnew file mode 100644index 0000000000..9205b5fb31--- /dev/null+++ b/codex-rs/tui/src/theme_picker.rs@@ -0,0 +1,620 @@+//! Builds the `/theme` picker dialog for the TUI.+//!+//! The picker lists all bundled themes plus any custom `.tmTheme` files found+//! under `{CODEX_HOME}/themes/`. It provides:+//!+//! - **Live preview:** the `on_selection_changed` callback swaps the runtime+//! syntax theme as the user navigates, giving instant visual feedback in both+//! the preview panel and any visible code blocks.+//! - **Cancel-restore:** on dismiss (Esc / Ctrl+C) the `on_cancel` callback+//! restores the theme snapshot taken when the picker opened.+//! - **Persist on confirm:** the `AppEvent::SyntaxThemeSelected` action persists+//! `[tui] theme = "..."` to `config.toml` via `ConfigEditsBuilder`.+//!+//! Two preview renderables adapt to terminal width:+//!+//! - `ThemePreviewWideRenderable` -- vertically centered, inset by 2 columns,+//! shown in the side panel when the terminal is wide enough for side-by-side+//! layout (>= 44-column side panel and >= 40-column list).+//! - `ThemePreviewNarrowRenderable` -- compact 4-line snippet stacked below the+//! list when side-by-side does not fit.++use std::path::Path;++use crate::app_event::AppEvent;+use crate::bottom_pane::SelectionItem;+use crate::bottom_pane::SelectionViewParams;+use crate::bottom_pane::SideContentWidth;+use crate::bottom_pane::popup_consts::standard_popup_hint_line;+use crate::bottom_pane::popup_content_width;+use crate::bottom_pane::side_by_side_layout_widths;+use crate::diff_render::DiffLineType;+use crate::diff_render::line_number_width;+use crate::diff_render::push_wrapped_diff_line;+use crate::diff_render::push_wrapped_diff_line_with_syntax;+use crate::render::highlight;+use crate::render::renderable::Renderable;+use crate::status::format_directory_display;+use ratatui::buffer::Buffer;+use ratatui::layout::Rect;+use ratatui::text::Line;+use ratatui::widgets::Widget;+use unicode_width::UnicodeWidthStr;++#[derive(Clone, Copy, Debug, Eq, PartialEq)]+enum PreviewDiffKind {+ Context,+ Added,+ Removed,+}++#[derive(Clone, Copy, Debug, Eq, PartialEq)]+struct PreviewRow {+ line_no: usize,+ kind: PreviewDiffKind,+ code: &'static str,+}++/// Compact fallback preview used in stacked (narrow) mode.+/// Keep exactly one removed and one added line visible at all times.+const NARROW_PREVIEW_ROWS: [PreviewRow; 4] = [+ PreviewRow {+ line_no: 12,+ kind: PreviewDiffKind::Context,+ code: "fn greet(name: &str) -> String {",+ },+ PreviewRow {+ line_no: 13,+ kind: PreviewDiffKind::Removed,+ code: " format!(\"Hello, {}!\", name)",+ },+ PreviewRow {+ line_no: 13,+ kind: PreviewDiffKind::Added,+ code: " format!(\"Hello, {name}!\")",+ },+ PreviewRow {+ line_no: 14,+ kind: PreviewDiffKind::Context,+ code: "}",+ },+];++/// Wider diff preview used in side-by-side mode.+/// This sample intentionally mixes context, additions, and removals.+const WIDE_PREVIEW_ROWS: [PreviewRow; 8] = [+ PreviewRow {+ line_no: 31,+ kind: PreviewDiffKind::Context,+ code: "fn summarize(users: &[User]) -> String {",+ },+ PreviewRow {+ line_no: 32,+ kind: PreviewDiffKind::Removed,+ code: " let active = users.iter().filter(|u| u.is_active).count();",+ },+ PreviewRow {+ line_no: 32,+ kind: PreviewDiffKind::Added,+ code: " let active = users.iter().filter(|u| u.is_active()).count();",+ },+ PreviewRow {+ line_no: 33,+ kind: PreviewDiffKind::Context,+ code: " let names: Vec<&str> = users.iter().map(User::name).take(3).collect();",+ },+ PreviewRow {+ line_no: 34,+ kind: PreviewDiffKind::Removed,+ code: " format!(\"{} active: {}\", active, names.join(\", \"))",+ },+ PreviewRow {+ line_no: 34,+ kind: PreviewDiffKind::Added,+ code: " format!(\"{active} active users: {}\", names.join(\", \"))",+ },+ PreviewRow {+ line_no: 35,+ kind: PreviewDiffKind::Added,+ code: " .trim()",+ },+ PreviewRow {+ line_no: 36,+ kind: PreviewDiffKind::Context,+ code: "}",+ },+];++/// Minimum side-panel width for side-by-side theme preview.+const WIDE_PREVIEW_MIN_WIDTH: u16 = 44;++/// Left inset used for wide preview content.+const WIDE_PREVIEW_LEFT_INSET: u16 = 2;++/// Minimum frame padding used for vertically centered wide preview.+const PREVIEW_FRAME_PADDING: u16 = 1;++const PREVIEW_FALLBACK_SUBTITLE: &str = "Move up/down to live preview themes";++/// Side-by-side preview: syntax-highlighted Rust diff snippet, vertically+/// centered with a 2-column left inset. Fills the entire side panel height.+struct ThemePreviewWideRenderable;++/// Stacked preview: compact 4-line Rust diff snippet shown below the list+/// when the terminal is too narrow for side-by-side layout.+struct ThemePreviewNarrowRenderable;++fn preview_diff_line_type(kind: PreviewDiffKind) -> DiffLineType {+ match kind {+ PreviewDiffKind::Context => DiffLineType::Context,+ PreviewDiffKind::Added => DiffLineType::Insert,+ PreviewDiffKind::Removed => DiffLineType::Delete,+ }+}++fn centered_offset(available: u16, content: u16, min_frame: u16) -> u16 {+ let free = available.saturating_sub(content);+ let frame = if free >= min_frame.saturating_mul(2) {+ min_frame+ } else {+ 0+ };+ frame + free.saturating_sub(frame.saturating_mul(2)) / 2+}++fn render_preview(+ area: Rect,+ buf: &mut Buffer,+ preview_rows: &[PreviewRow],+ center_vertically: bool,+ left_inset: u16,+) {+ if area.height == 0 || area.width == 0 {+ return;+ }+ if preview_rows.is_empty() {+ return;+ }+ let preview_code = preview_rows+ .iter()+ .map(|row| row.code)+ .collect::<Vec<_>>()+ .join("\n");+ let syntax_lines = highlight::highlight_code_to_styled_spans(&preview_code, "rust");++ let max_line_no = preview_rows+ .iter()+ .map(|row| row.line_no)+ .max()+ .unwrap_or(1);+ let ln_width = line_number_width(max_line_no);++ let content_height = (preview_rows.len() as u16).min(area.height);++ let left_pad = left_inset.min(area.width.saturating_sub(1));+ let top_pad = if center_vertically {+ centered_offset(area.height, content_height, PREVIEW_FRAME_PADDING)+ } else {+ 0+ };++ let mut y = area.y.saturating_add(top_pad);+ let render_width = area.width.saturating_sub(left_pad);+ for (idx, row) in preview_rows.iter().enumerate() {+ if y >= area.y + area.height {+ break;+ }+ let diff_type = preview_diff_line_type(row.kind);+ let wrapped = if let Some(syn) = syntax_lines.as_ref().and_then(|sl| sl.get(idx)) {+ push_wrapped_diff_line_with_syntax(+ row.line_no,+ diff_type,+ row.code,+ render_width as usize,+ ln_width,+ syn,+ )+ } else {+ push_wrapped_diff_line(+ row.line_no,+ diff_type,+ row.code,+ render_width as usize,+ ln_width,+ )+ };+ let first_line = wrapped.into_iter().next().unwrap_or_else(|| Line::from(""));+ first_line.render(+ Rect::new(area.x.saturating_add(left_pad), y, render_width, 1),+ buf,+ );+ y += 1;+ }+}++impl Renderable for ThemePreviewWideRenderable {+ fn desired_height(&self, _width: u16) -> u16 {+ u16::MAX+ }++ fn render(&self, area: Rect, buf: &mut Buffer) {+ render_preview(area, buf, &WIDE_PREVIEW_ROWS, true, WIDE_PREVIEW_LEFT_INSET);+ }+}++impl Renderable for ThemePreviewNarrowRenderable {+ fn desired_height(&self, _width: u16) -> u16 {+ NARROW_PREVIEW_ROWS.len() as u16+ }++ fn render(&self, area: Rect, buf: &mut Buffer) {+ render_preview(area, buf, &NARROW_PREVIEW_ROWS, false, 0);+ }+}++fn subtitle_available_width(terminal_width: Option<u16>) -> usize {+ let width = terminal_width.unwrap_or(80);+ let content_width = popup_content_width(width);+ if let Some((list_width, _side_width)) = side_by_side_layout_widths(+ content_width,+ SideContentWidth::Half,+ WIDE_PREVIEW_MIN_WIDTH,+ ) {+ list_width as usize+ } else {+ content_width as usize+ }+}++fn theme_picker_subtitle(codex_home: Option<&Path>, terminal_width: Option<u16>) -> String {+ let themes_dir = codex_home.map(|home| home.join("themes"));+ let themes_dir_display = themes_dir+ .as_deref()+ .map(|path| format_directory_display(path, None));+ let available_width = subtitle_available_width(terminal_width);++ if let Some(path) = themes_dir_display+ && path.starts_with('~')+ {+ let subtitle = format!("Custom .tmTheme files can be added to the {path} directory.");+ if UnicodeWidthStr::width(subtitle.as_str()) <= available_width {+ return subtitle;+ }+ }++ PREVIEW_FALLBACK_SUBTITLE.to_string()+}++/// Builds [`SelectionViewParams`] for the `/theme` picker dialog.+///+/// Lists all bundled themes plus custom `.tmTheme` files, with live preview+/// on cursor movement and cancel-restore.+///+/// `current_name` should be the value of `Config::tui_theme` (the persisted+/// preference). When it names a theme that is currently available the picker+/// pre-selects it; otherwise the picker falls back to the configured name (or+/// adaptive default) so opening the picker without a persisted preference still+/// highlights the most likely intended entry.+pub(crate) fn build_theme_picker_params(+ current_name: Option<&str>,+ codex_home: Option<&Path>,+ terminal_width: Option<u16>,+) -> SelectionViewParams {+ // Snapshot the current theme so we can restore on cancel.+ let original_theme = highlight::current_syntax_theme();++ let entries = highlight::list_available_themes(codex_home);+ let codex_home_owned = codex_home.map(Path::to_path_buf);++ // Resolve the effective theme name: honor explicit config only when it is+ // currently available; otherwise fall back to configured/default selection+ // so opening `/theme` does not auto-preview an unrelated first entry.+ let effective_name = if let Some(name) = current_name+ && entries.iter().any(|entry| entry.name == name)+ {+ name.to_string()+ } else {+ highlight::configured_theme_name()+ };++ // Track the index of the current theme so we can pre-select it.+ let mut initial_idx = None;++ let items: Vec<SelectionItem> = entries+ .iter()+ .enumerate()+ .map(|(idx, entry)| {+ let display_name = if entry.is_custom {+ format!("{} (custom)", entry.name)+ } else {+ entry.name.clone()+ };+ let is_current = entry.name == effective_name;+ if is_current {+ initial_idx = Some(idx);+ }+ let name_for_action = entry.name.clone();+ SelectionItem {+ name: display_name,+ is_current,+ dismiss_on_select: true,+ search_value: Some(entry.name.clone()),+ actions: vec![Box::new(move |tx| {+ tx.send(AppEvent::SyntaxThemeSelected {+ name: name_for_action.clone(),+ });+ })],+ ..Default::default()+ }+ })+ .collect();++ // Derive preview targets from the final `items` list (not from `entries`)+ // so preview ordering stays aligned if item construction/sorting changes.+ let preview_theme_names: Vec<Option<String>> =+ items.iter().map(|item| item.search_value.clone()).collect();+ let preview_home = codex_home_owned.clone();+ let on_selection_changed = Some(Box::new(move |idx: usize, _tx: &_| {+ if let Some(Some(name)) = preview_theme_names.get(idx)+ && let Some(theme) = highlight::resolve_theme_by_name(name, preview_home.as_deref())+ {+ highlight::set_syntax_theme(theme);+ }+ })+ as Box<dyn Fn(usize, &crate::app_event_sender::AppEventSender) + Send + Sync>);++ // Restore original theme on cancel.+ let on_cancel = Some(Box::new(move |_tx: &_| {+ highlight::set_syntax_theme(original_theme.clone());+ })+ as Box<dyn Fn(&crate::app_event_sender::AppEventSender) + Send + Sync>);+ SelectionViewParams {+ title: Some("Select Syntax Theme".to_string()),+ subtitle: Some(theme_picker_subtitle(+ codex_home_owned.as_deref(),+ terminal_width,+ )),+ footer_hint: Some(standard_popup_hint_line()),+ items,+ is_searchable: true,+ search_placeholder: Some("Type to filter themes...".to_string()),+ initial_selected_idx: initial_idx,+ side_content: Box::new(ThemePreviewWideRenderable),+ side_content_width: SideContentWidth::Half,+ side_content_min_width: WIDE_PREVIEW_MIN_WIDTH,+ stacked_side_content: Some(Box::new(ThemePreviewNarrowRenderable)),+ on_selection_changed,+ on_cancel,+ ..Default::default()+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use pretty_assertions::assert_eq;+ use ratatui::style::Modifier;++ fn render_buffer(renderable: &dyn Renderable, width: u16, height: u16) -> Buffer {+ let area = Rect::new(0, 0, width, height);+ let mut buf = Buffer::empty(area);+ renderable.render(area, &mut buf);+ buf+ }++ fn render_lines(renderable: &dyn Renderable, width: u16, height: u16) -> Vec<String> {+ let buf = render_buffer(renderable, width, height);+ (0..height)+ .map(|row| {+ let mut line = String::new();+ for col in 0..width {+ let symbol = buf[(col, row)].symbol();+ if symbol.is_empty() {+ line.push(' ');+ } else {+ line.push_str(symbol);+ }+ }+ line+ })+ .collect()+ }++ fn first_non_space_style_after_marker(buf: &Buffer, row: u16, width: u16) -> Option<Modifier> {+ let marker_col = (0..width)+ .find(|&col| buf[(col, row)].symbol() == "-" || buf[(col, row)].symbol() == "+")?;+ for col in marker_col + 1..width {+ if buf[(col, row)].symbol() != " " {+ return Some(buf[(col, row)].style().add_modifier);+ }+ }+ None+ }++ fn preview_line_number(line: &str) -> Option<usize> {+ let trimmed = line.trim_start();+ let digits_len = trimmed.chars().take_while(char::is_ascii_digit).count();+ if digits_len == 0 {+ return None;+ }+ let digits = &trimmed[..digits_len];+ if !trimmed[digits_len..].starts_with(' ') {+ return None;+ }+ digits.parse::<usize>().ok()+ }++ fn preview_line_marker(line: &str) -> Option<char> {+ let trimmed = line.trim_start();+ let digits_len = trimmed.chars().take_while(char::is_ascii_digit).count();+ if digits_len == 0 {+ return None;+ }+ let mut chars = trimmed[digits_len..].chars();+ if chars.next()? != ' ' {+ return None;+ }+ chars.next()+ }++ #[test]+ fn theme_picker_uses_half_width_with_stacked_fallback_preview() {+ let params = build_theme_picker_params(None, None, None);+ assert_eq!(params.side_content_width, SideContentWidth::Half);+ assert_eq!(params.side_content_min_width, WIDE_PREVIEW_MIN_WIDTH);+ assert!(params.stacked_side_content.is_some());+ }++ #[test]+ fn theme_picker_items_include_search_values_for_preview_mapping() {+ let params = build_theme_picker_params(None, None, None);+ assert!(+ params.items.iter().all(|item| item.search_value.is_some()),+ "theme picker preview mapping relies on item search_value to stay aligned with final item order"+ );+ }++ #[test]+ fn wide_preview_renders_all_lines_with_vertical_center_and_left_inset() {+ let lines = render_lines(&ThemePreviewWideRenderable, 80, 20);+ let numbered_rows: Vec<usize> = lines+ .iter()+ .enumerate()+ .filter_map(|(idx, line)| preview_line_number(line).map(|_| idx))+ .collect();+ let total_preview_lines = WIDE_PREVIEW_ROWS.len();++ assert_eq!(numbered_rows.len(), total_preview_lines);+ let first_row = *numbered_rows+ .first()+ .expect("expected at least one preview row");+ let last_row = *numbered_rows+ .last()+ .expect("expected at least one preview row");+ assert!(+ first_row > 0,+ "expected top padding before centered preview"+ );+ assert!(+ last_row < 19,+ "expected bottom padding after centered preview"+ );++ let first_line = &lines[first_row];+ assert!(+ first_line.starts_with(" 31 fn summarize"),+ "expected wide preview to start after a 2-char inset"+ );++ let markers: Vec<char> = lines+ .iter()+ .filter_map(|line| preview_line_marker(line))+ .collect();+ assert!(+ markers.contains(&'+'),+ "expected wide preview to include at least one addition line"+ );+ assert!(+ markers.contains(&'-'),+ "expected wide preview to include at least one removal line"+ );+ }++ #[test]+ fn narrow_preview_renders_single_add_and_single_remove_in_four_lines() {+ let lines = render_lines(&ThemePreviewNarrowRenderable, 80, 6);+ let numbered_lines: Vec<usize> = lines+ .iter()+ .filter_map(|line| preview_line_number(line))+ .collect();+ let markers: Vec<char> = lines+ .iter()+ .filter_map(|line| preview_line_marker(line))+ .collect();++ assert_eq!(numbered_lines, vec![12, 13, 13, 14]);+ assert_eq!(markers.len(), 4);+ assert_eq!(markers.iter().filter(|&&m| m == '+').count(), 1);+ assert_eq!(markers.iter().filter(|&&m| m == '-').count(), 1);+ let first_numbered = lines+ .iter()+ .find(|line| preview_line_number(line).is_some())+ .expect("expected at least one rendered preview row");+ assert!(+ first_numbered.starts_with("12 fn greet"),+ "expected narrow preview line numbers to start at the left edge"+ );+ }++ #[test]+ fn deleted_preview_code_uses_dim_overlay_like_real_diff_renderer() {+ let width = 80;+ let height = 6;+ let buf = render_buffer(&ThemePreviewNarrowRenderable, width, height);+ let lines = render_lines(&ThemePreviewNarrowRenderable, width, height);+ let deleted_row = lines+ .iter()+ .enumerate()+ .find_map(|(row, line)| (preview_line_marker(line) == Some('-')).then_some(row as u16))+ .expect("expected a deleted preview row");+ let modifiers = first_non_space_style_after_marker(&buf, deleted_row, width)+ .expect("expected code text after diff marker");+ assert!(+ modifiers.contains(Modifier::DIM),+ "expected deleted preview code to be dimmed"+ );+ }++ #[test]+ fn subtitle_uses_tilde_path_when_codex_home_under_home_directory() {+ let home = dirs::home_dir().expect("home directory should be available");+ let codex_home = home.join(".codex");++ let subtitle = theme_picker_subtitle(Some(&codex_home), Some(200));++ assert!(subtitle.contains("~"));+ assert!(subtitle.contains("directory"));+ }++ #[test]+ fn subtitle_falls_back_when_tilde_path_subtitle_is_too_wide() {+ let home = dirs::home_dir().expect("home directory should be available");+ let long_segment = "a".repeat(120);+ let codex_home = home.join(long_segment).join(".codex");++ let subtitle = theme_picker_subtitle(Some(&codex_home), Some(140));++ assert_eq!(subtitle, PREVIEW_FALLBACK_SUBTITLE);+ }++ #[test]+ fn subtitle_falls_back_to_preview_instructions_without_tilde_path() {+ let subtitle = theme_picker_subtitle(None, None);+ assert_eq!(subtitle, PREVIEW_FALLBACK_SUBTITLE);+ }++ #[test]+ fn subtitle_falls_back_for_94_column_terminal_side_by_side_layout() {+ let home = dirs::home_dir().expect("home directory should be available");+ let codex_home = home.join(".codex");++ let subtitle = theme_picker_subtitle(Some(&codex_home), Some(94));++ assert_eq!(subtitle, PREVIEW_FALLBACK_SUBTITLE);+ }++ #[test]+ fn unavailable_configured_theme_falls_back_to_configured_or_default_selection() {+ let configured_or_default_theme = highlight::configured_theme_name();+ let params = build_theme_picker_params(Some("not-a-real-theme"), None, Some(120));+ let selected_idx = params+ .initial_selected_idx+ .expect("expected selected index for active fallback theme");+ let selected_name = params.items[selected_idx]+ .search_value+ .as_deref()+ .expect("expected search value to contain canonical theme name");++ assert_eq!(selected_name, configured_or_default_theme);+ }+}