gitlab-org--gitlab-foss/lib/gitlab/highlight.rb

64 lines
1.8 KiB
Ruby
Raw Normal View History

module Gitlab
class Highlight
2016-06-20 18:59:28 +00:00
def self.highlight(blob_name, blob_content, repository: nil, nowrap: true, plain: false)
new(blob_name, blob_content, nowrap: nowrap, repository: repository).
2016-04-14 10:44:35 +00:00
highlight(blob_content, continue: false, plain: plain)
end
def self.highlight_lines(repository, ref, file_name)
blob = repository.blob_at(ref, file_name)
return [] unless blob
blob.load_all_data!(repository)
highlight(file_name, blob.data, repository: repository).lines.map!(&:html_safe)
end
attr_reader :lexer
def initialize(blob_name, blob_content, repository: nil, nowrap: true)
@blob_name = blob_name
@blob_content = blob_content
@repository = repository
@formatter = rouge_formatter(nowrap: nowrap)
@lexer = custom_language || begin
Rouge::Lexer.guess(filename: blob_name, source: blob_content).new
rescue Rouge::Lexer::AmbiguousGuess => e
e.alternatives.sort_by(&:tag).first
end
end
2016-04-14 10:44:35 +00:00
def highlight(text, continue: true, plain: false)
2016-06-15 18:32:27 +00:00
lexer = @lexer
2016-04-14 10:44:35 +00:00
if plain
2016-06-15 18:32:27 +00:00
lexer = Rouge::Lexers::PlainText
continue = false
2016-04-14 10:44:35 +00:00
end
2016-06-15 18:32:27 +00:00
@formatter.format(@lexer.lex(text, continue: continue)).html_safe
rescue
@formatter.format(Rouge::Lexers::PlainText.lex(text)).html_safe
end
private
2016-06-21 16:23:42 +00:00
def custom_language
language_name = @repository && @repository.gitattribute(@blob_name, 'gitlab-language')
2016-06-21 16:23:42 +00:00
return nil unless language_name
2016-06-21 16:23:42 +00:00
Rouge::Lexer.find_fancy(language_name)
2016-06-21 16:23:42 +00:00
end
def rouge_formatter(options = {})
options = options.reverse_merge(
cssclass: 'code highlight',
lineanchors: true,
lineanchorsid: 'LC'
)
Rouge::Formatters::HTMLGitlab.new(options)
end
end
end