Skip to content

Instantly share code, notes, and snippets.

@bmabey
Forked from nakajima/makers-mark.rb
Created February 27, 2009 18:14
Show Gist options
  • Save bmabey/71612 to your computer and use it in GitHub Desktop.
Save bmabey/71612 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'rubygems'
require 'tempfile'
require 'nokogiri'
require 'rdiscount'
# makers-mark
#
# Generates HTML from Markdown, replacing code blocks with syntax
# highlighted snippets (using the python pygments library).
#
# USAGE
#
# $ makers-mark README.md
#
# or
#
# $ cat README | makers-mark
class MakersMark
def self.parse(argv)
if idx = argv.index('-l') || argv.index('--lexer')
lexer = argv.delete(argv[idx+1])
argv.delete(argv[idx])
else
lexer = 'ruby'
end
content = argv.first ? File.read(argv.first) : $stdin.read
content = RDiscount.new(content).to_html
doc = Nokogiri::HTML(content)
doc.search('pre code').each do |snippet|
new(snippet, :lexer => lexer).highlight!
end
puts doc.at('body').children.to_s
end
def initialize(doc, opts)
@doc, @opts = doc, opts
end
def highlight!
begin ; @doc.replace Nokogiri::HTML(run).at('div')
ensure ; file.close! ; end
end
private
def run
`pygmentize -f html -l #{@opts[:lexer]} #{file.path}`
end
def file
@file ||= begin
tmp = Tempfile.new('to-highlight')
File.open(tmp.path, 'w+') { |f| f << @doc.children.to_s }
tmp
end
end
end
MakersMark.parse(ARGV.dup)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment