Commit 0e8352a5 authored by Heinrich Lee Yu's avatar Heinrich Lee Yu

Merge branch '353513-frontmatter-sourcepos' into 'master'

Fix source position mapping in markdown with frontmatter

See merge request gitlab-org/gitlab!81470
parents 718eb85d aa1c697b
......@@ -9,7 +9,10 @@ module Banzai
html.sub(Gitlab::FrontMatter::PATTERN) do |_match|
lang = $~[:lang].presence || lang_mapping[$~[:delim]]
["```#{lang}:frontmatter", $~[:front_matter].strip!, "```", "\n"].join("\n")
before = $~[:before]
before = "\n#{before}" if $~[:encoding].presence
"#{before}```#{lang}:frontmatter\n#{$~[:front_matter]}```\n"
end
end
end
......
......@@ -11,12 +11,12 @@ module Gitlab
DELIM = Regexp.union(DELIM_LANG.keys)
PATTERN = %r{
\A(?:[^\r\n]*coding:[^\r\n]*\R)? # optional encoding line
\s*
\A(?<encoding>[^\r\n]*coding:[^\r\n]*\R)? # optional encoding line
(?<before>\s*)
^(?<delim>#{DELIM})[ \t]*(?<lang>\S*)\R # opening front matter marker (optional language specifier)
(?<front_matter>.*?) # front matter block content (not greedy)
^(\k<delim> | \.{3}) # closing front matter marker
\s*
[^\S\r\n]*(\R|\z)
}mx.freeze
end
end
......@@ -109,7 +109,7 @@ module Gitlab
end
def parse_front_matter_block
wiki_content.match(Gitlab::FrontMatter::PATTERN) { |m| Block.new(*m.captures) } || Block.new
wiki_content.match(Gitlab::FrontMatter::PATTERN) { |m| Block.new(m[:delim], m[:lang], m[:front_matter]) } || Block.new
end
def strip_front_matter_block
......
......@@ -105,6 +105,56 @@ RSpec.describe Banzai::Filter::FrontMatterFilter do
end
end
context 'source position mapping' do
it 'keeps spaces before and after' do
content = <<~MD
---
foo: :foo_symbol
---
# Header
MD
output = filter(content)
expect(output).to eq <<~MD
```yaml:frontmatter
foo: :foo_symbol
```
# Header
MD
end
it 'keeps an empty line in place of the encoding' do
content = <<~MD
# encoding: UTF-8
---
foo: :foo_symbol
---
MD
output = filter(content)
expect(output).to eq <<~MD
```yaml:frontmatter
foo: :foo_symbol
```
MD
end
end
context 'on content without front matter' do
it 'returns the content unmodified' do
content = <<~MD
......@@ -119,7 +169,7 @@ RSpec.describe Banzai::Filter::FrontMatterFilter do
context 'on front matter without content' do
it 'converts YAML front matter to a fenced code block' do
content = <<~MD
content = <<~MD.rstrip
---
foo: :foo_symbol
bar: :bar_symbol
......@@ -134,7 +184,6 @@ RSpec.describe Banzai::Filter::FrontMatterFilter do
foo: :foo_symbol
bar: :bar_symbol
```
MD
end
end
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment