From 6144c58707164b58fdacacad4bfbde1ffc7ddb1a Mon Sep 17 00:00:00 2001 From: Yuval Shavit Date: Tue, 13 Aug 2024 06:04:15 -0400 Subject: [PATCH] Fix padded code (text) in mdast Closes GH-122. Closes GH-123. Reviewed-by: Titus Wormer --- src/to_mdast.rs | 10 ++++++++++ tests/code_text.rs | 30 ++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/src/to_mdast.rs b/src/to_mdast.rs index acea2193..526e6c4a 100644 --- a/src/to_mdast.rs +++ b/src/to_mdast.rs @@ -1080,6 +1080,16 @@ fn on_exit_raw_text(context: &mut CompileContext) -> Result<(), message::Message } } + let value_bytes = value.as_bytes(); + if value.len() > 2 + && value_bytes[0] == b' ' + && value_bytes[value.len() - 1] == b' ' + && !value_bytes.iter().all(|b| *b == b' ') + { + value.remove(0); + value.pop(); + } + match context.tail_mut() { Node::InlineCode(node) => node.value = value, Node::InlineMath(node) => node.value = value, diff --git a/tests/code_text.rs b/tests/code_text.rs index d4a0e70b..cfad799f 100644 --- a/tests/code_text.rs +++ b/tests/code_text.rs @@ -205,5 +205,35 @@ fn code_text() -> Result<(), message::Message> { "should support code (text) as `InlineCode`s in mdast" ); + assert_eq!( + to_mdast("` alpha `", &Default::default())?, + Node::Root(Root { + children: vec![Node::Paragraph(Paragraph { + children: vec![Node::InlineCode(InlineCode { + value: " alpha".into(), + position: Some(Position::new(1, 1, 0, 1, 11, 10)) + }),], + position: Some(Position::new(1, 1, 0, 1, 11, 10)) + })], + position: Some(Position::new(1, 1, 0, 1, 11, 10)) + }), + "should strip one space from each side of `InlineCode` if the value starts and ends with space" + ); + + assert_eq!( + to_mdast("` `", &Default::default())?, + Node::Root(Root { + children: vec![Node::Paragraph(Paragraph { + children: vec![Node::InlineCode(InlineCode { + value: " ".into(), + position: Some(Position::new(1, 1, 0, 1, 6, 5)) + }),], + position: Some(Position::new(1, 1, 0, 1, 6, 5)) + })], + position: Some(Position::new(1, 1, 0, 1, 6, 5)) + }), + "should not strip any whitespace if `InlineCode` is all whitespace" + ); + Ok(()) }