Class: Banzai::Filter::SyntaxHighlightFilter
- Inherits:
-
HTML::Pipeline::Filter
- Object
- HTML::Pipeline::Filter
- Banzai::Filter::SyntaxHighlightFilter
- Includes:
- OutputSafety
- Defined in:
- lib/banzai/filter/syntax_highlight_filter.rb
Overview
HTML Filter to highlight fenced code blocks
Constant Summary collapse
- LANG_PARAMS_DELIMITER =
':'
- LANG_PARAMS_ATTR =
'data-lang-params'
- CSS =
'pre:not([data-math-style]):not([data-mermaid-style]):not([data-kroki-style]) > code:only-child'
- XPATH =
Gitlab::Utils::Nokogiri.css_to_xpath(CSS).freeze
Instance Method Summary collapse
Methods included from OutputSafety
Instance Method Details
#call ⇒ Object
20 21 22 23 24 25 26 |
# File 'lib/banzai/filter/syntax_highlight_filter.rb', line 20 def call doc.xpath(XPATH).each do |node| highlight_node(node) end doc end |
#highlight_node(node) ⇒ Object
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/banzai/filter/syntax_highlight_filter.rb', line 28 def highlight_node(node) css_classes = +'code highlight js-syntax-highlight' lang, lang_params = parse_lang_params(node) sourcepos = node.parent.attr('data-sourcepos') retried = false if use_rouge?(lang) lexer = lexer_for(lang) language = lexer.tag else lexer = Rouge::Lexers::PlainText.new language = lang end begin code = Rouge::Formatters::HTMLGitlab.format(lex(lexer, node.text), tag: language) css_classes << " language-#{language}" if language rescue StandardError # Gracefully handle syntax highlighter bugs/errors to ensure users can # still access an issue/comment/etc. First, retry with the plain text # filter. If that fails, then just skip this entirely, but that would # be a pretty bad upstream bug. return if retried language = nil lexer = Rouge::Lexers::PlainText.new retried = true retry end sourcepos_attr = sourcepos ? "data-sourcepos=\"#{escape_once(sourcepos)}\"" : '' highlighted = %(<div class="gl-relative markdown-code-block js-markdown-code"><pre #{sourcepos_attr} class="#{css_classes}" lang="#{language}" #{lang_params} v-pre="true"><code>#{code}</code></pre><copy-code></copy-code></div>) # Extracted to a method to measure it replace_parent_pre_element(node, highlighted) end |