diff options
Diffstat (limited to 'lib/banzai/filter/front_matter_filter.rb')
-rw-r--r-- | lib/banzai/filter/front_matter_filter.rb | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/lib/banzai/filter/front_matter_filter.rb b/lib/banzai/filter/front_matter_filter.rb new file mode 100644 index 00000000000..a27d18facd1 --- /dev/null +++ b/lib/banzai/filter/front_matter_filter.rb @@ -0,0 +1,34 @@ +# frozen_string_literal: true + +module Banzai + module Filter + class FrontMatterFilter < HTML::Pipeline::Filter + DELIM_LANG = { + '---' => 'yaml', + '+++' => 'toml', + ';;;' => 'json' + }.freeze + + DELIM = Regexp.union(DELIM_LANG.keys) + + PATTERN = %r{ + \A(?:[^\r\n]*coding:[^\r\n]*)? # optional encoding line + \s* + ^(?<delim>#{DELIM})[ \t]*(?<lang>\S*) # opening front matter marker (optional language specifier) + \s* + ^(?<front_matter>.*?) # front matter (not greedy) + \s* + ^\k<delim> # closing front matter marker + \s* + }mx + + def call + html.sub(PATTERN) do |_match| + lang = $~[:lang].presence || DELIM_LANG[$~[:delim]] + + ["```#{lang}", $~[:front_matter], "```", "\n"].join("\n") + end + end + end + end +end |