Class: Banzai::Filter::SyntaxHighlightFilter

Inherits:
HTML::Pipeline::Filter
  • Object
show all
Includes:
OutputSafety
Defined in:
lib/banzai/filter/syntax_highlight_filter.rb

Overview

HTML Filter to highlight fenced code blocks

Constant Summary collapse

PARAMS_DELIMITER =
':'
LANG_PARAMS_ATTR =
'data-lang-params'

Instance Method Summary collapse

Methods included from OutputSafety

#escape_once

Instance Method Details

#callObject


16
17
18
19
20
21
22
# File 'lib/banzai/filter/syntax_highlight_filter.rb', line 16

def call
  doc.search('pre:not([data-math-style]):not([data-mermaid-style]) > code').each do |node|
    highlight_node(node)
  end

  doc
end

#highlight_node(node) ⇒ Object


24
25
26
27
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
# File 'lib/banzai/filter/syntax_highlight_filter.rb', line 24

def highlight_node(node)
  css_classes = +'code highlight js-syntax-highlight'
  lang, lang_params = parse_lang_params(node.attr('lang'))
  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}" if language
  rescue
    # 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

  highlighted = %(<pre class="#{css_classes}"
                       lang="#{language}"
                       #{lang_params}
                       v-pre="true"><code>#{code}</code></pre>)

  # Extracted to a method to measure it
  replace_parent_pre_element(node, highlighted)
end