2016-01-29 22:53:50 +05:30
|
|
|
module Gitlab
|
|
|
|
class Highlight
|
2016-08-24 12:49:21 +05:30
|
|
|
def self.highlight(blob_name, blob_content, repository: nil, plain: false)
|
|
|
|
new(blob_name, blob_content, repository: repository).
|
2016-06-02 11:05:42 +05:30
|
|
|
highlight(blob_content, continue: false, plain: plain)
|
2016-01-29 22:53:50 +05:30
|
|
|
end
|
|
|
|
|
|
|
|
def self.highlight_lines(repository, ref, file_name)
|
|
|
|
blob = repository.blob_at(ref, file_name)
|
|
|
|
return [] unless blob
|
|
|
|
|
2016-04-02 18:10:28 +05:30
|
|
|
blob.load_all_data!(repository)
|
2016-08-24 12:49:21 +05:30
|
|
|
highlight(file_name, blob.data, repository: repository).lines.map!(&:html_safe)
|
2016-01-29 22:53:50 +05:30
|
|
|
end
|
|
|
|
|
2016-08-24 12:49:21 +05:30
|
|
|
def initialize(blob_name, blob_content, repository: nil)
|
2017-08-17 22:00:37 +05:30
|
|
|
@formatter = Rouge::Formatters::HTMLGitlab
|
2016-08-24 12:49:21 +05:30
|
|
|
@repository = repository
|
|
|
|
@blob_name = blob_name
|
|
|
|
@blob_content = blob_content
|
2016-01-29 22:53:50 +05:30
|
|
|
end
|
|
|
|
|
2016-06-02 11:05:42 +05:30
|
|
|
def highlight(text, continue: true, plain: false)
|
|
|
|
if plain
|
2016-08-24 12:49:21 +05:30
|
|
|
hl_lexer = Rouge::Lexers::PlainText
|
|
|
|
continue = false
|
2016-06-02 11:05:42 +05:30
|
|
|
else
|
2016-08-24 12:49:21 +05:30
|
|
|
hl_lexer = self.lexer
|
2016-06-02 11:05:42 +05:30
|
|
|
end
|
2016-08-24 12:49:21 +05:30
|
|
|
|
2017-08-17 22:00:37 +05:30
|
|
|
@formatter.format(hl_lexer.lex(text, continue: continue), tag: hl_lexer.tag).html_safe
|
2016-01-29 22:53:50 +05:30
|
|
|
rescue
|
|
|
|
@formatter.format(Rouge::Lexers::PlainText.lex(text)).html_safe
|
|
|
|
end
|
|
|
|
|
2016-08-24 12:49:21 +05:30
|
|
|
def lexer
|
|
|
|
@lexer ||= custom_language || begin
|
|
|
|
Rouge::Lexer.guess(filename: @blob_name, source: @blob_content).new
|
|
|
|
rescue Rouge::Guesser::Ambiguous => e
|
|
|
|
e.alternatives.sort_by(&:tag).first
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2016-01-29 22:53:50 +05:30
|
|
|
private
|
|
|
|
|
2016-08-24 12:49:21 +05:30
|
|
|
def custom_language
|
|
|
|
language_name = @repository && @repository.gitattribute(@blob_name, 'gitlab-language')
|
|
|
|
|
|
|
|
return nil unless language_name
|
2016-01-29 22:53:50 +05:30
|
|
|
|
2016-08-24 12:49:21 +05:30
|
|
|
Rouge::Lexer.find_fancy(language_name)
|
2016-01-29 22:53:50 +05:30
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|