Class: Conversio::Pygmentizer

Inherits:
Object
  • Object
show all
Defined in:
lib/conversio/pygmentizer.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.respond_to?(command) ⇒ Boolean

Returns:

  • (Boolean)


6
7
8
9
# File 'lib/conversio/pygmentizer.rb', line 6

def self.respond_to?( command )
  return true if `which #{command}`.empty?
  return false
end

.run(command, input = '') ⇒ Object



11
12
13
14
15
16
17
18
# File 'lib/conversio/pygmentizer.rb', line 11

def self.run(command, input='')
 puts command if $DEBUG
 IO.popen(command, 'r+') do |io|
   io.puts input
   io.close_write
   return io.read
 end
end

Instance Method Details

#block_to_html(block) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/conversio/pygmentizer.rb', line 57

def block_to_html(block)
  style = get_style(block[0])
  unless style.empty? then
    # remove the style information from the code block
    block.slice!(0)
    output(highlight(block.join("\n"),style))
  else
    # Code blocks without style information will be
    # put to output includeing the 4 leading spaces
    block.each {|line| output("    #{line}") }
    output("")
  end
end

#get_style(string) ⇒ Object



72
73
74
75
# File 'lib/conversio/pygmentizer.rb', line 72

def get_style(string)
  return string.gsub(/--/,'').strip if string =~ /^--[a-z]* */
  return ""
end

#highlight(string, style) ⇒ Object



77
78
79
# File 'lib/conversio/pygmentizer.rb', line 77

def highlight(string, style)
  return Pygmentizer::run("pygmentize -f html -l #{style}", string) << "\n"
end

#output(string) ⇒ Object



22
23
24
# File 'lib/conversio/pygmentizer.rb', line 22

def output(string)
  @output << "#{string}\n"
end

#transform_code_blocks(text) ⇒ Object

Raises:

  • (RuntimeError)


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
# File 'lib/conversio/pygmentizer.rb', line 26

def transform_code_blocks(text)
  raise RuntimeError, "pygmentize not in path" if 
  Pygmentizer::respond_to?("pygmentize")
  @input_by_line = Array.new 
  text.each_line { |line| @input_by_line << line.chop }
  @output = String.new
  buffer = Array.new
  rec = false
  @input_by_line.each do |line|
    # true if a Markdown code block is found
    rec = true if !rec and line =~ /^    /
    # store the code block into buffer
    if rec and line =~ /^    / then
      # remove the leading 4 spaces
      line = line.gsub(/^    /,'')
      buffer << line
    # End of code block
    elsif rec 
      block_to_html(buffer)
      # Wipe the buffer
      buffer.clear
      rec = false
    # Anyting beside code blocks will be output
    else 
      output(line)
    end
  end
  return @output
end