debian-mirror-gitlab/lib/banzai/filter/syntax_highlight_filter.rb

57 lines
1.5 KiB
Ruby
Raw Normal View History

2015-09-25 12:07:36 +05:30
require 'rouge/plugins/redcarpet'
2015-12-23 02:04:40 +05:30
module Banzai
module Filter
2015-09-25 12:07:36 +05:30
# HTML Filter to highlight fenced code blocks
#
class SyntaxHighlightFilter < HTML::Pipeline::Filter
def call
doc.search('pre > code').each do |node|
highlight_node(node)
end
doc
end
def highlight_node(node)
2017-08-17 22:00:37 +05:30
language = node.attr('lang')
2016-09-13 17:45:13 +05:30
code = node.text
2016-08-24 12:49:21 +05:30
css_classes = "code highlight"
2016-09-13 17:45:13 +05:30
lexer = lexer_for(language)
2017-08-17 22:00:37 +05:30
lang = lexer.tag
2016-08-24 12:49:21 +05:30
2015-09-25 12:07:36 +05:30
begin
2017-08-17 22:00:37 +05:30
code = Rouge::Formatters::HTMLGitlab.format(lex(lexer, code), tag: lang)
2016-08-24 12:49:21 +05:30
2017-08-17 22:00:37 +05:30
css_classes << " js-syntax-highlight #{lang}"
2015-09-25 12:07:36 +05:30
rescue
2017-08-17 22:00:37 +05:30
lang = nil
2015-09-25 12:07:36 +05:30
# Gracefully handle syntax highlighter bugs/errors to ensure
# users can still access an issue/comment/etc.
end
2017-08-17 22:00:37 +05:30
highlighted = %(<pre class="#{css_classes}" lang="#{lang}" v-pre="true"><code>#{code}</code></pre>)
2016-08-24 12:49:21 +05:30
# Extracted to a method to measure it
replace_parent_pre_element(node, highlighted)
2015-09-25 12:07:36 +05:30
end
private
2016-09-13 17:45:13 +05:30
# Separate method so it can be instrumented.
def lex(lexer, code)
lexer.lex(code)
end
def lexer_for(language)
(Rouge::Lexer.find(language) || Rouge::Lexers::PlainText).new
end
2016-08-24 12:49:21 +05:30
def replace_parent_pre_element(node, highlighted)
# Replace the parent `pre` element with the entire highlighted block
node.parent.replace(highlighted)
end
2015-09-25 12:07:36 +05:30
end
end
end