BigW Consortium Gitlab

highlight.rb 1.28 KB
Newer Older
1 2
module Gitlab
  class Highlight
3 4 5
    def self.highlight(blob_name, blob_content, nowrap: true, plain: false)
      new(blob_name, blob_content, nowrap: nowrap).
        highlight(blob_content, continue: false, plain: plain)
6 7
    end

8 9 10 11
    def self.highlight_lines(repository, ref, file_name)
      blob = repository.blob_at(ref, file_name)
      return [] unless blob

12
      blob.load_all_data!(repository)
13 14 15
      highlight(file_name, blob.data).lines.map!(&:html_safe)
    end

16 17 18 19 20
    def initialize(blob_name, blob_content, nowrap: true)
      @formatter = rouge_formatter(nowrap: nowrap)
      @lexer = Rouge::Lexer.guess(filename: blob_name, source: blob_content).new rescue Rouge::Lexers::PlainText
    end

21 22 23 24 25 26
    def highlight(text, continue: true, plain: false)
      if plain
        @formatter.format(Rouge::Lexers::PlainText.lex(text)).html_safe
      else
        @formatter.format(@lexer.lex(text, continue: continue)).html_safe
      end
27 28
    rescue
      @formatter.format(Rouge::Lexers::PlainText.lex(text)).html_safe
29 30
    end

31 32
    private

33
    def rouge_formatter(options = {})
34 35 36 37 38 39 40 41 42 43 44
      options = options.reverse_merge(
        nowrap: true,
        cssclass: 'code highlight',
        lineanchors: true,
        lineanchorsid: 'LC'
      )

      Rouge::Formatters::HTMLGitlab.new(options)
    end
  end
end