Skip to content

Instantly share code, notes, and snippets.

@caius
Created July 3, 2016 10:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save caius/f030b0af95e41821c87c60686a1c5898 to your computer and use it in GitHub Desktop.
Save caius/f030b0af95e41821c87c60686a1c5898 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# Converts a markdown file from 4-space code blocks to ``` gated code blocks.
# aka, normal markdown code blocks to Github Formatted markdown code blocks.
#
# Usage:
#
# ruby gfm_code_block.rb path/to/file.md
#
require "tempfile"
require "pathname"
DELIM = " "
def gfmify(input, output)
input.each_line.each_cons(3) do |(prev_line, line, next_line)|
# If we've not written anything, print out prev line
# Bug - we don't handle ` ` being on the first line of file
if output.pos.zero?
output.print prev_line
end
if line.start_with?(DELIM)
# Ticks go before first line in block
output.puts "```" unless prev_line.start_with?(DELIM)
# De-indent one tabstop
line = line[4..-1]
# Ticks come after last line in block
line << "```\n" unless next_line.start_with?(DELIM)
end
output.print line
# Make sure to output the last line
output.print next_line if input.eof?
end
end
ARGV.each do |path|
path = Pathname.new(path)
Tempfile.open(path.basename.to_s) do |tmpfile|
gfmify path.open("r"), tmpfile
FileUtils.mv tmpfile.path, path.to_s
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment