From 2c63af94c85e5157b190c54318b2611d017f3079 Mon Sep 17 00:00:00 2001 From: "gcp-cherry-pick-bot[bot]" <98988430+gcp-cherry-pick-bot[bot]@users.noreply.github.com> Date: Sun, 11 May 2025 17:34:54 +0200 Subject: [PATCH] markdown: Fix out of range panic in parser (cherry-pick #30510) (#30512) Cherry-picked markdown: Fix out of range panic in parser (#30510) For some reason `pulldown_cmark` treats \````` as a codeblock, meaning that we could end up with an invalid range generated from `extract_code_block_content_range` (`3..2`) Closes #30495 Release Notes: - agent: Fix an edge case where the editor would crash when model generated malformed markdown Co-authored-by: Bennet Bo Fenner --- crates/markdown/src/parser.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/crates/markdown/src/parser.rs b/crates/markdown/src/parser.rs index 7c18a1200127eae20cd8779a7ef85dc550d33f76..ec81b0010f5c8efc3b994f1e2bd26f9ea5471974 100644 --- a/crates/markdown/src/parser.rs +++ b/crates/markdown/src/parser.rs @@ -509,6 +509,9 @@ pub(crate) fn extract_code_block_content_range(text: &str) -> Range { if !range.is_empty() && text.ends_with("```") { range.end -= 3; } + if range.start > range.end { + range.end = range.start; + } range } @@ -685,6 +688,10 @@ mod tests { let input = "```python\nprint('hello')\nprint('world')\n```"; assert_eq!(extract_code_block_content_range(input), 10..40); + + // Malformed input + let input = "`````"; + assert_eq!(extract_code_block_content_range(input), 3..3); } #[test]