class Conversio::Pygmentizer
Public Class Methods
respond_to?( command )
click to toggle source
# File lib/conversio/pygmentizer.rb 6 def self.respond_to?( command ) 7 return true if `which #{command}`.empty? 8 return false 9 end
run(command, input='')
click to toggle source
# File lib/conversio/pygmentizer.rb 11 def self.run(command, input='') 12 puts command if $DEBUG 13 IO.popen(command, 'r+') do |io| 14 io.puts input 15 io.close_write 16 return io.read 17 end 18 end
Public Instance Methods
block_to_html(block)
click to toggle source
# File lib/conversio/pygmentizer.rb 57 def block_to_html(block) 58 style = get_style(block[0]) 59 unless style.empty? then 60 # remove the style information from the code block 61 block.slice!(0) 62 output(highlight(block.join("\n"),style)) 63 else 64 # Code blocks without style information will be 65 # put to output includeing the 4 leading spaces 66 block.each {|line| output(" #{line}") } 67 output("") 68 end 69 end
get_style(string)
click to toggle source
# File lib/conversio/pygmentizer.rb 72 def get_style(string) 73 return string.gsub(/--/,'').strip if string =~ /^--[a-z]* */ 74 return "" 75 end
highlight(string, style)
click to toggle source
# File lib/conversio/pygmentizer.rb 77 def highlight(string, style) 78 return Pygmentizer::run("pygmentize -f html -l #{style}", string) << "\n" 79 end
output(string)
click to toggle source
# File lib/conversio/pygmentizer.rb 22 def output(string) 23 @output << "#{string}\n" 24 end
transform_code_blocks(text)
click to toggle source
# File lib/conversio/pygmentizer.rb 26 def transform_code_blocks(text) 27 raise RuntimeError, "pygmentize not in path" if 28 Pygmentizer::respond_to?("pygmentize") 29 @input_by_line = Array.new 30 text.each_line { |line| @input_by_line << line.chop } 31 @output = String.new 32 buffer = Array.new 33 rec = false 34 @input_by_line.each do |line| 35 # true if a Markdown code block is found 36 rec = true if !rec and line =~ /^ / 37 # store the code block into buffer 38 if rec and line =~ /^ / then 39 # remove the leading 4 spaces 40 line = line.gsub(/^ /,'') 41 buffer << line 42 # End of code block 43 elsif rec 44 block_to_html(buffer) 45 # Wipe the buffer 46 buffer.clear 47 rec = false 48 # Anyting beside code blocks will be output 49 else 50 output(line) 51 end 52 end 53 return @output 54 end