2016-01-14 14:11:50 +00:00
|
|
|
module Gitlab
|
|
|
|
class Highlight
|
2016-06-15 18:52:23 +00:00
|
|
|
def self.highlight(blob_name, blob_content, repository: nil, plain: false)
|
|
|
|
new(blob_name, blob_content, repository: repository).
|
2016-04-14 10:44:35 +00:00
|
|
|
highlight(blob_content, continue: false, plain: plain)
|
2016-01-14 14:11:50 +00:00
|
|
|
end
|
|
|
|
|
2016-01-14 21:28:07 +00:00
|
|
|
def self.highlight_lines(repository, ref, file_name)
|
|
|
|
blob = repository.blob_at(ref, file_name)
|
|
|
|
return [] unless blob
|
|
|
|
|
2016-02-01 12:51:05 +00:00
|
|
|
blob.load_all_data!(repository)
|
2016-06-10 22:42:43 +00:00
|
|
|
highlight(file_name, blob.data, repository: repository).lines.map!(&:html_safe)
|
2016-01-14 21:28:07 +00:00
|
|
|
end
|
|
|
|
|
2016-06-15 18:52:23 +00:00
|
|
|
def initialize(blob_name, blob_content, repository: nil)
|
|
|
|
@formatter = rouge_formatter
|
2016-06-10 22:42:43 +00:00
|
|
|
@repository = repository
|
|
|
|
@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
|
2016-01-19 14:13:37 +00:00
|
|
|
rescue
|
|
|
|
@formatter.format(Rouge::Lexers::PlainText.lex(text)).html_safe
|
2016-01-19 13:52:41 +00:00
|
|
|
end
|
|
|
|
|
2016-01-14 14:11:50 +00:00
|
|
|
private
|
|
|
|
|
2016-06-21 16:23:42 +00:00
|
|
|
def custom_language
|
2016-06-22 19:53:58 +00:00
|
|
|
language_name = @repository && @repository.gitattribute(@blob_name, 'gitlab-language')
|
2016-06-21 16:23:42 +00:00
|
|
|
|
2016-06-22 19:53:58 +00:00
|
|
|
return nil unless language_name
|
2016-06-21 16:23:42 +00:00
|
|
|
|
2016-06-22 19:53:58 +00:00
|
|
|
Rouge::Lexer.find_fancy(language_name)
|
2016-06-21 16:23:42 +00:00
|
|
|
end
|
|
|
|
|
2016-01-19 13:52:41 +00:00
|
|
|
def rouge_formatter(options = {})
|
2016-06-15 19:32:55 +00:00
|
|
|
Rouge::Formatters::HTMLGitlab.new
|
2016-01-14 14:11:50 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|