Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
Prefix read_file tool output with line numbers (#56779)
MartinYe1234cfd0461b5a93
diff --git a/crates/agent/src/outline.rs b/crates/agent/src/outline.rsindex 6a204e7694a..82592355295 100644--- a/crates/agent/src/outline.rs+++ b/crates/agent/src/outline.rs@@ -11,10 +11,15 @@ pub const AUTO_OUTLINE_SIZE: usize = 16384;/// Result of getting buffer content, which can be either full content or an outline.pub struct BufferContent {- /// The actual content (either full text or outline)+ /// The actual content (either full text, a symbol outline, or a+ /// truncated fallback — see `is_synthetic`).pub text: String,- /// Whether this is an outline (true) or full content (false)- pub is_outline: bool,+ /// `true` when `text` is not the file's full content — either a symbol+ /// outline or the truncated first-1KB fallback used when no outline is+ /// available. Callers that prefix line numbers to file content must+ /// skip prefixing in this case, because line numbers in `text` would+ /// not correspond to the file's real line numbers.+ pub is_synthetic: bool,}/// Returns either the full content of a buffer or its outline, depending on size.@@ -44,7 +49,10 @@ pub async fn get_buffer_content_or_outline(.collect::<Vec<_>>()});- // If no outline exists, fall back to first 1KB so the agent has some context+ // If no outline exists, fall back to first 1KB so the agent has some context.+ // This is reported as `is_synthetic: true` because the returned text is not+ // the file's full content — it has a synthetic header and is truncated — so+ // callers must not attach real-file line numbers to it.if outline_items.is_empty() {let text = buffer.read_with(cx, |buffer, _| {let snapshot = buffer.snapshot();@@ -59,7 +67,7 @@ pub async fn get_buffer_content_or_outline(return Ok(BufferContent {text,- is_outline: false,+ is_synthetic: true,});}@@ -72,14 +80,14 @@ pub async fn get_buffer_content_or_outline(};Ok(BufferContent {text,- is_outline: true,+ is_synthetic: true,})} else {// File is small enough, return full contentlet text = buffer.read_with(cx, |buffer, _| buffer.text());Ok(BufferContent {text,- is_outline: false,+ is_synthetic: false,})}}@@ -196,10 +204,13 @@ mod tests {"Result did not contain content subset");- // Should be marked as not an outline (it's truncated content)+ // Should be marked synthetic: the returned text is not the file's full+ // content (it's a truncated first-1KB fallback with a synthetic header), so+ // callers must treat it the same as the symbol-outline case and not attach+ // real-file line numbers to it.assert!(- !result.is_outline,- "Large file without outline should not be marked as outline"+ result.is_synthetic,+ "Truncated fallback should be reported as synthetic so callers skip line numbering");// Should be reasonably sized (much smaller than original)diff --git a/crates/agent/src/tools/edit_file_tool.rs b/crates/agent/src/tools/edit_file_tool.rsindex e952741d9c0..991288d515c 100644--- a/crates/agent/src/tools/edit_file_tool.rs+++ b/crates/agent/src/tools/edit_file_tool.rs@@ -23,8 +23,14 @@ const DEFAULT_UI_TEXT: &str = "Editing file";/// This is a tool for applying edits to an existing file.///-/// Before using this tool, use the `read_file` tool to understand the file's contents and context+/// Before using this tool, use the `read_file` tool to understand the file's contents and context./// To create a new file or overwrite an existing one with completely new contents, use the `write_file` tool instead.+///+/// `read_file` prefixes each line of its output with a line number right-aligned in a+/// 6-character field followed by a single tab, then the line's actual content. When you+/// derive `old_text` or `new_text` from that output, strip this prefix and keep only what+/// comes after the tab, preserving the original indentation (tabs and spaces) exactly.+/// Never include any part of the line number prefix in `old_text` or `new_text`.#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]pub struct EditFileToolInput {/// The full path of the file to edit in the project.diff --git a/crates/agent/src/tools/read_file_tool.rs b/crates/agent/src/tools/read_file_tool.rsindex 4638b170314..83ca602431d 100644--- a/crates/agent/src/tools/read_file_tool.rs+++ b/crates/agent/src/tools/read_file_tool.rs@@ -18,6 +18,80 @@ fn tool_content_err(e: impl std::fmt::Display) -> LanguageModelToolResultContentLanguageModelToolResultContent::from(e.to_string())}+/// Resolves the optional `start_line` / `end_line` inputs from the tool schema+/// to a concrete 1-indexed, inclusive `(start, end)` line range:+///+/// - `start` defaults to 1 and is clamped to `>= 1` (the model occasionally passes+/// `0` despite instructions to be 1-indexed).+/// - `end` defaults to `u32::MAX` and is clamped to `>= start`, so callers always+/// read at least one line even when the model passes `end < start`.+///+/// Callers translate this 1-indexed inclusive range to whichever coordinate+/// system their slicing API wants (e.g. 0-indexed exclusive row ranges for+/// `Buffer::text_for_range`).+fn resolve_line_range(start_line: Option<u32>, end_line: Option<u32>) -> (u32, u32) {+ let start = start_line.unwrap_or(1).max(1);+ let end = end_line.unwrap_or(u32::MAX).max(start);+ (start, end)+}++/// Prefixes each line of `text` with its line number in `cat -n` format:+/// the line number is right-aligned in a 6-character field, followed by a+/// single tab, followed by the line's original content (including its+/// trailing newline if present). Numbering starts at `start_line`.+///+/// This format matches what the model expects in the edit tool, where the+/// line number prefix is `line number + tab` and everything after the tab is+/// the actual file content to match.+fn format_with_line_numbers(text: &str, start_line: u32) -> String {+ if text.is_empty() {+ return String::new();+ }++ let mut output = String::with_capacity(text.len() + text.len() / 4);+ write_lines_numbered(&mut output, std::iter::once(text), start_line);+ output+}++/// Streams `cat -n`-style line-numbered output directly into `output` from an+/// iterator of string slices. Chunks do not need to align to line boundaries:+/// a single chunk may contain multiple newlines, span multiple lines, or end+/// mid-line. This lets callers consume `Buffer::text_for_range`'s `Chunks`+/// iterator without materializing the unnumbered text first.+fn write_lines_numbered<'a>(+ output: &mut String,+ chunks: impl IntoIterator<Item = &'a str>,+ start_line: u32,+) {+ use std::fmt::Write as _;++ let mut line_number = start_line;+ let mut at_line_start = true;+ for chunk in chunks {+ let mut rest = chunk;+ while !rest.is_empty() {+ if at_line_start {+ // Writes to a `String` are infallible, so the `Result` can be ignored.+ let _ = write!(output, "{line_number:>6}\t");+ at_line_start = false;+ }+ match rest.find('\n') {+ Some(nl) => {+ let (head, tail) = rest.split_at(nl + 1);+ output.push_str(head);+ line_number = line_number.saturating_add(1);+ at_line_start = true;+ rest = tail;+ }+ None => {+ output.push_str(rest);+ break;+ }+ }+ }+ }+}+/// Read a file under the global skills directory directly via the filesystem,/// bypassing project/worktree resolution. Used for skill resources that live/// outside any worktree.@@ -40,26 +114,21 @@ async fn read_global_skill_file(.line(start_line.map(|line| line.saturating_sub(1))),]));- let result_text = if start_line.is_some() || end_line.is_some() {- // Mirror the line-range semantics of the buffer-backed path: 1-indexed,- // start clamped to >= 1, end exclusive of the next line, and always- // returning at least one line. `split_inclusive` keeps each line's- // terminator attached, so CRLF stays CRLF and the trailing newline of- // the last returned line is preserved — matching `Buffer::text_for_range`.- let start = start_line.unwrap_or(1).max(1);- let mut end = end_line.unwrap_or(u32::MAX);- if end < start {- end = start;- }-+ let (raw_text, first_line_number) = if start_line.is_some() || end_line.is_some() {+ // `split_inclusive` keeps each line's terminator attached, so CRLF stays+ // CRLF and the trailing newline of the last returned line is preserved —+ // matching `Buffer::text_for_range` in the buffer-backed path.+ let (start, end) = resolve_line_range(start_line, end_line);let lines: Vec<&str> = content.split_inclusive('\n').collect();let start_idx = (start as usize).saturating_sub(1).min(lines.len());let end_idx = (end as usize).min(lines.len()).max(start_idx);- lines[start_idx..end_idx].concat()+ (lines[start_idx..end_idx].concat(), start)} else {- content+ (content, 1)};+ let result_text = format_with_line_numbers(&raw_text, first_line_number);+let markdown = MarkdownCodeBlock {tag: requested_path,text: &result_text,@@ -342,29 +411,38 @@ impl AgentTool for ReadFileTool {// Check if specific line ranges are providedlet result = if input.start_line.is_some() || input.end_line.is_some() {- let result = buffer.read_with(cx, |buffer, _cx| {- // .max(1) because despite instructions to be 1-indexed, sometimes the model passes 0.- let start = input.start_line.unwrap_or(1).max(1);+ let result_text = buffer.read_with(cx, |buffer, _cx| {+ let (start, end) = resolve_line_range(input.start_line, input.end_line);let start_row = start - 1;if start_row <= buffer.max_point().row {let column = buffer.line_indent_for_row(start_row).raw_len();anchor = Some(buffer.anchor_before(Point::new(start_row, column)));}- let mut end_row = input.end_line.unwrap_or(u32::MAX);- if end_row <= start_row {- end_row = start_row + 1; // read at least one lines- }- let start = buffer.anchor_before(Point::new(start_row, 0));- let end = buffer.anchor_before(Point::new(end_row, 0));- buffer.text_for_range(start..end).collect::<String>()+ // `end` is 1-indexed inclusive; `Point` rows are 0-indexed.+ // Using `end` directly as the (exclusive) end row is the+ // standard inclusive→exclusive translation, and since+ // `resolve_line_range` guarantees `end >= start`, we always+ // read at least one line.+ let start_anchor = buffer.anchor_before(Point::new(start_row, 0));+ let end_anchor = buffer.anchor_before(Point::new(end, 0));+ // Stream the numbered output directly from the buffer's+ // chunk iterator so the unnumbered range is never+ // materialized as its own `String`.+ let mut output = String::new();+ write_lines_numbered(+ &mut output,+ buffer.text_for_range(start_anchor..end_anchor),+ start,+ );+ output});action_log.update(cx, |log, cx| {log.buffer_read(buffer.clone(), cx);});- Ok(result.into())+ Ok(result_text.into())} else {// No line ranges specified, so check file size to see if it's too big.let buffer_content = outline::get_buffer_content_or_outline(@@ -378,9 +456,10 @@ impl AgentTool for ReadFileTool {log.buffer_read(buffer.clone(), cx);});- is_outline_response = buffer_content.is_outline;- if buffer_content.is_outline {+ is_outline_response = buffer_content.is_synthetic;++ if buffer_content.is_synthetic {Ok(formatdoc! {"SUCCESS: File outline retrieved. This file is too large to read all at once, so the outline below shows the file's structure with line numbers.@@ -394,7 +473,7 @@ impl AgentTool for ReadFileTool {}.into())} else {- Ok(buffer_content.text.into())+ Ok(format_with_line_numbers(&buffer_content.text, 1).into())}};@@ -427,6 +506,27 @@ impl AgentTool for ReadFileTool {result})}++ fn replay(+ &self,+ input: Self::Input,+ output: Self::Output,+ event_stream: ToolCallEventStream,+ _cx: &mut App,+ ) -> Result<()> {+ if let LanguageModelToolResultContent::Text(text) = output {+ let markdown = MarkdownCodeBlock {+ tag: &input.path,+ text: &text,+ }+ .to_string();+ event_stream.update_fields(acp::ToolCallUpdateFields::new().content(vec![+ acp::ToolCallContent::Content(acp::Content::new(markdown)),+ ]));+ }++ Ok(())+ }}#[cfg(test)]@@ -530,7 +630,10 @@ mod test {)}).await;- assert_eq!(result.unwrap(), "This is a small file content".into());+ assert_eq!(+ result.unwrap(),+ " 1\tThis is a small file content".into()+ );}#[gpui::test]@@ -777,7 +880,7 @@ mod test {)}).await;- assert_eq!(result.unwrap(), "root content".into());+ assert_eq!(result.unwrap(), " 1\troot content".into());}#[gpui::test]@@ -810,7 +913,10 @@ mod test {)}).await;- assert_eq!(result.unwrap(), "Line 2\nLine 3\nLine 4\n".into());+ assert_eq!(+ result.unwrap(),+ " 2\tLine 2\n 3\tLine 3\n 4\tLine 4\n".into()+ );}#[gpui::test]@@ -844,7 +950,7 @@ mod test {)}).await;- assert_eq!(result.unwrap(), "Line 1\nLine 2\n".into());+ assert_eq!(result.unwrap(), " 1\tLine 1\n 2\tLine 2\n".into());// end_line of 0 should result in at least 1 linelet result = cx@@ -861,7 +967,7 @@ mod test {)}).await;- assert_eq!(result.unwrap(), "Line 1\n".into());+ assert_eq!(result.unwrap(), " 1\tLine 1\n".into());// when start_line > end_line, should still return at least 1 linelet result = cx@@ -878,7 +984,7 @@ mod test {)}).await;- assert_eq!(result.unwrap(), "Line 3\n".into());+ assert_eq!(result.unwrap(), " 3\tLine 3\n".into());}fn error_text(content: LanguageModelToolResultContent) -> String {@@ -1112,7 +1218,7 @@ mod test {}).await;assert!(result.is_ok(), "Should be able to read normal files");- assert_eq!(result.unwrap(), "Normal file content".into());+ assert_eq!(result.unwrap(), " 1\tNormal file content".into());// Path traversal attempts with .. should faillet result = cx@@ -1282,7 +1388,7 @@ mod test {assert_eq!(result,- "fn main() { println!(\"Hello from worktree1\"); }".into()+ " 1\tfn main() { println!(\"Hello from worktree1\"); }".into());// Test reading private file in worktree1 should fail@@ -1348,7 +1454,7 @@ mod test {assert_eq!(result,- "export function greet() { return 'Hello from worktree2'; }".into()+ " 1\texport function greet() { return 'Hello from worktree2'; }".into());// Test reading private file in worktree2 should fail@@ -1658,7 +1764,10 @@ mod test {let LanguageModelToolResultContent::Text(text) = content else {panic!("expected text content");};- assert_eq!(text.as_ref(), "# Spec\n\nReference body.");+ assert_eq!(+ text.as_ref(),+ " 1\t# Spec\n 2\t\n 3\tReference body."+ );}#[gpui::test]@@ -1705,7 +1814,7 @@ mod test {};// Mirrors the buffer-backed path: lines 2-3 inclusive, WITH trailing// newline of the last returned line.- assert_eq!(text.as_ref(), "line two\nline three\n");+ assert_eq!(text.as_ref(), " 2\tline two\n 3\tline three\n");}#[gpui::test]@@ -1750,7 +1859,7 @@ mod test {let LanguageModelToolResultContent::Text(text) = result.unwrap() else {panic!("expected text content");};- assert_eq!(text.as_ref(), "Line 1\nLine 2\n");+ assert_eq!(text.as_ref(), " 1\tLine 1\n 2\tLine 2\n");}#[gpui::test]@@ -1795,7 +1904,7 @@ mod test {let LanguageModelToolResultContent::Text(text) = result.unwrap() else {panic!("expected text content");};- assert_eq!(text.as_ref(), "Line 1\n");+ assert_eq!(text.as_ref(), " 1\tLine 1\n");}#[gpui::test]@@ -1840,7 +1949,7 @@ mod test {let LanguageModelToolResultContent::Text(text) = result.unwrap() else {panic!("expected text content");};- assert_eq!(text.as_ref(), "Line 3\n");+ assert_eq!(text.as_ref(), " 3\tLine 3\n");}#[gpui::test]@@ -1885,7 +1994,7 @@ mod test {let LanguageModelToolResultContent::Text(text) = result.unwrap() else {panic!("expected text content");};- assert_eq!(text.as_ref(), "line one\r\nline two\r\n");+ assert_eq!(text.as_ref(), " 1\tline one\r\n 2\tline two\r\n");}#[gpui::test]diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rsindex ce6e2661ca4..65bd3a56791 100644--- a/crates/agent_ui/src/conversation_view.rs+++ b/crates/agent_ui/src/conversation_view.rs@@ -31,11 +31,11 @@ use futures::FutureExt as _;use gpui::{Action, Animation, AnimationExt, AnyView, App, ClickEvent, ClipboardItem, CursorStyle,ElementId, Empty, Entity, EventEmitter, FocusHandle, Focusable, Hsla, ListOffset, ListState,- ObjectFit, PlatformDisplay, ScrollHandle, SharedString, Subscription, Task, TaskExt, TextStyle,- WeakEntity, Window, WindowHandle, div, ease_in_out, img, linear_color_stop, linear_gradient,- list, point, pulsating_between,+ ObjectFit, PlatformDisplay, ScrollHandle, SharedString, StyledText, Subscription, Task,+ TaskExt, TextRun, TextStyle, WeakEntity, Window, WindowHandle, div, ease_in_out, img,+ linear_color_stop, linear_gradient, list, point, pulsating_between,};-use language::Buffer;+use language::{Buffer, Language, Rope};use language_model::{LanguageModelCompletionError, LanguageModelRegistry};use markdown::{CodeBlockRenderer, CopyButtonVisibility, Markdown, MarkdownElement, MarkdownFont, MarkdownStyle,diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rsindex abaf4ae981c..4f0adce1ad4 100644--- a/crates/agent_ui/src/conversation_view/thread_view.rs+++ b/crates/agent_ui/src/conversation_view/thread_view.rs@@ -217,6 +217,273 @@ pub enum AcpThreadViewEvent {impl EventEmitter<AcpThreadViewEvent> for ThreadView {}+/// `cat -n`-style numbered code block, already stripped of its line-number+/// prefixes and ready to render. Line numbers are guaranteed to be contiguous+/// starting at `first_number`, so we only store the first number and the line+/// count rather than allocating a per-line `Vec`.+struct ParsedCatNumberedCode {+ code: String,+ first_number: u32,+ line_count: usize,+}++fn parse_cat_numbered_markdown_code_block(markdown: &str) -> Option<ParsedCatNumberedCode> {+ let (_tag, code) = parse_single_fenced_code_block(markdown)?;+ parse_cat_numbered_code(code)+}++fn parse_single_fenced_code_block(markdown: &str) -> Option<(&str, &str)> {+ let first_non_backtick = markdown.find(|character| character != '`')?;+ if first_non_backtick < 3 {+ return None;+ }++ let fence = &markdown[..first_non_backtick];+ let after_opening_fence = &markdown[first_non_backtick..];+ let tag_end = after_opening_fence.find('\n')?;+ let tag = &after_opening_fence[..tag_end];+ let after_tag = &after_opening_fence[tag_end + 1..];+ let closing_fence = format!("\n{fence}\n");+ let code = after_tag.strip_suffix(&closing_fence)?;+ Some((tag, code))+}++/// Walks `code` exactly once: for each line it validates and strips the+/// `NNN\t` prefix, then pushes the line's content into the accumulating+/// code buffer (with `\n` between lines, no trailing newline). Verifies that+/// the line numbers form a contiguous, increasing sequence.+fn parse_cat_numbered_code(code: &str) -> Option<ParsedCatNumberedCode> {+ if code.is_empty() {+ return None;+ }++ let mut output = String::with_capacity(code.len());+ let mut first_number = None;+ let mut expected_number = None;+ let mut line_count: usize = 0;+ for raw_line in code.split_inclusive('\n') {+ let line = strip_line_ending(raw_line);+ let (number, text) = parse_cat_numbered_line(line)?;+ if let Some(expected) = expected_number {+ if number != expected {+ return None;+ }+ } else {+ first_number = Some(number);+ }+ expected_number = number.checked_add(1);+ if line_count > 0 {+ output.push('\n');+ }+ output.push_str(text);+ line_count += 1;+ }++ Some(ParsedCatNumberedCode {+ code: output,+ first_number: first_number?,+ line_count,+ })+}++fn strip_line_ending(line: &str) -> &str {+ let without_lf = line.strip_suffix('\n').unwrap_or(line);+ without_lf.strip_suffix('\r').unwrap_or(without_lf)+}++fn parse_cat_numbered_line(line: &str) -> Option<(u32, &str)> {+ let (prefix, text) = line.split_once('\t')?;+ let number = prefix.trim();+ if number.is_empty()+ || !prefix+ .chars()+ .all(|character| character == ' ' || character.is_ascii_digit())+ {+ return None;+ }++ Some((number.parse().ok()?, text))+}++fn render_cat_numbered_code_block(+ parsed: ParsedCatNumberedCode,+ language: Option<Arc<Language>>,+ markdown_style: MarkdownStyle,+ copy_button_id: String,+ cx: &App,+) -> AnyElement {+ use std::fmt::Write as _;++ let ParsedCatNumberedCode {+ code,+ first_number,+ line_count,+ } = parsed;++ // Line numbers are contiguous (verified during parsing), so the largest+ // line number is `first_number + line_count - 1`. Sizing the gutter to+ // that number's digit count means every rendered line contributes exactly+ // `gutter_width` bytes to the gutter, plus a newline between adjacent+ // lines.+ let last_number = first_number+ .saturating_add(u32::try_from(line_count.saturating_sub(1)).unwrap_or(u32::MAX));+ let gutter_width = last_number.to_string().len().max(1);+ let gutter_capacity = line_count * gutter_width + line_count.saturating_sub(1);++ let mut gutter = String::with_capacity(gutter_capacity);+ for i in 0..line_count {+ if i > 0 {+ gutter.push('\n');+ }+ let line_number = first_number.saturating_add(u32::try_from(i).unwrap_or(u32::MAX));+ // Writes to a `String` are infallible, so the `Result` can be ignored.+ let _ = write!(&mut gutter, "{line_number:>gutter_width$}");+ }++ let mut code_text_style = markdown_style.base_text_style.clone();+ code_text_style.refine(&markdown_style.code_block.text);++ let mut gutter_text_style = code_text_style.clone();+ gutter_text_style.color = cx.theme().colors().text_muted;++ let gutter_len = gutter.len();+ let gutter = StyledText::new(gutter).with_runs(vec![gutter_text_style.to_run(gutter_len)]);++ // Share `code` between syntax highlighting, the rendered `StyledText`, and+ // the copy button via a single `SharedString` (cheap `Arc` clones) instead+ // of cloning the underlying `String`.+ let code: SharedString = code.into();+ let code_runs = highlight_code_runs(&code, language.as_ref(), code_text_style, &markdown_style);+ let code_text = StyledText::new(code.clone()).with_runs(code_runs);++ let code_block_id = format!("read-file-code-block-{copy_button_id}");+ let code_scroll_id = format!("read-file-code-scroll-{copy_button_id}");+ let mut container = div()+ .id(code_block_id)+ .group("read-file-code-block")+ .relative()+ .w_full()+ .whitespace_nowrap();+ container.style().refine(&markdown_style.code_block);++ // `overflow_x_scroll` only actually scrolls when the container is laid out+ // as a flex container: in GPUI the default `Display` is `Block`, and a+ // block-level child fills its parent's content width instead of overflowing+ // it, so there is nothing for the scroll viewport to scroll. Using `flex()`+ // on the scroll wrapper plus `flex_none()` on the inner item lets the inner+ // item take its natural width (the unwrapped code), which is what overflows.+ // `restrict_scroll_to_axis` then keeps vertical wheel events flowing through+ // to the outer thread scroller. This mirrors the standard markdown+ // code-block path in `crates/markdown/src/markdown.rs`.+ let mut code_scroll = div()+ .id(code_scroll_id)+ .flex()+ .flex_1()+ .min_w_0()+ .overflow_x_scroll()+ .child(div().flex_none().child(code_text));+ code_scroll.style().restrict_scroll_to_axis = Some(true);++ container+ .child(+ h_flex()+ .items_start()+ .min_w_0()+ .w_full()+ .child(div().flex_none().pr_3().child(gutter))+ .child(code_scroll),+ )+ .child(+ h_flex()+ .w_4()+ .absolute()+ .top_0()+ .right_0()+ .justify_end()+ .visible_on_hover("read-file-code-block")+ .child(CopyButton::new(copy_button_id, code).tooltip_label("Copy Code")),+ )+ .into_any_element()+}++fn highlight_code_runs(+ code: &str,+ language: Option<&Arc<Language>>,+ code_text_style: TextStyle,+ markdown_style: &MarkdownStyle,+) -> Vec<TextRun> {+ if code.is_empty() {+ return Vec::new();+ }++ let Some(language) = language else {+ return vec![code_text_style.to_run(code.len())];+ };++ let mut runs = Vec::new();+ let mut offset = 0;+ for (range, highlight_id) in language.highlight_text(&Rope::from(code), 0..code.len()) {+ if range.start > offset {+ runs.push(code_text_style.to_run(range.start - offset));+ }++ let mut run_style = code_text_style.clone();+ if let Some(highlight) = markdown_style.syntax.get(highlight_id).cloned() {+ run_style = run_style.highlight(highlight);+ }+ runs.push(run_style.to_run(range.len()));+ offset = range.end;+ }++ if offset < code.len() {+ runs.push(code_text_style.to_run(code.len() - offset));+ }++ runs+}++#[cfg(test)]+mod numbered_code_block_tests {+ use super::*;++ #[test]+ fn parses_cat_numbered_markdown_code_block() {+ let parsed = parse_cat_numbered_markdown_code_block(+ "```rs zed/crates/example.rs\n 2\tfn main() {\n 3\t println!(\"hi\");\n 4\t}\n```\n",+ )+ .expect("cat-numbered block should parse");++ assert_eq!(parsed.line_count, 3);+ assert_eq!(parsed.first_number, 2);+ assert_eq!(parsed.code, "fn main() {\n println!(\"hi\");\n}");+ }++ #[test]+ fn parses_cat_numbered_code_with_crlf_line_endings() {+ let parsed = parse_cat_numbered_code(" 1\tline one\r\n 2\tline two\r\n")+ .expect("crlf-terminated cat-numbered code should parse");++ assert_eq!(parsed.line_count, 2);+ assert_eq!(parsed.first_number, 1);+ assert_eq!(parsed.code, "line one\nline two");+ }++ #[test]+ fn rejects_non_cat_numbered_code_block() {+ assert!(parse_cat_numbered_markdown_code_block("```rs\nfn main() {}\n```\n").is_none());+ }++ #[test]+ fn rejects_non_contiguous_cat_numbers() {+ assert!(+ parse_cat_numbered_markdown_code_block(+ "```rs\n 2\tlet a = 1;\n 4\tlet b = 2;\n```\n"+ )+ .is_none()+ );+ }+}+/// Tracks the user's permission dropdown selection state for a specific tool call.////// Default (no entry in the map) means the last dropdown choice is selected,@@ -7655,7 +7922,9 @@ impl ThreadView {} else if let Some(markdown) = content.markdown() {self.render_markdown_output(markdown.clone(),+ entry_ix,context_ix,+ tool_call,card_layout,window,cx,@@ -7798,11 +8067,28 @@ impl ThreadView {fn render_markdown_output(&self,markdown: Entity<Markdown>,+ entry_ix: usize,context_ix: usize,+ tool_call: &ToolCall,card_layout: bool,window: &Window,cx: &Context<Self>,) -> AnyElement {+ let markdown_style = MarkdownStyle::themed(MarkdownFont::Agent, window, cx);+ let output = self+ .render_numbered_read_file_output(+ markdown.clone(),+ entry_ix,+ context_ix,+ tool_call,+ markdown_style.clone(),+ cx,+ )+ .unwrap_or_else(|| {+ self.render_markdown(markdown, markdown_style, cx)+ .into_any()+ });+v_flex().gap_2().map(|this| {@@ -7820,14 +8106,39 @@ impl ThreadView {}).text_xs().text_color(cx.theme().colors().text_muted)- .child(self.render_markdown(- markdown,- MarkdownStyle::themed(MarkdownFont::Agent, window, cx),- cx,- ))+ .child(output).into_any_element()}+ fn render_numbered_read_file_output(+ &self,+ markdown: Entity<Markdown>,+ entry_ix: usize,+ context_ix: usize,+ tool_call: &ToolCall,+ markdown_style: MarkdownStyle,+ cx: &Context<Self>,+ ) -> Option<AnyElement> {+ let is_read_file = tool_call+ .tool_name+ .as_ref()+ .is_some_and(|tool_name| tool_name.as_ref() == "read_file");+ if !is_read_file {+ return None;+ }++ let markdown = markdown.read(cx);+ let parsed = parse_cat_numbered_markdown_code_block(markdown.source())?;+ let language = markdown.first_code_block_language();+ Some(render_cat_numbered_code_block(+ parsed,+ language,+ markdown_style,+ format!("copy-read-file-output-{entry_ix}-{context_ix}"),+ cx,+ ))+ }+fn render_image_output(&self,entry_ix: usize,diff --git a/crates/markdown/src/markdown.rs b/crates/markdown/src/markdown.rsindex 4abce8a878f..2d2f3cebe09 100644--- a/crates/markdown/src/markdown.rs+++ b/crates/markdown/src/markdown.rs@@ -630,6 +630,28 @@ impl Markdown {&self.source}+ pub fn first_code_block_language(&self) -> Option<Arc<Language>> {+ self.parsed_markdown.events.iter().find_map(|(_, event)| {+ let MarkdownEvent::Start(MarkdownTag::CodeBlock { kind, .. }) = event else {+ return None;+ };++ match kind {+ CodeBlockKind::FencedLang(language) => self+ .parsed_markdown+ .languages_by_name+ .get(language)+ .cloned(),+ CodeBlockKind::FencedSrc(path_range) => self+ .parsed_markdown+ .languages_by_path+ .get(&path_range.path)+ .cloned(),+ CodeBlockKind::Fenced | CodeBlockKind::Indented => None,+ }+ })+ }+pub fn append(&mut self, text: &str, cx: &mut Context<Self>) {self.source = SharedString::new(self.source.to_string() + text);self.parse(cx);diff --git a/crates/remote_server/src/remote_editing_tests.rs b/crates/remote_server/src/remote_editing_tests.rsindex 840485e6750..ff604da9de7 100644--- a/crates/remote_server/src/remote_editing_tests.rs+++ b/crates/remote_server/src/remote_editing_tests.rs@@ -2386,7 +2386,10 @@ async fn test_remote_agent_fs_tool_calls(cx: &mut TestAppContext, server_cx: &mu.run(ToolInput::resolved(input), event_stream.clone(), cx)});let output = exists_result.await.unwrap();- assert_eq!(output, LanguageModelToolResultContent::Text("B".into()));+ assert_eq!(+ output,+ LanguageModelToolResultContent::Text(" 1\tB".into())+ );let input = ReadFileToolInput {path: "project/c.txt".into(),