diff --git a/lib/ronn/document.rb b/lib/ronn/document.rb index b554c0a..7da173d 100644 --- a/lib/ronn/document.rb +++ b/lib/ronn/document.rb @@ -214,8 +214,32 @@ def sniff html = Kramdown::Document.new(data[0, 512], auto_ids: false, smart_quotes: ['apos', 'apos', 'quot', 'quot'], typographic_symbols: { hellip: '...', ndash: '--', mdash: '--' }).to_html + sniff_h2_headings(html) or sniff_h1_heading(html) or [nil, nil, nil] + end + + # If the document has a '## NAME' heading, see if we can sniff out + # some of the document metadata. + def sniff_h2_headings(html) + html.split('

').each do |section| + case section + when /^NAME<\/h2>\s*

([\w_.\/\[\]~+=@:<>-]+)\s+-+\s+([\w_.\/\[\]~+=@: -]*)<\/p>/m + # name -- description + description = $2 + name = $1.gsub(/<[^>]+>/, '') + return [name, nil, description] + when /^NAME<\/h2>\s*

([\w_.\/\[\]~+=@:<>-]+)<\/p>/m + # name + return [$1.gsub(/<[^>]+>/, ''), nil, nil] + end + end + nil + end + + # If the document has a top-level '# ' type heading, see + # what kind of metadata we can sniff out of it. + def sniff_h1_heading(html) heading, html = html.split("

\n", 2) - return [nil, nil, nil] if html.nil? + return if html.nil? case heading when /([\w_.\[\]~+=@:-]+)\s*\((\d\w*)\)\s*-+\s*(.*)/ @@ -436,7 +460,7 @@ def html_filter_inject_name_section markup = if title? "

#{title}

" - elsif name + elsif name && !@html.css('h2').map(&:text).include?('NAME') "

NAME

\n" \ "

\n #{name}" + (tagline ? " - #{tagline}\n" : "\n") + diff --git a/test/existing_name_section.ronn b/test/existing_name_section.ronn new file mode 100644 index 0000000..f100833 --- /dev/null +++ b/test/existing_name_section.ronn @@ -0,0 +1,9 @@ +# Test # + +## NAME ## + +test - the test manpage + +## DESCRIPTION ## + +Testing items. w00t! diff --git a/test/test_ronn_document.rb b/test/test_ronn_document.rb index cd573fe..57cf9d2 100644 --- a/test/test_ronn_document.rb +++ b/test/test_ronn_document.rb @@ -74,6 +74,18 @@ def canonicalize(text) assert_equal '5', doc.section assert_equal 'wootderitis', doc.tagline end + + test "new with NAME heading with #{i} dashes and description" do + doc = Ronn::Document.new { "# whatever\n\n## NAME\n\n`foo` #{dashes} bar" } + assert_equal 'foo', doc.name + assert_equal 'bar', doc.tagline + end + end + + test 'new with NAME heading without description' do + doc = Ronn::Document.new { "# whatever\n\n## NAME\n\n`foo`" } + assert_equal 'foo', doc.name + assert_equal nil, doc.tagline end context 'simple conventionally named document' do @@ -188,4 +200,9 @@ def canonicalize(text) @doc = Ronn::Document.new('hello.1.ronn', styles: %w[test boom test]) { '' } assert_equal %w[man test boom], @doc.styles end + + test 'NAME section is not duplicated' do + html = Ronn::Document.new(File.expand_path('existing_name_section.ronn', __dir__)).to_html + assert html.scan(/]*>NAME<\/h2>/).length == 1 + end end