Commits

Akihiro Uchida committed 75bd10d

extend standalone leader for dollar math expression

Comments (0)

Files changed (2)

+"""
+replace dollar math expression to math role
+"""
+from docutils.readers import standalone
+from docutils.frontend import validate_boolean, filter_settings_spec
+
+class Reader(standalone.Reader):
+    title, desc, opts = filter_settings_spec(standalone.Reader.settings_spec)
+    title += ' with dollar math extension'
+    opts += (('Use dollar math expression instead of math role',
+              ['--use-dollar-math'],
+              {'dest': 'use_dollar_math', 'action': 'store_true',
+               'default': 0, 'validator': validate_boolean}),)
+    settings_spec = (title, desc, opts)
+
+    config_section = 'standalone reader with dollarmath'
+    config_section_dependencies = ('readers', 'standalone reader')
+
+    def read(self, source, parser, settings):
+        self.source = source
+        if not self.parser:
+            self.parser = parser
+        self.settings = settings
+        if settings.use_dollar_math:
+            self.input = replace_dollar(self.source.read())
+        else:
+            self.input = self.source.read()
+        self.parse()
+        return self.document
+
+import re
+
+dollar_pat = r"(?:^|(?<=\s))[$]([^\n]*?)(?<![\\])[$](?:$|(?=\s|[.,;\\]))"
+_dollar = re.compile(dollar_pat)
+_notdollar = re.compile(r"\\[$]")
+
+def replace_dollar(content):
+    content = _dollar.sub(r":math:`\1`", content)
+    content = _notdollar.sub("$", content)
+    return content
+
+def test_expr(expr, expect):
+    result = replace_dollar(expr)
+    print 'A math expression: %s' % expr
+    print 'A expected output: %s' % expect
+    if result == expect:
+        print 'OK: A result match expected one'
+    else:
+        print 'NG: A result %s does not match expected one!' % result
+
+def test_dollar():
+    samples = {
+        u"no dollar": u"no dollar",
+        u"$only$": u":math:`only`",
+        u"$first$ is good": u":math:`first` is good",
+        u"so is $last$": u"so is :math:`last`",
+        u"and $mid$ too": u"and :math:`mid` too",
+        u"$first$, $mid$, $last$": u":math:`first`, :math:`mid`, :math:`last`",
+        u"dollar\$ escape": u"dollar$ escape",
+        u"dollar \$escape\$ too": u"dollar $escape$ too",
+        u"emb\ $ed$\ ed": u"emb\ :math:`ed`\ ed",
+        u"$first$a": u"$first$a",
+        u"a$last$": u"a$last$",
+        u"a $mid$dle a": u"a $mid$dle a",
+    }
+    for expr, expect in samples.items():
+        test_expr(expr, expect)
+
+if __name__ == "__main__":
+    import sys, locale, codecs
+    encoding = locale.getpreferredencoding()
+    sys.stdout = codecs.getwriter(encoding)(sys.stdout)
+    sys.stdin = codecs.getreader(encoding)(sys.stdin)
+
+    import optparse
+    parser = optparse.OptionParser(usage='usage: %prog [options]')
+    parser.add_option("-i", "--input", dest="expr", type="string",
+                      help="input $math$ expression to test")
+    parser.add_option("-o", "--output", dest="expect", type="string",
+                      help="output result you expect")
+
+    opts, args = parser.parse_args()
+    if opts.expr:
+        expression = unicode(opts.expr, encoding)
+        if opts.expect:
+            expected = unicode(opts.expect, encoding)
+            test_expr(expression, expected)
+        else:
+            print replace_dollar(expression)
+    else:
+        if opts.expect:
+            parser.print_help()
+            parser.error("output option requires input expression")
+        else:
+            test_dollar()
+
 """
 A minimal front end to the Docutils Publisher, producing HTML.
 
-Extended to add support for a latex directive.
+Extended to add support for a latex directive and dollar math extension.
 
 Latex code is processed by latex and turned into a png.
 """
     pass
 
 from docutils.core import publish_cmdline, Publisher, default_description
+from docutils import Component
 
 import latex_directive
 latex_directive.register()
 
 description = ('Generates (X)HTML documents from standalone reStructuredText '
-               'sources.  ' + default_description)
-
-publish_cmdline(writer_name='html', description=description)
+               'with dollar math extension sources.  ' + default_description)
+settings_spec = Component()
+publish_cmdline(reader_name='dollarmath', writer_name='html',
+                description=description)