From a7d822f25627a5abaf84385498770979ed702b8e Mon Sep 17 00:00:00 2001 From: Brett Terpstra Date: Fri, 22 Sep 2023 09:44:39 -0500 Subject: [PATCH] Fix comments inside of fenced code blocks - FIXED: Comments inside of fenced code rendering as ATX headlines --- lib/mdless/converter.rb | 56 ++++++++++++++++++++--------------------- test/codeblocks.md | 9 +++++++ 2 files changed, 37 insertions(+), 28 deletions(-) diff --git a/lib/mdless/converter.rb b/lib/mdless/converter.rb index 114e887..6636717 100644 --- a/lib/mdless/converter.rb +++ b/lib/mdless/converter.rb @@ -578,6 +578,34 @@ def convert_markdown(input) input = new_content.join("\n") end + # fenced code block parsing + input.gsub!(/(?i-m)(^[ \t]*[`~]{3,})([\s\S]*?)\n([\s\S]*?)\1/m) do + language = nil + m = Regexp.last_match + first_indent = m[1].gsub(/\t/, ' ').match(/^ */)[0].size + + if m[2] && !m[2].strip.empty? + language = m[2].strip.split(/ /)[0] + code_block = pad_max(m[3].to_s, '') + leader = language || 'code' + else + first_line = m[3].to_s.split(/\n/)[0] + + if first_line =~ %r{^\s*#!.*/.+} + shebang = first_line.match(%r{^\s*#!.*/(?:env )?([^/]+)$}) + language = shebang[1] + code_block = m[3] + leader = shebang[1] || 'code' + else + code_block = pad_max(m[3].to_s, "#{color('code_block eol')}¬") + leader = language || 'code' + end + end + leader += xc + + hiliteCode(language, code_block, leader, first_indent, m[0]) + end + # h_adjust = highest_header(input) - 1 # input.gsub!(/^(#+)/) do |m| # match = Regexp.last_match @@ -622,34 +650,6 @@ def convert_markdown(input) end } - # code block parsing - input.gsub!(/(?i-m)(^[ \t]*[`~]{3,})([\s\S]*?)\n([\s\S]*?)\1/m) do - language = nil - m = Regexp.last_match - first_indent = m[1].gsub(/\t/, ' ').match(/^ */)[0].size - - if m[2] && !m[2].strip.empty? - language = m[2].strip.split(/ /)[0] - code_block = pad_max(m[3].to_s, '') - leader = language || 'code' - else - first_line = m[3].to_s.split(/\n/)[0] - - if first_line =~ %r{^\s*#!.*/.+} - shebang = first_line.match(%r{^\s*#!.*/(?:env )?([^/]+)$}) - language = shebang[1] - code_block = m[3] - leader = shebang[1] || 'code' - else - code_block = pad_max(m[3].to_s, "#{color('code_block eol')}¬") - leader = language || 'code' - end - end - leader += xc - - hiliteCode(language, code_block, leader, first_indent, m[0]) - end - # remove empty links input.gsub!(/\[(.*?)\]\(\s*?\)/, '\1') input.gsub!(/\[(.*?)\]\[\]/, '[\1][\1]') diff --git a/test/codeblocks.md b/test/codeblocks.md index 677a6a4..64e4146 100644 --- a/test/codeblocks.md +++ b/test/codeblocks.md @@ -8,6 +8,15 @@ Code block tests #! ``` +``` +# Just a comment +do_thing() +``` + + # Another comment + does_this_work? + + Just some text before we get started. ![Image test](https://raw.githubusercontent.com/eddieantonio/i/master/imgcat.png)
after a break