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

55 lines
1.5 KiB
Ruby
Raw Normal View History

module Gitlab
class Highlight
def self.highlight(blob_name, blob_content, repository: nil, plain: false)
new(blob_name, blob_content, repository: repository).
2016-04-14 06:44:35 -04: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
def initialize(blob_name, blob_content, repository: nil)
2016-06-15 17:01:47 -04:00
@formatter = Rouge::Formatters::HTMLGitlab.new
@repository = repository
@blob_name = blob_name
@blob_content = blob_content
end
2016-04-14 06:44:35 -04:00
def highlight(text, continue: true, plain: false)
if plain
hl_lexer = Rouge::Lexers::PlainText
2016-06-15 14:32:27 -04:00
continue = false
else
hl_lexer = self.lexer
2016-04-14 06:44:35 -04:00
end
2016-06-15 14:32:27 -04:00
@formatter.format(hl_lexer.lex(text, continue: continue)).html_safe
rescue
@formatter.format(Rouge::Lexers::PlainText.lex(text)).html_safe
end
def lexer
@lexer ||= custom_language || begin
2016-07-14 15:21:22 -04:00
Rouge::Lexer.guess(filename: @blob_name, source: @blob_content).new
rescue Rouge::Guesser::Ambiguous => e
e.alternatives.sort_by(&:tag).first
end
end
private
2016-06-21 12:23:42 -04:00
def custom_language
language_name = @repository && @repository.gitattribute(@blob_name, 'gitlab-language')
2016-06-21 12:23:42 -04:00
return nil unless language_name
2016-06-21 12:23:42 -04:00
Rouge::Lexer.find_fancy(language_name)
2016-06-21 12:23:42 -04:00
end
end
end