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)
|
2017-06-21 09:48:12 -04:00
|
|
|
new(blob_name, blob_content, repository: repository)
|
|
|
|
.highlight(blob_content, continue: false, plain: plain)
|
2016-01-14 09:11:50 -05:00
|
|
|
end
|
|
|
|
|
2016-07-10 17:13:06 -04:00
|
|
|
attr_reader :blob_name
|
|
|
|
|
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)
|
2016-07-10 17:13:06 -04:00
|
|
|
highlighted_text = highlight_text(text, continue: continue, plain: plain)
|
|
|
|
highlighted_text = link_dependencies(text, highlighted_text) if blob_name
|
|
|
|
highlighted_text
|
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-07-10 17:13:06 -04:00
|
|
|
|
|
|
|
def highlight_text(text, continue: true, plain: false)
|
|
|
|
if plain
|
|
|
|
highlight_plain(text)
|
|
|
|
else
|
|
|
|
highlight_rich(text, continue: continue)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def highlight_plain(text)
|
|
|
|
@formatter.format(Rouge::Lexers::PlainText.lex(text)).html_safe
|
|
|
|
end
|
|
|
|
|
|
|
|
def highlight_rich(text, continue: true)
|
|
|
|
@formatter.format(lexer.lex(text, continue: continue), tag: lexer.tag).html_safe
|
|
|
|
rescue
|
|
|
|
highlight_plain(text)
|
|
|
|
end
|
|
|
|
|
|
|
|
def link_dependencies(text, highlighted_text)
|
|
|
|
Gitlab::DependencyLinker.link(blob_name, text, highlighted_text)
|
|
|
|
end
|
2016-01-14 09:11:50 -05:00
|
|
|
end
|
|
|
|
end
|