Skip to content


Static HTML Embedded Gists

I use GitHub a lot, and one of my favorite features are "Gists". They’re basically just a fancy way to share code snippets, but backed up by a mini Git repo. They also allow you to embed syntax highlighted source code into other web pages.

One thing I didn’t really like is that embedding a Gist into a page requires a lot of Javascript and HTTPS requests to the GitHub servers. It’s not a huge deal, but it slows things down a little bit.

So, I created the script below. It takes a Gist ID as a command line parameter, downloads it and runs the Javascript code through Qt’s Javascript interpreter. It intercepts the document.write calls to get the raw HTML. The results can be pasted into a static HTML page, or in this case a blog entry as raw HTML.

To reduce HTTP traffic and speed things up even more, the script strips out the link to GitHub’s gist stylesheet. To compensate, I added the content of that stylesheet to the stylesheet for the WordPress theme I’m using. I also had to tweak the rule for ".gist .gist-file .gist-data pre" a little bit, to set the line-height property back to 1.

In all honesty, executing the Javascript here is overkill. A few calls to string.replace() would be as effective and probably faster. But that wouldn’t give me an excuse to play with using Qt’s Javascript engine from Python :-)

#!/usr/bin/env python3
import urllib.request
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
from PyQt4.QtScript import QScriptEngine, QScriptValue
def doc_write(context, eng):
    if context.argumentCount() != 0:
        na = context.argumentCount()
        args = list()
        for i in range(na):
            args.append( str(context.argument(i).toVariant()))
        temp = ' '.join(args)
        # if not 'embed.css' in temp: broke when running the script on itself!
        if not temp.startswith('<link rel="stylesheet"'):
            temp = temp.replace("\n", '')
            print(temp)
    return QScriptValue('')
def main(args):
    gist_id = None
    if len(sys.argv) > 1:
        gist_id = args[0]
    else:
        print("No Gist ID given!")
        exit(0)
    url = "https://gist.github.com/{gist_id}.js".format(gist_id=gist_id)
    app = QtCore.QCoreApplication(args)
    qse = QScriptEngine()
    dw = qse.newFunction(doc_write)
    qse.globalObject().setProperty('doc_write', dw)
    
    fh = urllib.request.urlopen(url)
    gist_script = fh.read().decode('utf-8')
    gist_script = gist_script.replace('doc_write', 'doc_write')
    res = qse.evaluate(gist_script)
if __name__ == "__main__":
    main(sys.argv[1:])
view raw gisthtml.py This Gist brought to you by GitHub.

Posted in coding, computers. Tagged with , , , , , , .

0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.