Skip to content

Instantly share code, notes, and snippets.

@carlosefonseca
Created March 11, 2014 17:29
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 carlosefonseca/9490736 to your computer and use it in GitHub Desktop.
Save carlosefonseca/9490736 to your computer and use it in GitHub Desktop.
Adds code files into markdown
#!/usr/bin/env python3
# coding=utf-8
import sys
import re
import os
import shutil
if len(sys.argv) < 2:
print("Looks for '<!-- include code somefile.ext -->' and adds somefile.ext")
print("to the markdown file as a fenced code block with the extension as the syntax.")
print("Replaces an existing block code as long as it's right below the include line.")
print("")
print("usage: %s filename" % sys.argv[0])
sys.exit(1)
fn = sys.argv[1]
with open(fn) as filein:
content = filein.readlines()
incodeblock = False
codename = None
output = ""
for l in content:
if not codename:
m = re.match("^<!--\s+include code (.*)\s+-->$", l)
if m:
codename = m.group(1)
output += l
newcontent = open(codename).read()
_, fileExtension = os.path.splitext(codename)
output += "```%s\n%s\n```\n" % (fileExtension[1:], newcontent)
else:
output += l
else:
if not incodeblock:
# ficheiro definido mas bloco de código ainda não detectado
if l.startswith("```"):
incodeblock = True
else:
if l.startswith("```"):
incodeblock = False
codename = None
shutil.copyfile(fn, fn+".bak")
open(fn, "w").write(output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment