Skip to content

Instantly share code, notes, and snippets.

@frohoff
Created August 9, 2015 20:06
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 frohoff/7eaff168323406cdc283 to your computer and use it in GitHub Desktop.
Save frohoff/7eaff168323406cdc283 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'open3'
def replace(md, strip=false)
rex = /```([a-zA-Z]+)\n(([^`\n]{3,}\n)*)```\s*```mdexec\n([^`\n]{3,}\n)*```/
replaced = md.gsub(rex) do |rep|
int, code = $1, $2
if !strip
stdin, stdout, stderr = Open3.popen3(int)
stdin.write(code)
stdin.close
out = stdout.read.strip + "\n"
else
out = ""
end
"```#{int}\n#{code}```\n```mdexec\n#{out}```"
end
replaced
end
strip = !ARGV.delete("-s").nil?
files = ARGV
if files.size > 0
files.each do |f|
txt = File.read(f)
txt = replace(txt, strip)
File.open(f, "w") { |file| file.write(txt) }
end
else
puts replace(STDIN.read)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment