Skip to content

Instantly share code, notes, and snippets.

@jdhuntington
Created October 26, 2012 22:04
Show Gist options
  • Save jdhuntington/3961836 to your computer and use it in GitHub Desktop.
Save jdhuntington/3961836 to your computer and use it in GitHub Desktop.
Preview markdown in browser
#!/usr/bin/env ruby
require 'tempfile'
require 'rubygems'
require 'kramdown'
abort "Usage: #{__FILE__} <target file path>" unless ARGV[0]
TARGET_FILE = File.expand_path(ARGV[0])
OUTPUT_FILE = begin
f = Tempfile.new('markdown')
f.close
File.expand_path(f.path + ".html")
ensure
f.unlink
end
# Fetch bootstrap css if it doesn't exist
BOOTSTRAP_FILE_LOCATION = begin
f = Tempfile.new('bootstrap.css')
f.close
File.expand_path(f.path + ".css")
ensure
f.unlink
end
BOOTSTRAP_URL = "http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.0.4/css/bootstrap.min.css"
def open_in_browser
`open #{OUTPUT_FILE}`
end
def ensure_bootstrap_local
unless File.exist?(BOOTSTRAP_FILE_LOCATION)
out = `curl -s #{BOOTSTRAP_URL} > #{BOOTSTRAP_FILE_LOCATION}`
end
end
def body
Kramdown::Document.new(File.read(TARGET_FILE)).to_html
end
def header
<<EOS
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#{ARGV[0].inspect} preview</title>
<link href="file://#{BOOTSTRAP_FILE_LOCATION}" rel="stylesheet">
<head><body><div class="container">
EOS
end
def footer
"</div></body></html>"
end
def convert_target
File.open(OUTPUT_FILE, 'w') do |f|
f.print header
f.print body
f.print footer
end
end
filestat = nil
ensure_bootstrap_local
STDERR.puts "Watching #{TARGET_FILE} for changes."
while true
if (new_filestat = File.stat(TARGET_FILE)) != filestat
filestat = new_filestat
convert_target
open_in_browser
end
sleep 0.3
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment