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-07-14 14:40:55 -04:00
|
|
|
def initialize(blob_name, blob_content, repository: nil)
|
2017-03-10 16:34:29 -05:00
|
|
|
@formatter = Rouge::Formatters::HTMLGitlab
|
2016-06-10 18:42:43 -04:00
|
|
|
@repository = repository
|
2016-07-14 14:40:55 -04:00
|
|
|
@blob_name = blob_name
|
2016-07-14 14:44:59 -04:00
|
|
|
@blob_content = blob_content
|
2016-06-10 18:42:43 -04:00
|
|
|
end
|
|
|
|
|
2016-04-14 06:44:35 -04:00
|
|
|
def highlight(text, continue: true, plain: false)
|
|
|
|
if plain
|
2016-07-14 14:44:59 -04:00
|
|
|
hl_lexer = Rouge::Lexers::PlainText
|
2016-06-15 14:32:27 -04:00
|
|
|
continue = false
|
2016-07-14 14:44:59 -04:00
|
|
|
else
|
|
|
|
hl_lexer = self.lexer
|
2016-04-14 06:44:35 -04:00
|
|
|
end
|
2016-06-15 14:32:27 -04:00
|
|
|
|
2017-03-10 16:34:29 -05:00
|
|
|
@formatter.format(hl_lexer.lex(text, continue: continue), tag: hl_lexer.tag).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-07-14 14:44:59 -04:00
|
|
|
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
|
2016-07-14 14:44:59 -04:00
|
|
|
e.alternatives.sort_by(&:tag).first
|
|
|
|
end
|
|
|
|
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-14 09:11:50 -05:00
|
|
|
end
|
|
|
|
end
|