Class: Albino

Inherits:
Object
  • Object
show all
Defined in:
lib/jekyll/albino.rb

Overview

Wrapper for the Pygments command line tool, pygmentize.

Pygments: pygments.org/

Assumes pygmentize is in the path. If not, set its location with Albino.bin = ‘/path/to/pygmentize’

Use like so:

@syntaxer = Albino.new('/some/file.rb', :ruby)
puts @syntaxer.colorize

This’ll print out an HTMLized, Ruby-highlighted version of ‘/some/file.rb’.

To use another formatter, pass it as the third argument:

@syntaxer = Albino.new('/some/file.rb', :ruby, :bbcode)
puts @syntaxer.colorize

You can also use the #colorize class method:

puts Albino.colorize('/some/file.rb', :ruby)

Another also: you get a #to_s, for somewhat nicer use in Rails views.

... helper file ...
def highlight(text)
  Albino.new(text, :ruby)
end

... view file ...
<%= highlight text %>

The default lexer is ‘text’. You need to specify a lexer yourself; because we are using STDIN there is no auto-detect.

To see all lexers and formatters available, run ‘pygmentize -L`.

Chris Wanstrath // [email protected]

GitHub // http://github.com

Constant Summary collapse

@@bin =
Rails.development? ? 'pygmentize' : '/usr/bin/pygmentize' rescue 'pygmentize'

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(target, lexer = :text, format = :html) ⇒ Albino

Returns a new instance of Albino.



56
57
58
59
# File 'lib/jekyll/albino.rb', line 56

def initialize(target, lexer = :text, format = :html)
  @target  = target
  @options = { :l => lexer, :f => format, :O => 'encoding=utf-8' }
end

Class Method Details

.bin=(path) ⇒ Object



48
49
50
# File 'lib/jekyll/albino.rb', line 48

def self.bin=(path)
  @@bin = path
end

.colorize(*args) ⇒ Object



52
53
54
# File 'lib/jekyll/albino.rb', line 52

def self.colorize(*args)
  new(*args).colorize
end

Instance Method Details

#colorize(options = {}) ⇒ Object Also known as: to_s



71
72
73
74
75
# File 'lib/jekyll/albino.rb', line 71

def colorize(options = {})
  html = execute(@@bin + convert_options(options))
  # Work around an RDiscount bug: http://gist.github.com/97682
  html.to_s.sub(%r{</pre></div>\Z}, "</pre>\n</div>")
end

#convert_options(options = {}) ⇒ Object



78
79
80
81
82
# File 'lib/jekyll/albino.rb', line 78

def convert_options(options = {})
  @options.merge(options).inject('') do |string, (flag, value)|
    string + " -#{flag} #{value}"
  end
end

#execute(command) ⇒ Object



61
62
63
64
65
66
67
68
69
# File 'lib/jekyll/albino.rb', line 61

def execute(command)
  output = ''
  IO.popen(command, mode='r+') do |p|
    p.write @target
    p.close_write
    output = p.read.strip
  end
  output
end