BigW Consortium Gitlab

asciidoc.rb 2.36 KB
Newer Older
1
require 'asciidoctor'
2
require 'asciidoctor/converter/html5'
3
require "asciidoctor-plantuml"
4 5 6 7 8 9 10

module Gitlab
  # Parser/renderer for the AsciiDoc format that uses Asciidoctor and filters
  # the resulting HTML through HTML pipeline filters.
  module Asciidoc
    DEFAULT_ADOC_ATTRS = [
      'showtitle', 'idprefix=user-content-', 'idseparator=-', 'env=gitlab',
11
      'env-gitlab', 'source-highlighter=html-pipeline', 'icons=font'
12 13 14 15 16 17 18 19 20 21 22 23 24
    ].freeze

    # Public: Converts the provided Asciidoc markup into HTML.
    #
    # input         - the source text in Asciidoc format
    # context       - a Hash with the template context:
    #                 :commit
    #                 :project
    #                 :project_wiki
    #                 :requested_path
    #                 :ref
    # asciidoc_opts - a Hash of options to pass to the Asciidoctor converter
    #
25 26
    def self.render(input, context, asciidoc_opts = {})
      asciidoc_opts.reverse_merge!(
27
        safe: :secure,
28
        backend: :gitlab_html5,
29 30 31 32
        attributes: []
      )
      asciidoc_opts[:attributes].unshift(*DEFAULT_ADOC_ATTRS)

33 34
      plantuml_setup

35 36
      html = ::Asciidoctor.convert(input, asciidoc_opts)

37
      html = Banzai.post_process(html, context)
38

39 40 41
      filter = Banzai::Filter::SanitizationFilter.new(html)
      html = filter.call.to_s

42 43
      html.html_safe
    end
44

45 46 47 48 49 50 51 52 53
    def self.plantuml_setup
      Asciidoctor::PlantUml.configure do |conf|
        conf.url = ApplicationSetting.current.plantuml_url
        conf.svg_enable = ApplicationSetting.current.plantuml_enabled
        conf.png_enable = ApplicationSetting.current.plantuml_enabled
        conf.txt_enable = false
      end
    end

54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
    class Html5Converter < Asciidoctor::Converter::Html5Converter
      extend Asciidoctor::Converter::Config

      register_for 'gitlab_html5'

      def stem(node)
        return super unless node.style.to_sym == :latexmath

        %(<pre#{id_attribute(node)} class="code math js-render-math #{node.role}" data-math-style="display"><code>#{node.content}</code></pre>)
      end

      def inline_quoted(node)
        return super unless node.type.to_sym == :latexmath

        %(<code#{id_attribute(node)} class="code math js-render-math #{node.role}" data-math-style="inline">#{node.text}</code>)
      end

      private

      def id_attribute(node)
        node.id ? %( id="#{node.id}") : nil
      end
    end
  end
end