Class: TextUtils::CodeHighlighter

Inherits:
Processor
  • Object
show all
Defined in:
lib/text_utils/code_highlighter.rb

Instance Method Summary collapse

Methods inherited from Processor

#initialize

Constructor Details

This class inherits a constructor from TextUtils::Processor

Instance Method Details

#call(data, env) ⇒ Object

highlights code inside of <code lang/language=‘java’> … code … </code>



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/text_utils/code_highlighter.rb', line 3

def call data, env
  require 'nokogiri'

  snippets = {}

  # processign html :code tags
  data = data.gsub /(<code.*?>)(.+?)(<\/code\s*>)/im do
    node = Nokogiri::HTML($1 + $3).css('code').first
    language = node.attributes['lang'].try(:value) || node.attributes['language'].try(:value)
    code = $2

    if language and code
      attributes = {}; node.attributes.each{|name, value| attributes[name] = value.value}
      code = colorize code, language, attributes
      cut_snippet snippets, code
    else
      $&
    end
  end

  # processign markdown ``` tags
  data = data.gsub /^```\s*([a-z\-_0-9]+)\s*\n(.+?)^```\s*$/im do
    language, code = $1, $2

    if language and code
      code = colorize code, language, {language: language}
      cut_snippet snippets, code
    else
      $&
    end
  end

  data = call_next data, env

  restore_snippet snippets, data
end