Class: Mato::HtmlFilters::SyntaxHighlight

Inherits:
Object
  • Object
show all
Defined in:
lib/mato/html_filters/syntax_highlight.rb

Defined Under Namespace

Classes: RougeError

Instance Method Summary collapse

Constructor Details

#initialize(on_rouge_error: ->(ex) { warn ex }) ⇒ SyntaxHighlight

Returns a new instance of SyntaxHighlight.



11
12
13
# File 'lib/mato/html_filters/syntax_highlight.rb', line 11

def initialize(on_rouge_error: ->(ex) { warn ex })
  @on_rouge_error = on_rouge_error
end

Instance Method Details

#call(doc) ⇒ Object

Parameters:

  • doc (Nokogiri::HTML4::DocumentFragment)


16
17
18
19
20
21
22
# File 'lib/mato/html_filters/syntax_highlight.rb', line 16

def call(doc)
  doc.search("pre").each do |pre|
    if pre.at('code')
      pre.replace(highlight(pre))
    end
  end
end

#guess_lexer(language, filename, source) ⇒ Rouge::Lexer

Parameters:

  • language (String)
  • filename (String)
  • source (String)

Returns:

  • (Rouge::Lexer)


28
29
30
31
32
33
34
# File 'lib/mato/html_filters/syntax_highlight.rb', line 28

def guess_lexer(language, filename, source)
  Rouge::Lexer.find(language)&.tap do |lexer|
    return lexer.new
  end

  Rouge::Lexer.guess(filename: filename, source: source, &:first).new
end

#parse_label(class_name) ⇒ Object

Parameters:

  • CSS (String, nil)

    class names, e.g. “foo.js” “ruby:foo.rb”



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/mato/html_filters/syntax_highlight.rb', line 37

def parse_label(class_name)
  a = class_name&.split(/:/) || []
  if a.empty?
    {}
  elsif a.size == 1
    token = a[0].sub(/^language-/, '')
    if Rouge::Lexer.find(token)
      { language: token }
    else
      { filename: token }
    end
  else
    { language: a[0], filename: a[1] }
  end
end