#!/usr/bin/python # $Source: /cvsroot/mathtran/client/bookmarklet/generate.py,v $ # $Revision: 1.5 $ '''Script to create MathTran bookmarklets.''' import re from cgi import escape # Tim Hunt's bookmarklet code, taken from # http://www.mathtran.org/wiki/index.php?title=MathTran_bookmarklet&diff=1425&oldid=1424 # Split the code into tokens. split = re.compile(r'(\w+)').split class Compressor(object): def __init__(self): self._dict = {} def translate(self, tok): if '_' not in tok: return tok _dict = self._dict if tok not in _dict: _dict[tok] = chr(len(_dict)+ord('a')) return _dict[tok] def create_bookmarklets(data): bookmarklets = [] for item in data[1:]: lines = [line.strip() for line in item.split('\n')] lines = [line for line in lines if not line.startswith('//')] lines = lines[1:] toks = [tok for line in lines for tok in split(line)] compress = Compressor().translate new_toks = [compress(tok) for tok in toks] stuff = "(" + ''.join(new_toks) + ")()" bookmarklets.append(stuff) return bookmarklets TEMPLATE = '''\
The equation $$x^2+y^2=1$$
''' for name in 'firefox ie6'.split(): data = file(name+'.js').read().split('// BOOKMARKLET\n') bookmarklets = create_bookmarklets(data) print name, [len(item) for item in bookmarklets] bookmarklets = [escape(item, quote=True) for item in bookmarklets] fd = file("test_%s.html" %name, 'w') fd.write(TEMPLATE % tuple(bookmarklets)) fd.close()