Skip to content

Commit

Permalink
Fix comments inside of fenced code blocks
Browse files Browse the repository at this point in the history
- FIXED: Comments inside of fenced code rendering as ATX headlines
  • Loading branch information
ttscoff committed Sep 22, 2023
1 parent e89d687 commit a7d822f
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 28 deletions.
56 changes: 28 additions & 28 deletions lib/mdless/converter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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]')
Expand Down
9 changes: 9 additions & 0 deletions test/codeblocks.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)<br/>after a break
Expand Down

0 comments on commit a7d822f

Please sign in to comment.