diff options
author | wiemann <wiemann@929543f6-e4f2-0310-98a6-ba3bd3dd1d04> | 2006-01-09 20:44:25 +0000 |
---|---|---|
committer | wiemann <wiemann@929543f6-e4f2-0310-98a6-ba3bd3dd1d04> | 2006-01-09 20:44:25 +0000 |
commit | d77fdfef70e08114f57cbef5d91707df8717ea9f (patch) | |
tree | 49444e3486c0c333cb7b33dfa721296c08ee4ece /sandbox/cben/rolehack | |
parent | 53cd16ca6ca5f638cbe5956988e88f9339e355cf (diff) | |
parent | 3993c4097756e9885bcfbd07cb1cc1e4e95e50e4 (diff) | |
download | docutils-0.4.tar.gz |
Release 0.4: tagging released revisiondocutils-0.4
git-svn-id: http://svn.code.sf.net/p/docutils/code/tags/docutils-0.4@4268 929543f6-e4f2-0310-98a6-ba3bd3dd1d04
Diffstat (limited to 'sandbox/cben/rolehack')
-rw-r--r-- | sandbox/cben/rolehack/README.txt | 66 | ||||
-rwxr-xr-x | sandbox/cben/rolehack/imgmathhack.py | 98 | ||||
-rwxr-xr-x | sandbox/cben/rolehack/mathhack.py | 27 | ||||
-rw-r--r-- | sandbox/cben/rolehack/rolehack.py | 192 |
4 files changed, 0 insertions, 383 deletions
diff --git a/sandbox/cben/rolehack/README.txt b/sandbox/cben/rolehack/README.txt deleted file mode 100644 index 1ec7d8bda..000000000 --- a/sandbox/cben/rolehack/README.txt +++ /dev/null @@ -1,66 +0,0 @@ -Mathhack Instructions -===================== - -Formula syntax is everything LaTeX supports in math mode. This is supported -for the LaTeX writer and for anything else by converting with LaTeX (and some -external_ commands) to *images*. - -There are now other solutions (see the FAQ entry__) that employ dialects of -LaTeX for translation to MathML so you should consider limiting yourself to -the intersection of the syntaxes if you want to allow all possible convertions. - -__ http://docutils.sourceforge.net/ - FAQ.html#how-can-i-include-mathematical-equations-in-documents - -Just write:: - - text... :texmath:`formula` ...text - -or simply:: - - text... `formula` ...text - -for inline formulas; for display formulas use a directive:: - - .. texmath:: formula - -Inline formulas can also be written with substitution references:: - - text... |name| ...text - - .. |name| texmath:: formula - -Now you take this (in file foo.txt) and run:: - - mathhack.py foo.txt | rst2latex.py - foo.tex - -which converts the roles/directives to ``raw:: latex`` directives or:: - - imgmathhack.py foo.txt | html.py - foo.html - -which runs TeX (generating images into a subdirectory!) and converts -the roles/directives into ``img::`` directives. Quick, dirty and -convenient ;-). - -To allow including preprocessed files, do:: - - mathhack.py included.txt > included.txt.mathhack - imgmathhack.py included.txt > included.txt.imgmathhack - -and include ``included.txt.mathhack`` (imgmathhack.py will mangle this to -include ``included.txt.imgmathhack`` automatically). My makefile_ can do all -this for you (just set ENABLE_MATHHACK=1). - -.. _makefile: ../make/Makefile.docutils - -.. _external: - -Note that the `<imgmathhack.py>`_ script relies on some external commands (see -the comments at its top). `tex_to_images` seems to be separately availiable -from the `speech_tools CVS`__ - -__ http://cvs.sf.net/viewcvs.py/*checkout*/emu/speech_tools/scripts/tex_to_images.prl?rev=HEAD - -Also note that the scripts use regexps to "parse" the roles/directives, so -expect some bugs (e.g. don't try to split a formula into multiple lines inside -a table cell...). diff --git a/sandbox/cben/rolehack/imgmathhack.py b/sandbox/cben/rolehack/imgmathhack.py deleted file mode 100755 index 084dc05f0..000000000 --- a/sandbox/cben/rolehack/imgmathhack.py +++ /dev/null @@ -1,98 +0,0 @@ -#!/usr/bin/env python -""" -Convert latex math to images. Treats the default and ``texmath`` roles as -inline LaTeX math and the ``texmath::`` directive as display latex math. - -If you include a file which also needs mathhack/imgmathhack preprocessing, -write a name containing ``.mathhack`` in the include directive and it will be -replaced with ``.imgmathhack`` when preprocessed by this script (of course, -you should create both preprocessed versions of the file). - -.. note:: - This runs external commands and leaves files after itself! To reduce - running time when images are not changed and to reuse images for equal - fomulas, image names are md5 of the formula (hoping that no collisions - will happen) and images that already exist are not rebuilt. You should - purge the ``imgmath`` subdirectory manually to get rid of unused formulas. - - You'll need: - - - ``tex_to_images``, last version seems to live at the `speech_tools - CVS`__. - - __ http://cvs.sourceforge.net/viewcvs.py/*checkout*/ - emu/speech_tools/scripts/tex_to_images.prl?rev=HEAD - - It, in turn, relies upon: - - - LaTeX - - ``dviselect`` (part of ``dviutils``) - - ``dvips`` - - Ghoscript - - netpbm tools -""" - -import os, os.path, md5 - -from rolehack import * - -class Tex_to_images(object): - """Feeds math to ``tex_to_images``. Always goes through ppm.""" - def __init__(self, dir='./imgmath', options='-s 1.5', - converter='pnmtopng', extension='.png'): - try: - os.mkdir(dir) - except OSError: - pass - self.options = options - self.dir = dir - self.converter = converter - self.extension = extension - def process(self, text): - """Returns output filename.""" - dir = self.dir - extension = self.extension - options = self.options - converter = self.converter - fname = md5.new(text).hexdigest() - fpath = os.path.join(dir, fname) - if not os.path.exists(fpath + extension): - f = file(fpath, 'w') - f.write('@Start\n%s\n@End\n' % (text,)) - f.close() - os.system(('tex_to_images -f ppm -d %(dir)s -o %(fname)s.tmp ' - '%(options)s < %(fpath)s >& /dev/null' % vars())) - if self.converter: - os.system('%s < %s.tmp > %s%s' % - (self.converter, fpath, fpath, extension)) - else: - os.rename(fpath + '.tmp', fpath + '.ppm') - os.remove(fpath + '.tmp') - return fpath + extension - def texmath(self, text): - text = ' '.join(text.split()) - src = self.process(text) - return '''\ -image:: %(src)s - :align: middle - :class: texmath - :alt: %(text)s -''' % locals() - def texdisplay(self, text): - src = self.process(text) - return '''\ -image:: %(src)s - :align: center - :class: texdisplay - :alt: %(text)s -''' % locals() - -child = Tex_to_images() -texmath = child.texmath -texdisplay = child.texdisplay - -def mangle_include(text): - return 'include:: ' + text.replace('.mathhack', '.imgmathhack') - -main({'texmath': texmath}, texmath, - {'texmath': texdisplay, 'include': mangle_include}) diff --git a/sandbox/cben/rolehack/mathhack.py b/sandbox/cben/rolehack/mathhack.py deleted file mode 100755 index 0a02f231c..000000000 --- a/sandbox/cben/rolehack/mathhack.py +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env python -""" -.. epigraph:: - - Using ``raw`` is almost always evidence of a hack in progress. It's not a - clean solution. - - -- David Goodger. - -Convert the default and ``texmath`` role to raw latex inline math and the -``texmath`` directive to display math. -""" - -from rolehack import * - -texmath = template('''\ -raw:: latex - - $''', '$\n') - -texdisplay = template('''\ -raw:: latex - - \[ ''', ' \]\n') - -main({'texmath': texmath}, texmath, - {'texmath': texdisplay}) diff --git a/sandbox/cben/rolehack/rolehack.py b/sandbox/cben/rolehack/rolehack.py deleted file mode 100644 index 13895caa5..000000000 --- a/sandbox/cben/rolehack/rolehack.py +++ /dev/null @@ -1,192 +0,0 @@ -"""Preprocess reStructuredText roles to directives. - -This is a stop-gap hack for prototyping new syntaxes for reST, mainly useful -when you find yourself using directives every 3 lines. In such cases an -extension to docutils allowing some inline syntax is desired thing and such -extensions most probably will take the form of new interpretted text roles. - -This module allows to easily prototype them by converting given interpretted -text roles to directives. To make them inline, the uses of the roles are -replaced with substitutions and all substitution definitions are appeneded at -the end of the document (hint: use ``replace::`` if you don't want a -directive). - -Since what's useful for inline syntaxes might also be useful outside of -paragraphs, preprocessing simple directives (only an argument, no options or -content) into other directives is also supported. - -I was too lazy to implement an elaborate command-line interface, so this is -only a module. You should import it from a python script and call this module -with specific role->template mappings to do the work. - -BUGS -==== - -There are too many. Most can't be fixed here, the right thing is to extend -the docutils parser... - -- Backslashes are not interpretted in any way (except that backticks preceded - by backslashes are won't be treated as start/end of interpretted text). - This means backslashes are passed to the directive which probably won't stay - this way if the role is accepted into docutils (only the double-backtick - literal text syntax behaves this way). - - This bug is semi-intentional because it makes LaTeX generation easier... - -- Any number of lines is consumed in search for the closing backtick, - disregarding indentation. The content is pasted into the directive as one - line with normalized whitespace. - -- The width of the substitution references is not equal to the original, so - you can't use it in tables. - -- Long parts of the document without empty lines might cause ``recursion limit - exceeded`` errors. - -- Directives not recognized if preceded by non-whitespace (e.g. in a table). - -""" - -import re - -# Named groups are used to allow simultaneous replacement of all roles. - -_re_options = re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE - -def _role_re(group_name): - return r''' - # Start-string: - (?:^|(?<=\s|[\'"([{<\-/:])) - ` - (?=\S) - # Content: - (?P<%(group_name)s> - (?:[^`]|\\.)+ # skip escaped chars - ) - # End-string: - (?<=\S) - ` - (?=$|\s|[#\'")\]}>\-/:.,;!?\\]) - ''' % locals() - -_default_re = _role_re('_DEFAULT') - -def _role2regexp(role): - """Return regexp for approximate recognition of `role`.""" - prefix_re = _role_re('prefix_' + role) - postfix_re = _role_re('postfix_' + role) - return r''' - :%(role)s: - %(prefix_re)s - | - %(postfix_re)s - :%(role)s: - ''' % locals() - -def _dir2regexp(dir): - """Return regexp for approximate recognition of directive `dir`.""" - return r''' - ^(?P<indent_%(dir)s> [ \t]* ) # record indentation - \.\. \s+ - (?P<subst_%(dir)s> - ## (?:|[^|]*|)? # optional substitution - ) - \s* - %(dir)s \s* :: - (?P<argument_%(dir)s> - [^\n]* - (?: - \n - (?P=indent_%(dir)s) [ \t] # bigger indentation - [^\n]+ - )* - ) - ''' % locals() - -def process(doc, roles={}, default_role=None, directives={}): - """Process `doc` replacing given `roles`. - - `doc` should be a single string containing the whole document. The - `roles` dictionary maps from role names to replacement functions that - should accept the role content and return the directive text, starting - from the directive name, e.g.:: - - def repl(text): - return 'raw:: latex\n\n %s\n' % (text,) - - See `template()` for an easy way to create such trivial functions. The - optional `default_role` argument specifies a replacement for the default - role. - - The `directives` dictionary like `roles` but specifies directive names to - handle. The directive can have only an argument; substitution definitions - with these directives are also recognized. Indentation is adjusted - properly for directives. - - """ - re_parts = [] - repls = {} - if default_role: - re_parts.append(_default_re) - repls['_DEFAULT'] = default_role - for role, repl in roles.items(): - re_parts.append(_role2regexp(role)) - repls['prefix_' + role] = repls['postfix_' + role] = repl - for dir, repl in directives.items(): - re_parts.append(_dir2regexp(dir)) - repls['argument_' + dir] = repl - full_re = '\n|'.join(re_parts) - full_re = re.compile(full_re, _re_options) - - after_output = [] - def count(n=0): - while True: - yield n - n += 1 - ids = count() - def dispatch(match): - groupname = match.lastgroup - content = match.group(groupname) - kind, name = groupname.split('_', 1) - if kind == 'argument': # substitution - indent = match.group('indent_' + name) - subst = match.group('subst_' + name) - repl = '\n.. %s %s' % (subst, repls[groupname](content)) - return indent + repl.replace('\n', '\n' + indent) - else: # role - id = ids.next() - subst = '|rolehack_%d|' % (id,) - repl = '.. %s %s' % (subst, repls[groupname](content)) - after_output.append(repl) - return subst - - # Hack: process by chunks separated by blank lines, trying to avoid - # "recursion limit exceeded" errors. - empty_line_re = re.compile(r'\n[ \t]*\n') - output = [full_re.sub(dispatch, chunk) - for chunk in empty_line_re.split(doc)] - return '\n\n'.join(output + after_output) - -def template(pre, post): - """Make replacement function for wrapping content with two strings.""" - def repl(text): - return ''.join((pre, text, post)) - return repl - -def main(*args, **kw_args): - """Simple command-line interface.""" - import sys - def parse_args(input='-', output='-'): - if input == '-': - input = sys.stdin - else: - input = file(input) - if output == '-': - output = sys.stdout - else: - output = file(output, 'w') - output.write(process(input.read(), *args, **kw_args)) - parse_args(*sys.argv[1:]) - -##main({'foo': template('foo::\n\n ', '\n')}, -## template('default::\n\n ', '\n')) |