File: markdown_filter.rb

package info (click to toggle)
ruby-html-pipeline 2.14.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 424 kB
  • sloc: ruby: 2,265; sh: 13; makefile: 6
file content (56 lines) | stat: -rw-r--r-- 2,151 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# frozen_string_literal: true

HTML::Pipeline.require_dependency('commonmarker', 'MarkdownFilter')

module HTML
  class Pipeline
    # HTML Filter that converts Markdown text into HTML and converts into a
    # DocumentFragment. This is different from most filters in that it can take a
    # non-HTML as input. It must be used as the first filter in a pipeline.
    #
    # Context options:
    #   :gfm      => false    Disable GFM line-end processing
    #   :commonmarker_extensions => [ :table, :strikethrough,
    #      :tagfilter, :autolink ] Commonmarker extensions to include
    #
    # This filter does not write any additional information to the context hash.
    class MarkdownFilter < TextFilter
      DEFAULT_COMMONMARKER_EXTENSIONS = %i[table strikethrough tagfilter autolink].freeze

      def initialize(text, context = nil, result = nil)
        super text, context, result
        @text = @text.delete "\r"
      end

      # Convert Markdown to HTML using the best available implementation
      # and convert into a DocumentFragment.
      def call
        extensions = context.fetch(
          :commonmarker_extensions,
          DEFAULT_COMMONMARKER_EXTENSIONS
        )
        html = if (renderer = context[:commonmarker_renderer])
          unless renderer < CommonMarker::HtmlRenderer
            raise ArgumentError, "`commonmark_renderer` must be derived from `CommonMarker::HtmlRenderer`"
          end
          parse_options = :DEFAULT
          parse_options = [:UNSAFE] if context[:unsafe]

          render_options = [:GITHUB_PRE_LANG]
          render_options << :HARDBREAKS if context[:gfm] != false
          render_options << :UNSAFE if context[:unsafe]

          doc = CommonMarker.render_doc(@text, parse_options, extensions)
          renderer.new(options: render_options, extensions: extensions).render(doc)
        else
          options = [:GITHUB_PRE_LANG]
          options << :HARDBREAKS if context[:gfm] != false
          options << :UNSAFE if context[:unsafe]
          CommonMarker.render_html(@text, options, extensions)
        end
        html.rstrip!
        html
      end
    end
  end
end