From 2ad9662d83938e576b4cd16e7f2a1ef6e040ee29 Mon Sep 17 00:00:00 2001 From: Hartley McGuire Date: Sat, 13 Jul 2024 12:43:32 -0400 Subject: [PATCH] Require space between hash/content in ATX heading MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit While writing some Markdown documentation for Rails, I came across an interesting case where trying to link to an instance method at the start of a line would instead parse as an H1 heading: ```markdown #response_body= ``` Expected: ```html #response_body= ``` Actual: ```html

response_body=

``` According to the CommonMark spec: > At least one space or tab is required between the # characters and the > heading’s contents, unless the heading is empty. Note that many > implementations currently do not require the space. However, the space > was required by the original ATX implementation, and it helps prevent > things like the following from being parsed as headings: > > Example 64 So while some implementations do not follow this requirement, I believe RDoc should because it makes it easy to write text similar to Example 64 (which was used in the new test) and it also enables automatically linking to instance methods at the start of a line. --- lib/rdoc/markdown.kpeg | 2 +- test/rdoc/test_rdoc_markdown.rb | 17 +++++++++++++++-- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/lib/rdoc/markdown.kpeg b/lib/rdoc/markdown.kpeg index 576a167457..66a4aa74fd 100644 --- a/lib/rdoc/markdown.kpeg +++ b/lib/rdoc/markdown.kpeg @@ -530,7 +530,7 @@ AtxInline = !@Newline !(@Sp /#*/ @Sp @Newline) Inline AtxStart = < /\#{1,6}/ > { text.length } -AtxHeading = AtxStart:s @Sp AtxInline+:a (@Sp /#*/ @Sp)? @Newline +AtxHeading = AtxStart:s @Spacechar+ AtxInline+:a (@Sp /#*/ @Sp)? @Newline { RDoc::Markup::Heading.new(s, a.join) } SetextHeading = SetextHeading1 | SetextHeading2 diff --git a/test/rdoc/test_rdoc_markdown.rb b/test/rdoc/test_rdoc_markdown.rb index 31d5b068f9..72587caf46 100644 --- a/test/rdoc/test_rdoc_markdown.rb +++ b/test/rdoc/test_rdoc_markdown.rb @@ -414,10 +414,23 @@ def test_parse_escape end def test_parse_heading_atx - doc = parse "# heading\n" + # CommonMark Example 62 + (1..6).each do |level| + doc = parse "#{"#" * level} heading\n" + + expected = @RM::Document.new( + @RM::Heading.new(level, "heading")) + + assert_equal expected, doc + end + + # CommonMark Example 64 + doc = parse "#5 bolt\n\n#hashtag\n" expected = @RM::Document.new( - @RM::Heading.new(1, "heading")) + para("#5 bolt"), + para("#hashtag"), + ) assert_equal expected, doc end