Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

wrap long lines in code blocks instead of cutting them off (#3304)

Sebastian Müllerf20664507eda
diff --git a/.changes/fix-code-fence-wrap.md b/.changes/fix-code-fence-wrap.md
new file mode 100644
index 0000000000..87c51a6b3d
--- /dev/null
+++ b/.changes/fix-code-fence-wrap.md
@@ -0,0 +1 @@
+- Long lines inside fenced code blocks now wrap onto the next row instead of being cut off at the edge of the terminal.
diff --git a/crates/pa-tui/src/markdown.rs b/crates/pa-tui/src/markdown.rs
index 6a04e8adf4..65b7fa3eec 100644
--- a/crates/pa-tui/src/markdown.rs
+++ b/crates/pa-tui/src/markdown.rs
@@ -480,6 +480,31 @@ fn highlighted_code_lines(
))
}
+/// The block's unwrapped rows (TS `renderCodeBlock`): the indent outside
+/// each highlighted or uniform code line; an empty block is one indented
+/// empty row. Paint wraps these rows and the count measures the same rows.
+fn code_rows(block: &Block, lang: Option<&str>, style: &MarkdownStyle) -> Vec<Line> {
+ let indent = style.code_block_indent.as_str();
+ let lines = highlighted_code_lines(block, lang, style).unwrap_or_else(|| {
+ block
+ .lines
+ .iter()
+ .map(|line| vec![Span::styled(line.clone(), style.code_block)])
+ .collect()
+ });
+ if lines.is_empty() {
+ return vec![vec![Span::raw(indent)]];
+ }
+ lines
+ .into_iter()
+ .map(|line| {
+ let mut row: Line = vec![Span::raw(indent)];
+ row.extend(line);
+ row
+ })
+ .collect()
+}
+
/// Heading spans: inline-rendered, tapered to the heading color with
/// the link affordance kept — an underlined label stays underlined and
/// the URL bracket keeps its dim `link_url` slot, tracked by origin
@@ -547,29 +572,11 @@ fn render_block(
// outside the styled code line, each source line rendered with
// the codeBlock style. The theme's `codeBlockBorder` hook exists
// in the TS MarkdownTheme too and is unused by the renderer on
- // both sides.
- let indent = style.code_block_indent.as_str();
- match highlighted_code_lines(block, lang.as_deref(), style) {
- Some(code_lines) => {
- for line in code_lines {
- let mut row: Line = vec![Span::raw(indent)];
- row.extend(line);
- out.push(row);
- }
- }
- None => {
- for line in &block.lines {
- out.push(vec![
- Span::raw(indent),
- Span::styled(line.clone(), style.code_block),
- ]);
- }
- }
- }
- if block.lines.is_empty() {
- // An empty block still renders one indented empty line
- // (TS maps a lone codeBlock("")).
- out.push(vec![Span::raw(indent)]);
+ // both sides. TS `renderBlock` then wraps every code row
+ // (wrapTextWithAnsi), so a continuation row starts at column 0
+ // with no re-added indent.
+ for row in code_rows(block, lang.as_deref(), style) {
+ wrap_spans(&row, width, style.code_block, out);
}
if blank_after(false) {
out.push(Vec::new());
diff --git a/crates/pa-tui/src/markdown/geometry.rs b/crates/pa-tui/src/markdown/geometry.rs
index 2deeabbfbc..92ae2ad5ae 100644
--- a/crates/pa-tui/src/markdown/geometry.rs
+++ b/crates/pa-tui/src/markdown/geometry.rs
@@ -1,7 +1,7 @@
//! Geometry uses the same wrapping traversal as painted Markdown rows.
use super::{
- block_cache_key, heading_spans, parse_blocks, render_inline, wrapped_span_count, Block,
- BlockKind, MarkdownBlockCache, MarkdownStyle,
+ block_cache_key, code_rows, heading_spans, parse_blocks, render_inline, wrapped_span_count,
+ Block, BlockKind, MarkdownBlockCache, MarkdownStyle,
};
use crate::{Line, Span};
use ratatui::style::Style;
@@ -66,11 +66,12 @@ pub(super) fn blank_after(next: Option<&Block>, exclude_lists: bool) -> bool {
}
}
-/// Count rows without painting output buffers or syntax highlighting.
-/// A non-empty `cache` replays the block's painted rows: the count==paint
-/// invariant holds by construction (the cached rows ARE what the render
-/// emits for the same key). The cache is only read — a cold cache costs
-/// what [`markdown_row_count`] costs.
+/// Count rows without collecting the painted rows; fenced code measures
+/// the same (highlighted) rows the paint wraps. A non-empty `cache`
+/// replays the block's painted rows: the count==paint invariant holds by
+/// construction (the cached rows ARE what the render emits for the same
+/// key). The cache is only read — a cold cache costs what
+/// [`markdown_row_count`] costs.
pub(crate) fn markdown_row_count_tagged(
text: &str,
width: usize,
@@ -105,8 +106,12 @@ pub(crate) fn markdown_row_count_tagged(
+ usize::from(blank_after(next, false))
}
BlockKind::Hr => 1,
- BlockKind::Code { .. } => {
- block.lines.len().max(1) + usize::from(blank_after(next, false))
+ BlockKind::Code { lang } => {
+ code_rows(block, lang.as_deref(), style)
+ .iter()
+ .map(|row| wrapped_span_count(row, width))
+ .sum::<usize>()
+ + usize::from(blank_after(next, false))
}
BlockKind::Paragraph => {
block
diff --git a/crates/pa-tui/src/markdown/tests.rs b/crates/pa-tui/src/markdown/tests.rs
index 4b45055f21..d2f7b72dcb 100644
--- a/crates/pa-tui/src/markdown/tests.rs
+++ b/crates/pa-tui/src/markdown/tests.rs
@@ -544,6 +544,32 @@ fn python_fence_multiline_string_carries_across_rows() {
assert_eq!(lines[1][1].style, string);
}
+#[test]
+fn long_code_rows_wrap_at_the_width() {
+ // TS renderBlock wraps every code row (wrapTextWithAnsi): the indent
+ // leads the first row only and no code text is lost.
+ let style = MarkdownStyle::default();
+ let code = (0..50)
+ .map(|i| format!("f({i}, 'x')"))
+ .collect::<Vec<_>>()
+ .join(" ");
+ for fence in ["```", "```python"] {
+ let text = format!("intro\n\n{fence}\n{code}\n```\n\nafter");
+ let rows: Vec<String> = render_markdown(&text, 40, &style)
+ .iter()
+ .map(|row| row.iter().map(|s| s.content.as_str()).collect())
+ .collect();
+ let code_rows = &rows[2..rows.len() - 2];
+ assert!(
+ code_rows[0].starts_with(" f(0,") && !code_rows[1].starts_with(' '),
+ "{rows:?}"
+ );
+ assert!(code_rows.iter().all(|row| str_width(row) <= 40), "{rows:?}");
+ assert_eq!(code_rows.concat().replace(' ', ""), code.replace(' ', ""));
+ assert_eq!(markdown_row_count(&text, 40, &style), rows.len());
+ }
+}
+
#[test]
fn list_render() {
let style = MarkdownStyle::default();