Last active
January 4, 2016 15:29
-
-
Save tompave/8641449 to your computer and use it in GitHub Desktop.
simple markdown script. It uses Redcarpet for markdown and Rouge for code syntax highlighting.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env ruby | |
# Author: Tommaso Pavese | |
# [email protected] | |
# www.wonderingmachine.com | |
# | |
# Simple script for markdown using: | |
# | |
# Redcarpet: https://github.com/vmg/redcarpet | |
# Rouge: https://github.com/jayferd/rouge | |
# | |
require 'redcarpet' | |
require 'rouge' | |
#require 'rouge/plugins/redcarpet' | |
module MarkRedRouge | |
WITH_CODE_CSS = false | |
CODE_CSS_CLASS = "code_highlight" | |
class RougeHtmlRenderer < Redcarpet::Render::HTML | |
include Redcarpet::Render::SmartyPants | |
#include Rouge::Plugins::Redcarpet | |
def block_code(code, language) | |
lexer = Rouge::Lexer.find_fancy(language, code) || Rouge::Lexers::PlainText | |
formatter = Rouge::Formatters::HTML.new( | |
css_class: "#{CODE_CSS_CLASS} #{lexer.tag}", | |
line_numbers: true) | |
formatter.format(lexer.lex(code)) | |
end | |
end | |
class Processor | |
def initialize(file_name) | |
@input_file_name = file_name | |
build_files_and_paths | |
@parser = build_markdown_parser | |
end | |
def build_markdown_parser | |
options = { no_intra_emphasis: true, | |
fenced_code_blocks: true} | |
Redcarpet::Markdown.new(MarkRedRouge::RougeHtmlRenderer, options) | |
end | |
def parse! | |
@input_md = read_input_file | |
@output_html = @parser.render(@input_md) | |
write_output | |
end | |
def build_files_and_paths | |
@input_file_path = File.expand_path @input_file_name | |
abort("input file doesn't exist") unless File.exists? @input_file_path | |
ext = File.extname @input_file_name | |
base = File.basename @input_file_name, ext | |
dir = File.dirname @input_file_path | |
@output_file_path = File.join dir, "#{base}.html" | |
end | |
def read_input_file | |
File.read(@input_file_path) | |
rescue | |
abort("input file can't be read") | |
end | |
def try_css(file) | |
if WITH_CODE_CSS | |
css = Rouge::Themes::Github.render(scope: ".#{CODE_CSS_CLASS}") | |
file.write "<style>\n" | |
file.write css | |
file.write "\n</style>" | |
end | |
end | |
def write_output | |
File.open(@output_file_path, 'w') do |file| | |
try_css file | |
file.write @output_html | |
end | |
rescue | |
puts "error while writing the output" | |
end | |
end | |
end | |
abort("no input file provided") unless ARGV[0] | |
processor = MarkRedRouge::Processor.new(ARGV[0]) | |
processor.parse! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment