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