summaryrefslogtreecommitdiff
path: root/lib/redcarpet/render/gitlab_html.rb
blob: 5a87b230579a3a3a8cbf40f647398f681454ed68 (plain)
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
require 'active_support/core_ext/string/output_safety'

class Redcarpet::Render::GitlabHTML < Redcarpet::Render::HTML
  attr_reader :template
  alias_method :h, :template

  def initialize(template, color_scheme, options = {})
    @template = template
    @color_scheme = color_scheme
    @project = @template.instance_variable_get("@project")
    @options = options.dup

    super(options)
  end

  # If project has issue number 39, apostrophe will be linked in
  # regular text to the issue as Redcarpet will convert apostrophe to
  # #39;
  # We replace apostrophe with right single quote before Redcarpet
  # does the processing and put the apostrophe back in postprocessing.
  # This only influences regular text, code blocks are untouched.
  def normal_text(text)
    return text unless text.present?

    text = ERB::Util.html_escape_once(text)
    text.gsub("'", "&rsquo;")
  end

  # Stolen from Rugments::Plugins::Redcarpet as this module is not required
  # from Rugments's gem root.
  def block_code(code, language)
    lexer = Rugments::Lexer.find_fancy(language, code) || Rugments::Lexers::PlainText

    # XXX HACK: Redcarpet strips hard tabs out of code blocks,
    # so we assume you're not using leading spaces that aren't tabs,
    # and just replace them here.
    if lexer.tag == 'make'
      code.gsub!(/^    /, "\t")
    end

    formatter = Rugments::Formatters::HTML.new(
      cssclass: "code highlight #{@color_scheme} #{lexer.tag}"
    )
    formatter.format(lexer.lex(code))
  end

  def postprocess(full_document)
    full_document.gsub!("&rsquo;", "'")

    unless @template.instance_variable_get("@project_wiki") || @project.nil?
      full_document = h.create_relative_links(full_document)
    end

    h.gfm_with_options(full_document, @options)
  end
end