2016-01-14 09:11:50 -05:00
|
|
|
module Gitlab
|
|
|
|
class Highlight
|
2016-01-19 08:52:41 -05:00
|
|
|
def self.highlight(blob_name, blob_content, nowrap: true)
|
|
|
|
new(blob_name, blob_content, nowrap: nowrap).highlight(blob_content, continue: false)
|
2016-01-14 09:11:50 -05:00
|
|
|
end
|
|
|
|
|
2016-01-14 16:28:07 -05:00
|
|
|
def self.highlight_lines(repository, ref, file_name)
|
|
|
|
blob = repository.blob_at(ref, file_name)
|
|
|
|
return [] unless blob
|
|
|
|
|
|
|
|
highlight(file_name, blob.data).lines.map!(&:html_safe)
|
|
|
|
end
|
|
|
|
|
2016-01-19 08:52:41 -05:00
|
|
|
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
|
|
|
|
|
|
|
|
def highlight(text, continue: true)
|
2016-01-19 09:13:37 -05:00
|
|
|
@formatter.format(@lexer.lex(text, continue: continue)).html_safe
|
|
|
|
rescue
|
|
|
|
@formatter.format(Rouge::Lexers::PlainText.lex(text)).html_safe
|
2016-01-19 08:52:41 -05:00
|
|
|
end
|
|
|
|
|
2016-01-14 09:11:50 -05:00
|
|
|
private
|
|
|
|
|
2016-01-19 08:52:41 -05:00
|
|
|
def rouge_formatter(options = {})
|
2016-01-14 09:11:50 -05:00
|
|
|
options = options.reverse_merge(
|
|
|
|
nowrap: true,
|
|
|
|
cssclass: 'code highlight',
|
|
|
|
lineanchors: true,
|
|
|
|
lineanchorsid: 'LC'
|
|
|
|
)
|
|
|
|
|
|
|
|
Rouge::Formatters::HTMLGitlab.new(options)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|