Skip to content

Instantly share code, notes, and snippets.

@swenson
Created August 10, 2016 22:09
Show Gist options
  • Save swenson/689c63bc202422944cadb6ab4ff0ef08 to your computer and use it in GitHub Desktop.
Save swenson/689c63bc202422944cadb6ab4ff0ef08 to your computer and use it in GitHub Desktop.
Ctags + Pygments static source generator
from collections import defaultdict
import json
import os
import os.path
import shutil
from pygments.formatters import HtmlFormatter
from pygments.lexers import get_lexer_for_filename
from pygments import highlight
files = set([])
json_out = []
tags = defaultdict(list)
for line in open('tags'):
if line.startswith('!'):
continue
l = line.strip().split('\t')
if len(l) < 3:
continue
var = l[0]
if len(var) < 2:
continue
filename = l[1]
try:
lineno = int(l[2].rstrip(';"'))
except:
continue
files.add(filename)
json_out.append(dict(s=var, f=filename, l=lineno))
if not os.path.exists('html'):
os.mkdir('html')
print "Writing %d tags to JSON" % len(json_out)
with open('html/ctags.json', 'w') as out:
json.dump(json_out, out)
print "Formatting %d files" % len(files)
index = []
for f in sorted(files):
if f.startswith('./'):
f = f[2:]
formatter = HtmlFormatter(linenos=True, cssclass="source", tagsfile='tags', full=True, lineanchors='line', anchorlinenos=True, filename=f, tagurlformat=r'/python-xr/%(path)s%(fname)s%(fext)s.html')
try:
lexer = get_lexer_for_filename(f)
except:
continue
print 'Highlighting', f
outfile = os.path.join('html', f + '.html')
dir = os.path.dirname(outfile)
if not os.path.exists(dir):
os.makedirs(dir)
with open(f) as text:
result = highlight(text.read(), lexer, formatter)
with open(outfile, 'w') as out:
out.write(result.encode('utf8'))
index.append('<li><a href="%s.html">%s</a></li>' % (f, f))
with open('html/filelist.html', 'w') as out:
out.write('<html><body><h2>File list</h2><ul>')
out.write(''.join(index))
out.write('</body></html>')
shutil.copyfile('index.html', 'html/index.html')
shutil.copyfile('typeahead.bundle.min.js', 'html/typeahead.bundle.min.js')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment