Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

Add independent TUI rendering toggles for Mermaid, math, and tables (#46938)

Eric Trauta86631502d49
diff --git a/codex-rs/config/src/lib.rs b/codex-rs/config/src/lib.rs
index 3197988f78..6da94a301d 100644
--- a/codex-rs/config/src/lib.rs
+++ b/codex-rs/config/src/lib.rs
@@ -44,6 +44,7 @@ pub mod test_support;
mod thread_config;
mod tui_effects;
mod tui_keymap;
+mod tui_rendering;
pub mod types;
pub const CONFIG_TOML_FILE: &str = "config.toml";
diff --git a/codex-rs/config/src/tui_rendering.rs b/codex-rs/config/src/tui_rendering.rs
new file mode 100644
index 0000000000..ea4a313024
--- /dev/null
+++ b/codex-rs/config/src/tui_rendering.rs
@@ -0,0 +1,28 @@
+//! TUI content rendering preferences, independent of animation effects.
+
+use schemars::JsonSchema;
+use serde::Deserialize;
+use serde::Serialize;
+
+/// Optional rich renderers. Disabled renderers preserve the original source.
+#[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialEq, Eq, JsonSchema)]
+#[serde(default)]
+#[schemars(deny_unknown_fields)]
+pub struct TuiRendering {
+ /// Render Mermaid code blocks as diagrams.
+ pub mermaid: bool,
+ /// Render math expressions using Unicode notation.
+ pub math: bool,
+ /// Render pipe tables, including tables inside Markdown fences.
+ pub tables: bool,
+}
+
+impl Default for TuiRendering {
+ fn default() -> Self {
+ Self {
+ mermaid: true,
+ math: true,
+ tables: true,
+ }
+ }
+}
diff --git a/codex-rs/config/src/types.rs b/codex-rs/config/src/types.rs
index a03851e4d5..96a0222d6b 100644
--- a/codex-rs/config/src/types.rs
+++ b/codex-rs/config/src/types.rs
@@ -47,6 +47,7 @@ pub use crate::tui_keymap::TuiPagerKeymap;
pub use crate::tui_keymap::TuiVimNormalKeymap;
pub use crate::tui_keymap::TuiVimOperatorKeymap;
pub use crate::tui_keymap::TuiVimSearchKeymap;
+pub use crate::tui_rendering::TuiRendering;
pub const DEFAULT_OTEL_ENVIRONMENT: &str = "dev";
pub const DEFAULT_MEMORIES_MAX_ROLLOUTS_PER_STARTUP: usize = 2;
@@ -758,6 +759,10 @@ pub struct Tui {
#[serde(default)]
pub effects: TuiEffects,
+ /// Rich content rendering. Independent of animations and visual effects.
+ #[serde(default)]
+ pub rendering: TuiRendering,
+
/// Show startup tooltips in the TUI welcome screen.
/// Defaults to `true`.
#[serde(default = "default_true")]
diff --git a/codex-rs/config/src/types_tests.rs b/codex-rs/config/src/types_tests.rs
index 3e1082a07b..0503dd41d3 100644
--- a/codex-rs/config/src/types_tests.rs
+++ b/codex-rs/config/src/types_tests.rs
@@ -104,3 +104,19 @@ fn memories_version_selects_pipeline_without_changing_other_defaults() {
}
assert!(toml::from_str::<MemoriesToml>("version = \"v3\"").is_err());
}
+
+#[test]
+fn rendering_preferences_default_individually_and_ignore_animation_switch() {
+ for key in ["mermaid", "math", "tables"] {
+ let tui: Tui =
+ toml::from_str(&format!("animations = false\n[rendering]\n{key} = false\n")).unwrap();
+ assert_eq!(
+ tui.rendering,
+ TuiRendering {
+ mermaid: key != "mermaid",
+ math: key != "math",
+ tables: key != "tables",
+ }
+ );
+ }
+}
diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json
index f3138968a7..6e834902ec 100644
--- a/codex-rs/core/config.schema.json
+++ b/codex-rs/core/config.schema.json
@@ -4479,6 +4479,19 @@
"description": "Start the TUI in raw scrollback mode for copy-friendly transcript output. Defaults to `false`.",
"type": "boolean"
},
+ "rendering": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/TuiRendering"
+ }
+ ],
+ "default": {
+ "math": true,
+ "mermaid": true,
+ "tables": true
+ },
+ "description": "Rich content rendering. Independent of animations and visual effects."
+ },
"resume_cwd": {
"allOf": [
{
@@ -5612,6 +5625,28 @@
}
]
},
+ "TuiRendering": {
+ "additionalProperties": false,
+ "description": "Optional rich renderers. Disabled renderers preserve the original source.",
+ "properties": {
+ "math": {
+ "default": true,
+ "description": "Render math expressions using Unicode notation.",
+ "type": "boolean"
+ },
+ "mermaid": {
+ "default": true,
+ "description": "Render Mermaid code blocks as diagrams.",
+ "type": "boolean"
+ },
+ "tables": {
+ "default": true,
+ "description": "Render pipe tables, including tables inside Markdown fences.",
+ "type": "boolean"
+ }
+ },
+ "type": "object"
+ },
"TuiVimNormalKeymap": {
"additionalProperties": false,
"description": "Vim normal-mode keybindings for modal editing inside text areas.\n\nActions that use uppercase letters (like `A` for append-line-end) should be specified as `shift-a` in config; the runtime matcher handles cross-terminal shift-reporting differences automatically.",
diff --git a/codex-rs/core/src/config/config_tests.rs b/codex-rs/core/src/config/config_tests.rs
index 4af6772d10..0bf3dcf638 100644
--- a/codex-rs/core/src/config/config_tests.rs
+++ b/codex-rs/core/src/config/config_tests.rs
@@ -1254,6 +1254,7 @@ fn config_toml_deserializes_model_availability_nux() {
animations: true,
screen_reader_detection_done: None,
effects: Default::default(),
+ rendering: Default::default(),
show_tooltips: true,
show_server_version_notice: true,
auto_recap: true,
@@ -4382,6 +4383,7 @@ fn tui_config_missing_notifications_field_defaults_to_enabled() {
animations: true,
screen_reader_detection_done: None,
effects: Default::default(),
+ rendering: Default::default(),
show_tooltips: true,
show_server_version_notice: true,
auto_recap: true,
diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs
index 7b6ec2d393..e71ad88dde 100644
--- a/codex-rs/core/src/config/mod.rs
+++ b/codex-rs/core/src/config/mod.rs
@@ -751,6 +751,9 @@ pub struct Config {
/// Individual TUI effects, subordinate to the animation master switch.
pub tui_effects: codex_config::types::TuiEffects,
+ /// Rich content rendering preferences, independent of animations.
+ pub tui_rendering: codex_config::types::TuiRendering,
+
/// Show startup tooltips in the TUI welcome screen.
pub show_tooltips: bool,
@@ -4386,6 +4389,7 @@ impl Config {
.unwrap_or_default(),
animations: cfg.tui.as_ref().map(|t| t.animations).unwrap_or(true),
tui_effects: cfg.tui.as_ref().map(|t| t.effects).unwrap_or_default(),
+ tui_rendering: cfg.tui.as_ref().map(|t| t.rendering).unwrap_or_default(),
show_tooltips: cfg.tui.as_ref().map(|t| t.show_tooltips).unwrap_or(true),
tui_show_server_version_notice: cfg
.tui
diff --git a/codex-rs/thread-manager-sample/src/main.rs b/codex-rs/thread-manager-sample/src/main.rs
index f6ac386fb7..1bcf5d15f3 100644
--- a/codex-rs/thread-manager-sample/src/main.rs
+++ b/codex-rs/thread-manager-sample/src/main.rs
@@ -228,6 +228,7 @@ fn new_config(model: Option<String>, arg0_paths: Arg0DispatchPaths) -> anyhow::R
tui_notifications: TuiNotificationSettings::default(),
animations: true,
tui_effects: Default::default(),
+ tui_rendering: Default::default(),
show_tooltips: true,
tui_show_server_version_notice: true,
tui_auto_recap: true,
diff --git a/codex-rs/tui/src/app/agents_overview_details.rs b/codex-rs/tui/src/app/agents_overview_details.rs
index bc1249270e..03b3c9b14c 100644
--- a/codex-rs/tui/src/app/agents_overview_details.rs
+++ b/codex-rs/tui/src/app/agents_overview_details.rs
@@ -23,7 +23,7 @@ use std::collections::HashMap;
const PREVIEW_CHARS: usize = 512;
pub(super) fn preview_agent_message(text: &str) -> String {
- preview_markdown(&crate::markdown::unwrap_markdown_fences(text))
+ preview_markdown(&crate::markdown::normalize_markdown_for_rendering(text))
}
pub(super) fn preview_markdown(text: &str) -> String {
diff --git a/codex-rs/tui/src/app/agents_overview_view.rs b/codex-rs/tui/src/app/agents_overview_view.rs
index b39734b128..489a3562f3 100644
--- a/codex-rs/tui/src/app/agents_overview_view.rs
+++ b/codex-rs/tui/src/app/agents_overview_view.rs
@@ -430,7 +430,7 @@ impl AgentsOverviewView {
if let Some((message, cwd)) = &row.details.last_message {
details.extend([Line::default(), "Last message".dim().into()]);
crate::markdown::append_markdown(
- &crate::markdown::unwrap_markdown_fences(message),
+ &crate::markdown::normalize_markdown_for_rendering(message),
Some(width),
Some(cwd.as_path()),
&mut details,
diff --git a/codex-rs/tui/src/app/config_persistence.rs b/codex-rs/tui/src/app/config_persistence.rs
index b6cb2f1160..e6d4136046 100644
--- a/codex-rs/tui/src/app/config_persistence.rs
+++ b/codex-rs/tui/src/app/config_persistence.rs
@@ -1885,6 +1885,8 @@ theme = "dracula"
let mut tui = crate::tui::test_support::make_test_tui()?;
app.sync_tui_theme_selection("dracula".to_string());
app.chat_widget.requires_openai_auth = false;
+ crate::markdown_render::preferences::init(Default::default());
+ app.local_settings.tui.rendering.math = false;
let mut legacy_config = app.config.clone();
legacy_config.tui_theme = Some("nord".to_string());
legacy_config.model_provider.requires_openai_auth = true;
@@ -1896,6 +1898,12 @@ theme = "dracula"
let replacement = ChatWidget::new_with_app_event(init);
assert_eq!(replacement.local_settings, app.local_settings);
assert!(!replacement.requires_openai_auth);
+ app.replace_chat_widget(replacement);
+ let source = r"Math: \(x^2\)";
+ assert_eq!(
+ crate::markdown_render::render_markdown_text(source).to_string(),
+ source
+ );
Ok(())
}
diff --git a/codex-rs/tui/src/app/session_lifecycle.rs b/codex-rs/tui/src/app/session_lifecycle.rs
index e4bc4c9879..bcf9d75fef 100644
--- a/codex-rs/tui/src/app/session_lifecycle.rs
+++ b/codex-rs/tui/src/app/session_lifecycle.rs
@@ -519,6 +519,7 @@ impl App {
);
}
chat_widget.restore_kill_buffer_snapshot(self.chat_widget.take_kill_buffer_snapshot());
+ crate::markdown_render::preferences::init(chat_widget.local_settings.tui.rendering);
self.chat_widget = chat_widget;
self.sync_active_agent_label();
}
diff --git a/codex-rs/tui/src/clipboard_html_tests.rs b/codex-rs/tui/src/clipboard_html_tests.rs
index 2c478244dd..9df27e4d7c 100644
--- a/codex-rs/tui/src/clipboard_html_tests.rs
+++ b/codex-rs/tui/src/clipboard_html_tests.rs
@@ -68,10 +68,16 @@ fn markdown_clipboard_escapes_raw_html_and_rejects_unsafe_destinations() {
}
#[test]
-fn markdown_clipboard_unwraps_table_fences_like_the_tui() {
+fn markdown_clipboard_unwraps_table_fences_independent_of_tui_preferences() {
let table = "| Item | Result |\n| --- | --- |\n| Copy | Formatted |\n";
- assert_eq!(
- render_markdown(&format!("```markdown\n{table}```")),
- render_markdown(table)
- );
+ for tables in [true, false] {
+ crate::markdown_render::preferences::init(codex_config::types::TuiRendering {
+ tables,
+ ..Default::default()
+ });
+ assert_eq!(
+ render_markdown(&format!("```markdown\n{table}```")),
+ render_markdown(table)
+ );
+ }
}
diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs
index 01a73daf55..83f5c1a43f 100644
--- a/codex-rs/tui/src/lib.rs
+++ b/codex-rs/tui/src/lib.rs
@@ -1372,6 +1372,7 @@ async fn run_ratatui_app(
})
};
+ crate::markdown_render::preferences::init(config.tui_rendering);
// Startup pickers need the current theme before selection can reload config.
// Leave the one-time override initialization below to use the final config.
if (cli.resume_picker || cli.fork_picker)
@@ -1869,6 +1870,7 @@ async fn run_ratatui_app(
}
let local_settings = crate::local_settings::LocalSettings::for_tui(&config, &tui);
+ crate::markdown_render::preferences::init(local_settings.tui.rendering);
// 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.
diff --git a/codex-rs/tui/src/local_settings.rs b/codex-rs/tui/src/local_settings.rs
index f60e5f5d8f..aab16143cc 100644
--- a/codex-rs/tui/src/local_settings.rs
+++ b/codex-rs/tui/src/local_settings.rs
@@ -63,6 +63,7 @@ impl LocalSettings {
animations: animations && system_motion == crate::motion::MotionMode::Animated,
screen_reader_detection_done: None,
effects: config.tui_effects,
+ rendering: config.tui_rendering,
show_tooltips: config.show_tooltips,
show_server_version_notice: config.tui_show_server_version_notice,
auto_recap: config.tui_auto_recap,
diff --git a/codex-rs/tui/src/local_settings_tests.rs b/codex-rs/tui/src/local_settings_tests.rs
index cef866fbd4..05c58073b7 100644
--- a/codex-rs/tui/src/local_settings_tests.rs
+++ b/codex-rs/tui/src/local_settings_tests.rs
@@ -104,6 +104,10 @@ terminal_resize_reflow_max_rows = 0
session_picker_view = "comfortable"
[tui.effects]
shimmer = false
+[tui.rendering]
+mermaid = false
+math = false
+tables = false
[history]
persistence = "none"
max_bytes = 4096
@@ -138,6 +142,11 @@ fast_default_opt_out = true
if !config_text.is_empty() {
expected.animations = false;
expected.effects.shimmer = false;
+ expected.rendering = codex_config::types::TuiRendering {
+ mermaid: false,
+ math: false,
+ tables: false,
+ };
expected.show_tooltips = false;
expected.show_server_version_notice = false;
expected.auto_recap = false;
diff --git a/codex-rs/tui/src/markdown.rs b/codex-rs/tui/src/markdown.rs
index 240cadb538..2d4db67f55 100644
--- a/codex-rs/tui/src/markdown.rs
+++ b/codex-rs/tui/src/markdown.rs
@@ -6,9 +6,9 @@
//! - [`append_markdown`] -- general-purpose, used for plan blocks and history
//! cells that already hold pre-processed markdown (no fence unwrapping).
//! - [`append_markdown_agent`] -- for agent responses. Runs
-//! [`unwrap_markdown_fences`] first so that `` ```md ``/`` ```markdown ``
+//! [`normalize_markdown_for_rendering`] first so that `` ```md ``/`` ```markdown ``
//! fences containing tables are stripped and `pulldown-cmark` sees raw
-//! table syntax instead of fenced code.
+//! table syntax instead of fenced code, when `tui.rendering.tables` is enabled.
//!
//! ## Why fence unwrapping exists
//!
@@ -65,7 +65,7 @@ pub(crate) fn append_markdown_agent(
width: Option<usize>,
lines: &mut Vec<Line<'static>>,
) {
- let normalized = unwrap_markdown_fences(markdown_source);
+ let normalized = normalize_markdown_for_rendering(markdown_source);
let rendered = crate::markdown_render::render_markdown_text_with_width_and_cwd(
&normalized,
width,
@@ -97,7 +97,7 @@ pub(crate) fn render_markdown_agent_with_list_spacing(
list_spacing: ListSpacing,
) -> Vec<HyperlinkLine> {
let rewritten = rewrite_inline_visualizations(markdown_source, inline_visualization_context);
- let normalized = unwrap_markdown_fences(&rewritten.markdown);
+ let normalized = normalize_markdown_for_rendering(&rewritten.markdown);
let is_hidden_link_destination = |destination: &str| {
rewritten.trusted_file_links.contains_key(destination)
|| crate::markdown_render::hide_web_link_destination(destination)
@@ -129,7 +129,7 @@ pub(crate) fn render_streaming_markdown_agent_with_links_and_cwd(
cwd: Option<&Path>,
list_spacing: ListSpacing,
) -> crate::markdown_render::StreamingMarkdownRender {
- let normalized = unwrap_markdown_fences(markdown_source);
+ let normalized = normalize_markdown_for_rendering(markdown_source);
let mut rendered = crate::markdown_render::render_streaming_markdown_lines_with_width_and_cwd(
&normalized,
width,
@@ -150,7 +150,7 @@ pub(crate) fn render_streaming_markdown_agent_with_links_and_cwd(
.last_top_level_block_start
.and_then(|boundary| markdown_source.strip_suffix(&normalized[boundary..]))
.map(str::len);
- rendered.mermaid_start = rendered.mermaid_start.map(|boundary| {
+ rendered.mutable_fence_start = rendered.mutable_fence_start.map(|boundary| {
markdown_source
.strip_suffix(&normalized[boundary..])
.map_or(0, str::len)
@@ -246,6 +246,15 @@ pub(crate) fn extract_copy_targets(markdown_source: &str) -> Vec<CopyTarget> {
targets
}
+/// Apply table-fence normalization only when terminal table layouts are enabled.
+pub(crate) fn normalize_markdown_for_rendering(markdown_source: &str) -> Cow<'_, str> {
+ if crate::markdown_render::preferences::current().tables {
+ unwrap_markdown_fences(markdown_source)
+ } else {
+ Cow::Borrowed(markdown_source)
+ }
+}
+
/// Strip `` ```md ``/`` ```markdown `` fences that contain tables, emitting their content as bare
/// markdown so `pulldown-cmark` parses the tables natively.
///
diff --git a/codex-rs/tui/src/markdown_render.rs b/codex-rs/tui/src/markdown_render.rs
index 3ab4574ef6..bea1e2923e 100644
--- a/codex-rs/tui/src/markdown_render.rs
+++ b/codex-rs/tui/src/markdown_render.rs
@@ -3,7 +3,7 @@
//! This module consumes `pulldown-cmark` events and emits styled `ratatui`
//! lines, including table layout, Mermaid previews, width-aware wrapping, and local file-link
//! display. It is the final rendering stage used by higher-level helpers in
-//! `markdown.rs`.
+//! `markdown.rs`. Launch-time `tui.rendering` preferences preserve disabled features as source.
//!
//! Local file-link parsing and display policy live in [`local_links`].
//! List spacing stays a renderer policy: compact while streaming in an owned viewport, uniform
@@ -78,6 +78,8 @@ mod list_spacing;
mod local_links;
mod math;
mod mermaid;
+pub(crate) mod preferences;
+mod source_tables;
mod streaming;
mod table_key_value;
mod web_links;
@@ -366,9 +368,10 @@ pub(crate) fn render_markdown_lines_with_width_cwd_and_hidden_link_destinations(
options.insert(Options::ENABLE_STRIKETHROUGH);
options.insert(Options::ENABLE_TABLES);
let math = math::MathMarkdown::new(input, options, width);
- let parser = DecodedTextMerge::new(
+ let parser = DecodedTextMerge::new(source_tables::preserve(
+ input,
math.events(Parser::new_ext(&math.markdown, options).into_offset_iter()),
- );
+ ));
let mut w = Writer::new(input, parser, width, cwd, is_hidden_link_destination);
w.run();
w.text
@@ -956,7 +959,8 @@ where
if let Some(lang) = self.code_block_lang.take() {
let code = std::mem::take(&mut self.code_block_buffer);
if !code.is_empty() {
- let diagram = if lang == "mermaid"
+ let diagram = if preferences::current().mermaid
+ && lang == "mermaid"
&& mermaid::has_closing_fence(self.input, range, self.code_block_content_end)
{
let indent =
diff --git a/codex-rs/tui/src/markdown_render/math.rs b/codex-rs/tui/src/markdown_render/math.rs
index 3ac9a1d7df..fc012aec1e 100644
--- a/codex-rs/tui/src/markdown_render/math.rs
+++ b/codex-rs/tui/src/markdown_render/math.rs
@@ -221,7 +221,7 @@ impl<'a> MathMarkdown<'a> {
continue;
}
}
- let rendered = if formula.len() < MAX_MATH_BYTES {
+ let rendered = if super::preferences::current().math && formula.len() < MAX_MATH_BYTES {
render::render(formula, display)
} else {
None
diff --git a/codex-rs/tui/src/markdown_render/preferences.rs b/codex-rs/tui/src/markdown_render/preferences.rs
new file mode 100644
index 0000000000..464b13ace1
--- /dev/null
+++ b/codex-rs/tui/src/markdown_render/preferences.rs
@@ -0,0 +1,43 @@
+//! Content preferences shared by streaming and completed Markdown renderers.
+//!
+//! Seed before startup previews, then refresh when resolved session settings become active.
+//! Tests isolate preferences per thread so parallel renderer tests cannot affect one another.
+
+use codex_config::types::TuiRendering;
+
+#[cfg(not(test))]
+static RENDERING: std::sync::LazyLock<std::sync::RwLock<TuiRendering>> =
+ std::sync::LazyLock::new(|| std::sync::RwLock::new(TuiRendering::default()));
+
+#[cfg(test)]
+thread_local! {
+ static RENDERING: std::cell::Cell<TuiRendering> = std::cell::Cell::new(TuiRendering::default());
+}
+
+pub(crate) fn init(rendering: TuiRendering) {
+ #[cfg(not(test))]
+ {
+ *RENDERING
+ .write()
+ .unwrap_or_else(std::sync::PoisonError::into_inner) = rendering;
+ }
+ #[cfg(test)]
+ RENDERING.set(rendering);
+}
+
+pub(crate) fn current() -> TuiRendering {
+ #[cfg(not(test))]
+ {
+ *RENDERING
+ .read()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ }
+ #[cfg(test)]
+ {
+ RENDERING.get()
+ }
+}
+
+#[cfg(test)]
+#[path = "preferences_tests.rs"]
+mod tests;
diff --git a/codex-rs/tui/src/markdown_render/preferences_tests.rs b/codex-rs/tui/src/markdown_render/preferences_tests.rs
new file mode 100644
index 0000000000..4dd7fa4810
--- /dev/null
+++ b/codex-rs/tui/src/markdown_render/preferences_tests.rs
@@ -0,0 +1,87 @@
+use super::init;
+use crate::markdown::render_streaming_markdown_agent_with_links_and_cwd;
+use crate::markdown_render::render_markdown_text;
+use crate::terminal_hyperlinks::visible_lines;
+use codex_config::types::TuiRendering;
+use pretty_assertions::assert_eq;
+use ratatui::text::Text;
+
+#[test]
+fn disabled_renderers_preserve_source_independently() {
+ let samples = [
+ "```mermaid\nflowchart LR\nA[Request] --> B[Reply]\n```\n",
+ "Inline $\\alpha_1$ and \\(x^{2}\\).\n\n\\[\n\\frac{a}{b}\n\\]\n",
+ "| **Name** | Value |\n|---|---|\n| `a` | path\\_1 &amp; \\* |\n",
+ ];
+ let defaults = samples.map(render_markdown_text);
+ let mut snapshot = Vec::new();
+ for rendering in [
+ TuiRendering {
+ mermaid: false,
+ ..Default::default()
+ },
+ TuiRendering {
+ math: false,
+ ..Default::default()
+ },
+ TuiRendering {
+ tables: false,
+ ..Default::default()
+ },
+ ] {
+ init(rendering);
+ for (index, source) in samples.iter().enumerate() {
+ let rendered = render_markdown_text(source);
+ if [rendering.mermaid, rendering.math, rendering.tables][index] {
+ assert_eq!(rendered, defaults[index]);
+ } else {
+ snapshot.push(format!("{rendering:?}\n{rendered}"));
+ }
+ }
+ }
+ insta::assert_snapshot!(snapshot.join("\n\n---\n\n"));
+}
+
+#[test]
+fn disabled_tables_keep_markdown_fences_and_cell_markup() {
+ init(TuiRendering {
+ tables: false,
+ ..Default::default()
+ });
+ for fence in [
+ "```md",
+ "```markdown",
+ "~~~markdown",
+ "```MARKDOWN title=example",
+ ] {
+ let closer = &fence[..3];
+ let source = format!("{fence}\n| A | B |\n|---|---|\n| **a** | $x^2$ |\n{closer}\n");
+ assert_eq!(render_markdown_text(&source).to_string(), source.trim_end());
+ }
+ let quoted =
+ "> ```md\n> Intro\n>\n>| A | B |\n> |---|---|\n> | a | b |\n>\n>> literal\n> ```\n";
+ let rendered = render_markdown_text(quoted).to_string();
+ insta::assert_snapshot!("disabled_tables_keep_mixed_quote_spacing", rendered);
+ let streamed = render_streaming_markdown_agent_with_links_and_cwd(
+ quoted,
+ /*width*/ None,
+ /*cwd*/ None,
+ crate::markdown_render::ListSpacing::AfterMultiline,
+ );
+ assert_eq!(
+ Text::from(visible_lines(streamed.lines)).to_string(),
+ rendered
+ );
+ // Four-space continuation indentation must not hide the table inside a list fence.
+ for (marker, indent) in [("1. ", " "), ("> > 1. ", ">> ")] {
+ let listed = format!(
+ "{marker}```md\n{indent}| A | B |\n{indent}|---|---|\n{indent}| a | b |\n{indent}```\n"
+ );
+ let text = render_markdown_text(&listed).to_string();
+ assert!(text.contains("```md"));
+ assert_eq!(text.matches("```").count(), 2);
+ assert!(text.contains("| a | b |"));
+ }
+ let prose = "```markdown\n**Not a table**\n```\n";
+ assert_eq!(render_markdown_text(prose).to_string(), "**Not a table**");
+}
diff --git a/codex-rs/tui/src/markdown_render/snapshots/codex_tui__markdown_render__preferences__tests__disabled_renderers_preserve_source_independently.snap b/codex-rs/tui/src/markdown_render/snapshots/codex_tui__markdown_render__preferences__tests__disabled_renderers_preserve_source_independently.snap
new file mode 100644
index 0000000000..ddb4487d76
--- /dev/null
+++ b/codex-rs/tui/src/markdown_render/snapshots/codex_tui__markdown_render__preferences__tests__disabled_renderers_preserve_source_independently.snap
@@ -0,0 +1,24 @@
+---
+source: tui/src/markdown_render/preferences_tests.rs
+assertion_line: 34
+expression: "snapshot.join(\"\\n\\n---\\n\\n\")"
+---
+TuiRendering { mermaid: false, math: true, tables: true }
+flowchart LR
+A[Request] --> B[Reply]
+
+---
+
+TuiRendering { mermaid: true, math: false, tables: true }
+Inline $\alpha_1$ and \(x^{2}\).
+
+\[
+\frac{a}{b}
+\]
+
+---
+
+TuiRendering { mermaid: true, math: true, tables: false }
+| **Name** | Value |
+|---|---|
+| `a` | path\_1 &amp; \* |
diff --git a/codex-rs/tui/src/markdown_render/snapshots/codex_tui__markdown_render__preferences__tests__disabled_tables_keep_mixed_quote_spacing.snap b/codex-rs/tui/src/markdown_render/snapshots/codex_tui__markdown_render__preferences__tests__disabled_tables_keep_mixed_quote_spacing.snap
new file mode 100644
index 0000000000..f75b891590
--- /dev/null
+++ b/codex-rs/tui/src/markdown_render/snapshots/codex_tui__markdown_render__preferences__tests__disabled_tables_keep_mixed_quote_spacing.snap
@@ -0,0 +1,13 @@
+---
+source: tui/src/markdown_render/preferences_tests.rs
+expression: rendered
+---
+> ```md
+> Intro
+>
+> | A | B |
+> |---|---|
+> | a | b |
+>
+> > literal
+> ```
diff --git a/codex-rs/tui/src/markdown_render/source_tables.rs b/codex-rs/tui/src/markdown_render/source_tables.rs
new file mode 100644
index 0000000000..b92b88442e
--- /dev/null
+++ b/codex-rs/tui/src/markdown_render/source_tables.rs
@@ -0,0 +1,97 @@
+//! Restore disabled tables as literal blocks before the writer consumes inline Markdown events.
+//!
+//! Keep parser offsets and block boundaries intact, including Markdown fences around tables.
+
+use itertools::Either;
+use pulldown_cmark::CodeBlockKind;
+use pulldown_cmark::Event;
+use pulldown_cmark::Options;
+use pulldown_cmark::Parser;
+use pulldown_cmark::Tag;
+use pulldown_cmark::TagEnd;
+use std::ops::Range;
+
+pub(super) fn preserve<'a>(
+ input: &'a str,
+ events: impl Iterator<Item = (Event<'a>, Range<usize>)>,
+) -> impl Iterator<Item = (Event<'a>, Range<usize>)> {
+ let enabled = super::preferences::current().tables;
+ let mut skipped_end = None;
+ events.flat_map(move |(event, range)| {
+ if let Some(end) = skipped_end {
+ if matches!(&event, Event::End(tag) if *tag == end) {
+ skipped_end = None;
+ }
+ return Either::Right(None.into_iter());
+ }
+ let end = match &event {
+ Event::Start(Tag::Table(_)) if !enabled => Some(TagEnd::Table),
+ Event::Start(Tag::CodeBlock(CodeBlockKind::Fenced(info)))
+ if !enabled
+ && crate::table_detect::is_markdown_fence_info(info, /*marker_len*/ 0) =>
+ {
+ Some(TagEnd::CodeBlock)
+ }
+ _ => None,
+ };
+ if let Some(end) = end {
+ // The first line's container prefix is outside the parser range. Strip matching
+ // continuation prefixes so the writer's list/quote indentation is applied once.
+ let prefix = input[..range.start].rsplit('\n').next().unwrap_or_default();
+ let indent = " ".repeat(prefix.len());
+ let source = input[range.clone()]
+ .split_inclusive('\n')
+ .enumerate()
+ .map(|(index, line)| {
+ if index == 0 {
+ line
+ } else if let Some(line) = line.strip_prefix(prefix) {
+ line
+ } else if let Some((_, suffix)) = prefix.rsplit_once('>') {
+ // Only enclosing quotes are structural; further markers and newlines
+ // belong to the literal fence body.
+ let mut rest = line;
+ for _ in prefix.matches('>') {
+ let Some(content) =
+ rest.trim_start_matches([' ', '\t']).strip_prefix('>')
+ else {
+ break;
+ };
+ rest = content.strip_prefix(' ').unwrap_or(content);
+ }
+ // Remove only the enclosing list/fence indentation after the final quote.
+ for _ in 0..suffix.strip_prefix(' ').unwrap_or(suffix).len() {
+ rest = rest.strip_prefix(' ').unwrap_or(rest);
+ }
+ rest
+ } else {
+ line.strip_prefix(&indent).unwrap_or(line)
+ }
+ })
+ .collect::<String>();
+ if end == TagEnd::CodeBlock
+ && !source.split_once('\n').is_some_and(|(_, body)| {
+ Parser::new_ext(body, Options::ENABLE_TABLES)
+ .any(|event| matches!(event, Event::Start(Tag::Table(_))))
+ })
+ {
+ return Either::Right(Some((event, range)).into_iter());
+ }
+ skipped_end = Some(end);
+ let kind = match event {
+ Event::Start(Tag::CodeBlock(kind)) => kind,
+ _ => CodeBlockKind::Fenced("".into()),
+ };
+ Either::Left(
+ [
+ (Event::Start(Tag::CodeBlock(kind)), range.clone()),
+ (Event::Text(source.into()), range.clone()),
+ (Event::End(TagEnd::CodeBlock), range),
+ ]
+ .into_iter(),
+ )
+ } else {
+ Either::Right(Some((event, range)).into_iter())
+ }
+ })
+}
diff --git a/codex-rs/tui/src/markdown_render/streaming.rs b/codex-rs/tui/src/markdown_render/streaming.rs
index 3bf0123c08..5f65fc5868 100644
--- a/codex-rs/tui/src/markdown_render/streaming.rs
+++ b/codex-rs/tui/src/markdown_render/streaming.rs
@@ -28,8 +28,8 @@ pub(crate) struct StreamingMarkdownRender {
pub(crate) has_reference_link_definition: bool,
/// Whether the first block is raw HTML, which joins a retained prefix without a separator.
pub(crate) first_top_level_block_is_html: bool,
- /// Mermaid in the final top-level block stays mutable, including within a list or quote.
- pub(crate) mermaid_start: Option<usize>,
+ /// Transformable fences in the final block stay mutable, including within a list or quote.
+ pub(crate) mutable_fence_start: Option<usize>,
}
/// Render `input` while tracking the final mutable top-level block.
@@ -51,12 +51,15 @@ pub(crate) fn render_streaming_markdown_lines_with_width_and_cwd(
let parser = Parser::new_ext(&math.markdown, options);
let has_reference_link_definition = parser.reference_definitions().iter().next().is_some();
let parser = TopLevelBlockTracker {
- iter: DecodedTextMerge::new(citations.events(math.events(parser.into_offset_iter()), cwd)),
+ iter: DecodedTextMerge::new(super::source_tables::preserve(
+ input,
+ citations.events(math.events(parser.into_offset_iter()), cwd),
+ )),
depth: 0,
block_count: 0,
last_start: 0,
first_is_html: false,
- mermaid_start: None,
+ mutable_fence_start: None,
};
let mut writer = Writer::new(input, parser, width, cwd, is_hidden_link_destination);
writer.list_spacing = list_spacing;
@@ -75,7 +78,7 @@ pub(crate) fn render_streaming_markdown_lines_with_width_and_cwd(
}),
has_reference_link_definition,
first_top_level_block_is_html: writer.iter.first_is_html,
- mermaid_start: writer.iter.mermaid_start,
+ mutable_fence_start: writer.iter.mutable_fence_start,
}
}
@@ -86,7 +89,7 @@ struct TopLevelBlockTracker<I> {
block_count: usize,
last_start: usize,
first_is_html: bool,
- mermaid_start: Option<usize>,
+ mutable_fence_start: Option<usize>,
}
impl<'a, I> Iterator for TopLevelBlockTracker<I>
@@ -98,7 +101,7 @@ where
fn next(&mut self) -> Option<Self::Item> {
let (event, range) = self.iter.next()?;
if self.depth == 0 && matches!(&event, Event::Start(_) | Event::Rule | Event::Html(_)) {
- self.mermaid_start = None;
+ self.mutable_fence_start = None;
self.block_count += 1;
self.last_start = range.start;
if self.block_count == 1 {
@@ -107,9 +110,12 @@ where
}
}
if let Event::Start(Tag::CodeBlock(pulldown_cmark::CodeBlockKind::Fenced(info))) = &event
- && info.split([',', ' ', '\t']).next() == Some("mermaid")
+ && (super::preferences::current().mermaid
+ && info.split([',', ' ', '\t']).next() == Some("mermaid")
+ || !super::preferences::current().tables
+ && crate::table_detect::is_markdown_fence_info(info, /*marker_len*/ 0))
{
- self.mermaid_start.get_or_insert(self.last_start);
+ self.mutable_fence_start.get_or_insert(self.last_start);
}
match event {
Event::Start(_) => self.depth += 1,
diff --git a/codex-rs/tui/src/streaming/code_fence.rs b/codex-rs/tui/src/streaming/code_fence.rs
index 24cd36a005..42597bf9ec 100644
--- a/codex-rs/tui/src/streaming/code_fence.rs
+++ b/codex-rs/tui/src/streaming/code_fence.rs
@@ -49,6 +49,12 @@ impl OpenCodeFence {
.split([',', ' ', '\t'])
.next()
.filter(|language| !language.is_empty())?;
+ // Markdown fences may gain visible delimiters when a disabled table is recognized.
+ if !crate::markdown_render::preferences::current().tables
+ && crate::table_detect::is_markdown_fence_info(info, /*marker_len*/ 0)
+ {
+ return None;
+ }
// Retain at most one bounded language token, never the streamed code itself.
if language.len() > MAX_HIGHLIGHT_LINE_BYTES
|| has_possible_closing_line(code, marker, marker_len)
diff --git a/codex-rs/tui/src/streaming/controller.rs b/codex-rs/tui/src/streaming/controller.rs
index 660f3e984a..aff21d1472 100644
--- a/codex-rs/tui/src/streaming/controller.rs
+++ b/codex-rs/tui/src/streaming/controller.rs
@@ -19,7 +19,8 @@
//! agent and proposed-plan streams. Lines in `Outside` and `Markdown` fence
//! contexts are scanned; lines inside non-markdown fences are skipped.
//!
-//! Mermaid stays mutable while its containing top-level block is last. The closing fence replaces
+//! Transformable fences stay mutable while their containing top-level block is last. Markdown
+//! fences may gain literal delimiters when table rendering is disabled. For Mermaid, the closing fence replaces
//! source with a diagram, and resizing can replace a diagram that no longer fits with its source.
//! Once another block starts, the diagram enters scrollback so later prose does not grow the tail.
//!
@@ -422,7 +423,7 @@ impl StreamCore {
};
[
table_start,
- self.render.mermaid_start,
+ self.render.mutable_fence_start,
self.render.pending_math_start,
]
.into_iter()
@@ -2081,3 +2082,7 @@ mod tests {
);
}
}
+
+#[cfg(test)]
+#[path = "rendering_preferences_tests.rs"]
+mod rendering_preferences_tests;
diff --git a/codex-rs/tui/src/streaming/mermaid_tests.rs b/codex-rs/tui/src/streaming/mermaid_tests.rs
index d6f67587c2..8ff2613043 100644
--- a/codex-rs/tui/src/streaming/mermaid_tests.rs
+++ b/codex-rs/tui/src/streaming/mermaid_tests.rs
@@ -107,7 +107,7 @@ fn mermaid_holdback_tracks_nested_blocks_after_normalized_markdown() {
/*inline_visualization_context*/ None,
);
}
- assert_eq!(render.mermaid_start, Some(prefix.len()));
+ assert_eq!(render.mutable_fence_start, Some(prefix.len()));
render.recompute(
&source,
Some(80),
@@ -115,7 +115,7 @@ fn mermaid_holdback_tracks_nested_blocks_after_normalized_markdown() {
HistoryRenderMode::Rich,
/*inline_visualization_context*/ None,
);
- assert_eq!(render.mermaid_start, Some(prefix.len()));
+ assert_eq!(render.mutable_fence_start, Some(prefix.len()));
let continuation = "\nAfter.\n\n";
source.push_str(continuation);
render.append(
@@ -126,7 +126,7 @@ fn mermaid_holdback_tracks_nested_blocks_after_normalized_markdown() {
HistoryRenderMode::Rich,
/*inline_visualization_context*/ None,
);
- assert_eq!(render.mermaid_start, None);
+ assert_eq!(render.mutable_fence_start, None);
render.recompute(
&source,
Some(80),
@@ -134,7 +134,7 @@ fn mermaid_holdback_tracks_nested_blocks_after_normalized_markdown() {
HistoryRenderMode::Rich,
/*inline_visualization_context*/ None,
);
- assert_eq!(render.mermaid_start, None);
+ assert_eq!(render.mutable_fence_start, None);
}
}
diff --git a/codex-rs/tui/src/streaming/render.rs b/codex-rs/tui/src/streaming/render.rs
index 9fa26f7a8f..1322895dce 100644
--- a/codex-rs/tui/src/streaming/render.rs
+++ b/codex-rs/tui/src/streaming/render.rs
@@ -25,7 +25,7 @@ pub(super) struct StreamingRender {
pub(super) list_spacing: ListSpacing,
pub(super) lines: Vec<HyperlinkLine>,
pub(super) pending_math_start: Option<usize>,
- pub(super) mermaid_start: Option<usize>,
+ pub(super) mutable_fence_start: Option<usize>,
/// Source prefix containing only completed top-level markdown blocks.
stable_source_len: usize,
/// Rendered-line boundary corresponding to `stable_source_len`.
@@ -44,7 +44,7 @@ impl StreamingRender {
list_spacing: ListSpacing::AfterMultiline,
lines: Vec::with_capacity(64),
pending_math_start: None,
- mermaid_start: None,
+ mutable_fence_start: None,
stable_source_len: 0,
stable_rendered_len: 0,
has_reference_link_definition: false,
@@ -56,7 +56,7 @@ impl StreamingRender {
pub(super) fn clear(&mut self) {
self.lines.clear();
self.pending_math_start = None;
- self.mermaid_start = None;
+ self.mutable_fence_start = None;
self.stable_source_len = 0;
self.stable_rendered_len = 0;
self.has_reference_link_definition = false;
@@ -78,7 +78,7 @@ impl StreamingRender {
) {
self.open_code_fence = None;
self.pending_math_start = None;
- self.mermaid_start = None;
+ self.mutable_fence_start = None;
self.has_inline_visualization_directive = contains_inline_visualization(source);
self.lines = match (render_mode, inline_visualization_context) {
(HistoryRenderMode::Rich, None) if !self.has_inline_visualization_directive => {
@@ -90,7 +90,7 @@ impl StreamingRender {
);
self.has_reference_link_definition = rendered.has_reference_link_definition;
self.pending_math_start = rendered.pending_math_start;
- self.mermaid_start = rendered.mermaid_start;
+ self.mutable_fence_start = rendered.mutable_fence_start;
rendered.lines
}
_ => {
@@ -103,7 +103,7 @@ impl StreamingRender {
self.list_spacing,
);
self.pending_math_start = rendered.pending_math_start;
- self.mermaid_start = rendered.mermaid_start;
+ self.mutable_fence_start = rendered.mutable_fence_start;
}
render_source_with_list_spacing(
source,
@@ -184,8 +184,8 @@ impl StreamingRender {
self.pending_math_start = pending
.pending_math_start
.map(|start| self.stable_source_len + start);
- self.mermaid_start = pending
- .mermaid_start
+ self.mutable_fence_start = pending
+ .mutable_fence_start
.map(|start| self.stable_source_len + start);
if pending.has_reference_link_definition {
self.has_reference_link_definition = true;
diff --git a/codex-rs/tui/src/streaming/rendering_preferences_tests.rs b/codex-rs/tui/src/streaming/rendering_preferences_tests.rs
new file mode 100644
index 0000000000..3ad25d0638
--- /dev/null
+++ b/codex-rs/tui/src/streaming/rendering_preferences_tests.rs
@@ -0,0 +1,86 @@
+use super::StreamCore;
+use super::render_source;
+use crate::history_cell::HistoryRenderMode;
+use crate::markdown_render::preferences;
+use codex_config::types::TuiRendering;
+use pretty_assertions::assert_eq;
+
+#[test]
+fn rendering_preferences_match_incremental_final_and_emitted_responses() {
+ let cwd = std::env::temp_dir();
+ let source = concat!(
+ "Before.\n\n",
+ "```markdown\n| A | B |\n|---|---|\n| `a` | \\(x_1\\) |\n```\n\n",
+ "```mermaid\nflowchart LR\nA --> B\n```\n\n",
+ "Inline \\(\\alpha_1\\) and $x^2$.\n\n\\[\n\\frac{a}{b}\n\\]\n\n",
+ "| Name | Value |\n|---|---|\n| **a** | $x^2$ |\n\n",
+ "Prose after the table.\n\nOne.\n\nTwo.\n\nThree.\n\nFour.\n\n",
+ "| **Name** | Value |\n|---|---|\n| `a` | b |\n\nAfter.\n"
+ );
+ for mermaid in [true, false] {
+ for math in [true, false] {
+ for tables in [true, false] {
+ preferences::init(TuiRendering {
+ mermaid,
+ math,
+ tables,
+ });
+ // A disabled table must retain even the prose preceding it inside its fence.
+ let mut source = if tables {
+ source.to_owned()
+ } else {
+ source.replacen(
+ "```markdown\n",
+ "```markdown\nIntro inside fence.\n\n",
+ /*count*/ 1,
+ )
+ };
+ if !math {
+ // A later protected code block can reject provisional math masking even
+ // without Unicode conversion, so the pending expression must stay mutable.
+ source.insert_str(
+ /*idx*/ 0,
+ "$$\n# heading\none\ntwo\nthree\nfour\nfive\n```rust\nx\n```\n$$\n\n",
+ );
+ }
+ let mut stream = StreamCore::new(
+ Some(80),
+ &cwd,
+ HistoryRenderMode::Rich,
+ /*inline_visualization_context*/ None,
+ );
+ let render = |source: &str| {
+ render_source(
+ source,
+ Some(80),
+ &cwd,
+ HistoryRenderMode::Rich,
+ /*inline_visualization_context*/ None,
+ )
+ };
+ let mut emitted = Vec::new();
+ let mut committed = String::new();
+ for chunk in source.split_inclusive('\n') {
+ committed.push_str(chunk);
+ stream.push_delta(chunk);
+ emitted.extend(stream.tick_batch(usize::MAX));
+ assert_eq!(
+ stream.render.lines,
+ render(&committed),
+ "{mermaid}/{math}/{tables}: {committed}"
+ );
+ }
+ if !tables {
+ assert!(
+ emitted
+ .iter()
+ .any(|line| line.line.to_string() == "Prose after the table.")
+ );
+ }
+ let (remaining, _) = stream.finalize_remaining();
+ emitted.extend(remaining);
+ assert_eq!(emitted, render(&source), "{mermaid}/{math}/{tables}");
+ }
+ }
+ }
+}
diff --git a/codex-rs/tui/src/streaming/table_holdback.rs b/codex-rs/tui/src/streaming/table_holdback.rs
index e53da7bcaf..7a7f92eb69 100644
--- a/codex-rs/tui/src/streaming/table_holdback.rs
+++ b/codex-rs/tui/src/streaming/table_holdback.rs
@@ -3,6 +3,7 @@
//! Agent streams with markdown tables keep the active table as mutable tail so
//! adding a row can reflow earlier table rows instead of committing a stale
//! render to scrollback.
+//! Literal tables only retain candidate headers until their delimiter arrives.
//!
//! The scanner is intentionally conservative: it only looks for enough
//! structure to decide where the mutable tail should start. It does not try to
@@ -148,8 +149,10 @@ impl TableHoldbackScanner {
&& previous_line.is_header
&& is_delimiter
{
- self.confirmed_table_start
- .get_or_insert(previous_line.source_start);
+ if crate::markdown_render::preferences::current().tables {
+ self.confirmed_table_start
+ .get_or_insert(previous_line.source_start);
+ }
self.pending_header_start = None;
self.in_table = true;
}