diff options
| author | dkuhlman <dkuhlman@929543f6-e4f2-0310-98a6-ba3bd3dd1d04> | 2009-01-07 19:09:28 +0000 |
|---|---|---|
| committer | dkuhlman <dkuhlman@929543f6-e4f2-0310-98a6-ba3bd3dd1d04> | 2009-01-07 19:09:28 +0000 |
| commit | abbb642285c586333f2679b2d960f73d663bbd9f (patch) | |
| tree | 838986aeb639b567e7a55dafc81c5cdf3270a2c3 /docutils | |
| parent | c5429fabba4546cc39af7c8b9194d27fc2aa68cc (diff) | |
| download | docutils-abbb642285c586333f2679b2d960f73d663bbd9f.tar.gz | |
Misc updates after initial checkin
git-svn-id: http://svn.code.sf.net/p/docutils/code/trunk@5839 929543f6-e4f2-0310-98a6-ba3bd3dd1d04
Diffstat (limited to 'docutils')
| -rw-r--r-- | docutils/docs/user/odt.txt | 230 | ||||
| -rw-r--r-- | docutils/docutils/core.py | 33 | ||||
| -rw-r--r-- | docutils/docutils/io.py | 18 | ||||
| -rw-r--r-- | docutils/docutils/writers/odf_odt/__init__.py | 328 | ||||
| -rw-r--r-- | docutils/docutils/writers/odf_odt/pygmentsformatter.py | 121 | ||||
| -rwxr-xr-x | docutils/setup.py | 1 | ||||
| -rwxr-xr-x | docutils/tools/rst2odt.py | 61 | ||||
| -rwxr-xr-x | docutils/tools/rst2odt_prepstyles.py | 5 |
8 files changed, 356 insertions, 441 deletions
diff --git a/docutils/docs/user/odt.txt b/docutils/docs/user/odt.txt index 1841fa40e..c458697cd 100644 --- a/docutils/docs/user/odt.txt +++ b/docutils/docs/user/odt.txt @@ -34,54 +34,18 @@ You should be able to open documents (.odt files) generated with You can learn more about Docutils and reST here: `Docutils`_ -How to Install It -================= - -Where to get it ---------------- - -``odtwriter`` is included in the standard Docutils distribution. - -You can find the last independent source distribution of -ODF/ODT writer for Docutils here: -`http://www.rexx.com/~dkuhlman/odtwriter-1.3d.tar.gz -<http://www.rexx.com/~dkuhlman/odtwriter-1.3d.tar.gz>`_. - -``odtwriter`` is also available via Subversion from -the Docutils repository under -``docutils/sandbox/OpenDocument/``. The following will -download Docutils including ``odtwriter`` and associated files into -your current directory:: - - $ svn checkout svn://svn.berlios.de/docutils/trunk docutils - -For more information about access to the Docutils Subversion -repository, see: -http://docutils.sourceforge.net/docs/dev/repository.html. - - Requirements ------------- - -``odtwriter`` requires: - -- Python - -- A sufficiently recent version of `Docutils`_. - -- One of the following: - - - Lxml -- See: http://codespeak.net/lxml/. - - - ElementTree -- See: http://effbot.org/zone/element-index.htm. +============ - - ElementTree from that Python standard library -- Python 2.5 and - later comes with ElementTree included. +In addition to the Docutils standard requirements, ``odtwriter`` +requires: - ``odtwriter`` will try first to use Lxml; if that fails, it will - try to use a separately installed version of ElementTree; and if - that fails, it will try to use ElementTree from the standard - library. +- ElementTree or Lxml (http://codespeak.net/lxml/). Python (version 2.5 or later) now includes + ElementTree (``xml.etree.ElementTree``). However, ``odtwriter`` + will use Lxml if it is installed. ``odtwriter`` tries to import + (1) Lxml, and if that fails, (2) a separately installed + ElementTree, and if that fails, (3) ElementTree from the Python + standard library. - Optional -- `Pygments`_ is required if you want syntax highlighting of code in literal blocks. See section `Syntax @@ -92,19 +56,6 @@ Requirements and ``height``. See section `Images and figures`_. -Installation ------------- - -Install ``odtwriter`` with the standard Python installation -commands:: - - $ python setup.py build - $ python setup.py install # possibly as root - -This will install ``rst2odt.py`` in your ``bin`` directory and the -odtwriter and the styles file under ``docutils/writers/odtwriter`` -within your Docutils installation. - How to Use It ============= @@ -122,22 +73,17 @@ Examples:: $ rst2odt.py -s -g python_comments.txt python_comments.odt - $ rst2odt.py --source-url=odtwriter.txt --generator --stylesheet-path=/myconfigs/styles.odt odtwriter.txt odtwriter.odt + $ rst2odt.py --source-url=odtwriter.txt --generator --stylesheet=/myconfigs/styles.odt odtwriter.txt odtwriter.odt -Command line flags ------------------- +Command line options +-------------------- The following command line flags are specific to ``odtwriter``: ---stylesheet=<URL> Specify a stylesheet URL, used verbatim. Overrides - --stylesheet-path. ---stylesheet-path=<file> - Specify a stylesheet file, relative to the current - working directory. The path is adjusted relative to - the output ODF file. Overrides --stylesheet. - Default: "/usr/local/lib/python2.6/site- - packages/docutils/writers/odtwriter/styles.odt" +--stylesheet=<URL> Specify a stylesheet URL, used verbatim. + Default: writers/odf_odt/styles.odt in the + installation directory. --odf-config-file=<file> Specify a configuration/mapping file relative to the current working directory for additional ODF options. @@ -158,13 +104,13 @@ The following command line flags are specific to ``odtwriter``: a cm. Default is 35. --add-syntax-highlighting Add syntax highlighting in literal code blocks. ---no-add-syntax-highlighting +--no-syntax-highlighting Do not add syntax highlighting in literal code blocks. (default) --create-sections Create sections for headers. (default) ---no-create-sections Do not create sections for headers. +--no-sections Do not create sections for headers. --create-links Create links. ---no-create-links Do not create links. (default) +--no-links Do not create links. (default) --endnotes-end-doc Generate endnotes at end of document, not footnotes at bottom of page. --no-endnotes-end-doc Generate footnotes at bottom of page, not endnotes at @@ -174,8 +120,13 @@ The following command line flags are specific to ``odtwriter``: Styles ====== -``odtwriter`` uses a number of styles that are defined in the -default ``styles.xml``. This section describes those styles. +``odtwriter`` uses a number of styles that are defined in +``styles.xml`` in the default ``styles.odt``. This section +describes those styles. + +Note that with the ``--stylesheet`` command line option, you can +use either ``styles.odt`` or ``styles.xml``, as described below. +Use of ``styles.odt`` is recommended over ``styles.xml``. You can modify the look of documents generated by ``odtwriter`` in several ways: @@ -199,15 +150,15 @@ several ways: - Extract ``styles.xml`` from ``styles.odt`` using your favorite ``zip/unzip`` tool. Then modify ``styles.xml`` with a text editor. Now re-zip it back into your own ``styles.odt``, or use - it directly by specifying it with a command line flag. - **Hint:** If you intend to extract ``styles.xml`` from an - ``.odt`` file (and then "re-zip" it), you should turn off XML - optimization/compression in ``oowriter``. In order to this in - ``oowriter``, use Tools --> Options... --> Load-Save --> General - and turn off "Size optimization for XML format". - -- Open an empty (or new) document in ``oowriter``. Define the - styles described in this section. Then, use that document (a + it directly by specifying it with the ``--stylesheet`` command + line option. **Hint:** If you intend to extract ``styles.xml`` + from an ``.odt`` file (and then "re-zip" it), you should turn off + XML optimization/compression in ``oowriter``. In order to this + in ``oowriter``, use Tools --> Options... --> Load-Save --> + General and turn off "Size optimization for XML format". + +- Open an empty (or new) document in ``oowriter``. Define all of + the styles described in this section. Then, use that document (a .odt file) as your stylesheet. ``odtwriter`` will extract the ``styles.xml`` file from that document and insert it into the output document. @@ -239,9 +190,9 @@ the styles used by ``odtwriter``. Notice that you can make a copy of file ``styles.odt``, modify it using ``oowriter``, and then use your copy with the -``--stylesheet-path=<file>`` command line option. Example:: +``--stylesheet=<file>`` command line option. Example:: - $ rst2odt.py --stylesheet-path=mystyles.odt test2.txt test2.odt + $ rst2odt.py --stylesheet=mystyles.odt test2.txt test2.odt Paragraph styles @@ -581,14 +532,14 @@ Defining and using a custom stylesheet You can create your own custom stylesheet. Here is how: -1. Make a copy of ``styles.xml``, which is in the distribution. +1. Make a copy of ``styles.odt``, which is in the distribution. -2. Open your copy of ``styles.xml`` in ``oowriter``. Modify styles +2. Open your copy of ``styles.odt`` in ``oowriter``. Modify styles in that document. Then, save it. -3. When you run ``rst2odt.py``, use the ``--stylesheet=<URL>`` or - ``--stylesheet-path=<file>`` to use your custom stylesheet. Run - ``rst2odt.py --help`` to learn more about these options. +3. When you run ``rst2odt.py``, use the ``--stylesheet`` command + line option to use your custom stylesheet. Run ``rst2odt.py + --help`` to learn more about these options. Why custom stylesheets @@ -679,10 +630,10 @@ contain them, do the following: 4. When you run ``odtwriter``, specify the ``--odf-config-file`` option. You might also want to specify your styles document - using the ``--stylesheet-path`` option in order to include your + using the ``--stylesheet`` option in order to include your custom style definitions. For example:: - rst2odt.py --odf-config-file=mymappingfile.ini --stylesheet-path=mystyles.odt mydoc.txt mydoc.odt + rst2odt.py --odf-config-file=mymappingfile.ini --stylesheet=mystyles.odt mydoc.txt mydoc.odt @@ -705,38 +656,15 @@ table of contents. That feature is under menu item:: Syntax highlighting ------------------- -**Note:** Syntax highlighting uses the Docutils class -``docutils.parsers.rst.Directive``. Therefore, it requires a very -recent version of Docutils, specifically version 0.5 or later. - ``odtwriter`` can add syntax highlighting to code in code blocks. In order to activate this, do all of the following: -1. Install Pygments_ and ... +1. Install `Pygments`_ and ... 2. Use the command line flag ``--add-syntax-highlighting``. Example:: - $ rst2odt.py -g --add-syntax-highlight test.txt test.odt - - and ... - -3. In your reST (.txt) file, include code to which syntax - highlighting is to be applied inside a ``sourcecode`` directive, - for example: - - .. parsed-literal:: - - .. sourcecode:: *language* - - def test(): - print 'hi' - return 'something' - - where *language* is the programming language, for example - "python", "java", etc. See the - `Pygments documentation`_ for a list of - `languages supported by Pygments`_. + $ rst2odt.py --add-syntax-highlight test.txt test.odt The following styles are defined in styles.odt and are used for literal code blocks and syntax highlighting: @@ -777,64 +705,6 @@ also need to select "All Styles" from the drop-down selection list at the bottom of the Styles and Formatting window. -Controlling syntax highlighting within a document -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -By default, when you use the ``--add-syntax-highlighting`` command -line flag, syntax highlighting in literal blocks is on and the -Python lexer is used. You can change this within your reST document -with the following directive: - -.. parsed-literal:: - - .. sourcecode:: *newstate* - -or: - -.. parsed-literal:: - - .. sourcecode:: *language* - -where: - -- *newstate* is either "on" or "off", which makes highlighting - active or inactive. - -- *language* is the language in literal code blocks. It should be - one of the *"short names"* listed at Pygments' `Available - Lexers`_, for example "python", "pycon", "java", "cpp", "c", - "perl", "javascript", etc. - -Examples:: - - .. sourcecode:: on - .. sourcecode:: python - .. sourcecode:: off - .. sourcecode:: java - .. sourcecode:: on - -A few additional notes and hints: - -- The syntax highlighting state and language set by this - directive remain in effect until the next ``sourcecode`` directive - is encountered in the reST document. - -- In order to turn syntax highlighting on (or off) and set the - language, you will need to use this directive twice. - -- Special note to Pythonistas: there is a separate lexer for - examples of code from the Python interactive prompt and console - output or doctests. The alias for that lexer is "pycon". - -.. _`Pygments documentation`: - http://pygments.org/docs/ - -.. _`languages supported by Pygments`: - http://pygments.org/languages/ - -.. _`Available Lexers`: - http://pygments.org/docs/lexers/ - The container directive ----------------------- @@ -913,7 +783,7 @@ Endnotes -- There are command line flags that control whether ``odtwriter`` creates endnotes instead of footnotes. Endnotes appear at the end of the document instead of at the bottom of the page. See flags ``--endnotes-end-doc`` and -``--no-endnotes-end-doc`` in section `Command line flags`_. +``--no-endnotes-end-doc`` in section `Command line options`_. Images and figures @@ -1055,13 +925,5 @@ pick up the default paper size on platforms where the program http://www.pythonware.com/products/pil/ -.. Configuration for Emacs -.. - Local Variables: - mode: rst - indent-tabs-mode: nil - sentence-end-double-space: t - fill-column: 68 - End: diff --git a/docutils/docutils/core.py b/docutils/docutils/core.py index fb3a6001a..0f6e1aeaa 100644 --- a/docutils/docutils/core.py +++ b/docutils/docutils/core.py @@ -502,6 +502,39 @@ def publish_from_doctree(document, destination_path=None, pub.set_destination(None, destination_path) return pub.publish(enable_exit_status=enable_exit_status) +def publish_cmdline_to_binary(reader=None, reader_name='standalone', + parser=None, parser_name='restructuredtext', + writer=None, writer_name='pseudoxml', + settings=None, settings_spec=None, + settings_overrides=None, config_section=None, + enable_exit_status=1, argv=None, + usage=default_usage, description=default_description, + destination=None, destination_class=io.BinaryFileOutput + ): + """ + Set up & run a `Publisher` for command-line-based file I/O (input and + output file paths taken automatically from the command line). Return the + encoded string output also. + + This is just like publish_cmdline, except that it uses + io.BinaryFileOutput instead of io.FileOutput. + + Parameters: see `publish_programmatically` for the remainder. + + - `argv`: Command-line argument list to use instead of ``sys.argv[1:]``. + - `usage`: Usage string, output if there's a problem parsing the command + line. + - `description`: Program description, output for the "--help" option + (along with command-line option descriptions). + """ + pub = Publisher(reader, parser, writer, settings=settings, + destination_class=destination_class) + pub.set_components(reader_name, parser_name, writer_name) + output = pub.publish( + argv, usage, description, settings_spec, settings_overrides, + config_section=config_section, enable_exit_status=enable_exit_status) + return output + def publish_programmatically(source_class, source, source_path, destination_class, destination, destination_path, reader, reader_name, diff --git a/docutils/docutils/io.py b/docutils/docutils/io.py index ec481fb45..3d1ccf663 100644 --- a/docutils/docutils/io.py +++ b/docutils/docutils/io.py @@ -343,6 +343,24 @@ class FileOutput(Output): self.opened = None +class BinaryFileOutput(FileOutput): + """ + A version of docutils.io.FileOutput which writes to a binary file. + """ + def open(self): + try: + self.destination = open(self.destination_path, 'wb') + except IOError, error: + if not self.handle_io_errors: + raise + print >>sys.stderr, '%s: %s' % (error.__class__.__name__, + error) + print >>sys.stderr, ('Unable to open destination file for writing ' + '(%r). Exiting.' % self.destination_path) + sys.exit(1) + self.opened = 1 + + class StringInput(Input): """ diff --git a/docutils/docutils/writers/odf_odt/__init__.py b/docutils/docutils/writers/odf_odt/__init__.py index 31b36e815..70e34f6e3 100644 --- a/docutils/docutils/writers/odf_odt/__init__.py +++ b/docutils/docutils/writers/odf_odt/__init__.py @@ -1,3 +1,6 @@ +# $Id$ +# Author: Dave Kuhlman <dkuhlman@rexx.com> +# Copyright: This module has been placed in the public domain. """ Open Document Format (ODF) Writer. @@ -51,102 +54,14 @@ except ImportError, e: print '***' raise +# +# Import pygments and odtwriter pygments formatters if possible. try: import pygments - import pygments.formatter import pygments.lexers - class OdtPygmentsFormatter(pygments.formatter.Formatter): - def __init__(self, rststyle_function): - pygments.formatter.Formatter.__init__(self) - self.rststyle_function = rststyle_function - - def rststyle(self, name, parameters=( )): - return self.rststyle_function(name, parameters) - - class OdtPygmentsProgFormatter(OdtPygmentsFormatter): - def format(self, tokensource, outfile): - tokenclass = pygments.token.Token - for ttype, value in tokensource: - value = escape_cdata(value) - if ttype == tokenclass.Keyword: - s2 = self.rststyle('codeblock-keyword') - s1 = '<text:span text:style-name="%s">%s</text:span>' % \ - (s2, value, ) - elif ttype == tokenclass.Literal.String: - s2 = self.rststyle('codeblock-string') - s1 = '<text:span text:style-name="%s">%s</text:span>' % \ - (s2, value, ) - elif ttype in ( - tokenclass.Literal.Number.Integer, - tokenclass.Literal.Number.Integer.Long, - tokenclass.Literal.Number.Float, - tokenclass.Literal.Number.Hex, - tokenclass.Literal.Number.Oct, - tokenclass.Literal.Number, - ): - s2 = self.rststyle('codeblock-number') - s1 = '<text:span text:style-name="%s">%s</text:span>' % \ - (s2, value, ) - elif ttype == tokenclass.Operator: - s2 = self.rststyle('codeblock-operator') - s1 = '<text:span text:style-name="%s">%s</text:span>' % \ - (s2, value, ) - elif ttype == tokenclass.Comment: - s2 = self.rststyle('codeblock-comment') - s1 = '<text:span text:style-name="%s">%s</text:span>' % \ - (s2, value, ) - elif ttype == tokenclass.Name.Class: - s2 = self.rststyle('codeblock-classname') - s1 = '<text:span text:style-name="%s">%s</text:span>' % \ - (s2, value, ) - elif ttype == tokenclass.Name.Function: - s2 = self.rststyle('codeblock-functionname') - s1 = '<text:span text:style-name="%s">%s</text:span>' % \ - (s2, value, ) - elif ttype == tokenclass.Name: - s2 = self.rststyle('codeblock-name') - s1 = '<text:span text:style-name="%s">%s</text:span>' % \ - (s2, value, ) - else: - s1 = value - outfile.write(s1) - class OdtPygmentsLaTeXFormatter(OdtPygmentsFormatter): - def format(self, tokensource, outfile): - tokenclass = pygments.token.Token - for ttype, value in tokensource: - value = escape_cdata(value) - if ttype == tokenclass.Keyword: - s2 = self.rststyle('codeblock-keyword') - s1 = '<text:span text:style-name="%s">%s</text:span>' % \ - (s2, value, ) - elif ttype in (tokenclass.Literal.String, - tokenclass.Literal.String.Backtick, - ): - s2 = self.rststyle('codeblock-string') - s1 = '<text:span text:style-name="%s">%s</text:span>' % \ - (s2, value, ) - elif ttype == tokenclass.Name.Attribute: - s2 = self.rststyle('codeblock-operator') - s1 = '<text:span text:style-name="%s">%s</text:span>' % \ - (s2, value, ) - elif ttype == tokenclass.Comment: - if value[-1] == '\n': - s2 = self.rststyle('codeblock-comment') - s1 = '<text:span text:style-name="%s">%s</text:span>\n' % \ - (s2, value[:-1], ) - else: - s2 = self.rststyle('codeblock-comment') - s1 = '<text:span text:style-name="%s">%s</text:span>' % \ - (s2, value, ) - elif ttype == tokenclass.Name.Builtin: - s2 = self.rststyle('codeblock-name') - s1 = '<text:span text:style-name="%s">%s</text:span>' % \ - (s2, value, ) - else: - s1 = value - outfile.write(s1) - -except ImportError, e: + from pygmentsformatter import escape_cdata, OdtPygmentsProgFormatter, \ + OdtPygmentsLaTeXFormatter +except ImportError, exp: pygments = None # @@ -393,82 +308,70 @@ def ToString(et): outstream.close() return s1 -def escape_cdata(text): - text = text.replace("&", "&") - text = text.replace("<", "<") - text = text.replace(">", ">") - ascii = '' - for char in text: - if ord(char) >= ord("\x7f"): - ascii += "&#x%X;" % ( ord(char), ) - else: - ascii += char - return ascii - # # Classes # -# Does this version of Docutils has Directive support? -if hasattr(rst, 'Directive'): - # - # Class to control syntax highlighting. - class SyntaxHighlightCodeBlock(rst.Directive): - required_arguments = 1 - optional_arguments = 0 - has_content = True - # - # See visit_literal_block for code that processes the node - # created here. - def run(self): - language = self.arguments[0] - code_block = nodes.literal_block(classes=["code-block", language], - language=language) - lines = self.content - content = '\n'.join(lines) - text_node = nodes.Text(content) - code_block.append(text_node) - # Mark this node for high-lighting so that visit_literal_block - # will be able to hight-light those produced here and - # *not* high-light regular literal blocks (:: in reST). - code_block['hilight'] = True - #import pdb; pdb.set_trace() - return [code_block] - - rst.directives.register_directive('sourcecode', SyntaxHighlightCodeBlock) - rst.directives.register_directive('code', SyntaxHighlightCodeBlock) - - rst.directives.register_directive('code-block', SyntaxHighlightCodeBlock) - -# -# Register directives defined in a module named "odtwriter_plugins". -# -def load_plugins(): - plugin_mod = None - count = 0 - try: - name = 'odtwriter_plugins' - fp, pathname, description = imp.find_module(name) - plugin_mod = imp.load_module(name, fp, pathname, description) - #import odtwriter_plugins - #plugin_mod = odtwriter_plugins - except ImportError, e: - pass - if plugin_mod is None: - return count - klasses = inspect.getmembers(plugin_mod, inspect.isclass) - for klass in klasses: - if register_plugin(*klass): - count += 1 - return count - -def register_plugin(name, klass): - plugin_name = getattr(klass, 'plugin_name', None) - if plugin_name is not None: - rst.directives.register_directive(plugin_name, klass) - -load_plugins() +## # Does this version of Docutils has Directive support? +## if hasattr(rst, 'Directive'): +## # +## # Class to control syntax highlighting. +## class SyntaxHighlightCodeBlock(rst.Directive): +## required_arguments = 1 +## optional_arguments = 0 +## has_content = True +## # +## # See visit_literal_block for code that processes the node +## # created here. +## def run(self): +## language = self.arguments[0] +## code_block = nodes.literal_block(classes=["code-block", language], +## language=language) +## lines = self.content +## content = '\n'.join(lines) +## text_node = nodes.Text(content) +## code_block.append(text_node) +## # Mark this node for high-lighting so that visit_literal_block +## # will be able to hight-light those produced here and +## # *not* high-light regular literal blocks (:: in reST). +## code_block['hilight'] = True +## #import pdb; pdb.set_trace() +## return [code_block] +## +## rst.directives.register_directive('sourcecode', SyntaxHighlightCodeBlock) +## rst.directives.register_directive('code', SyntaxHighlightCodeBlock) +## +## rst.directives.register_directive('code-block', SyntaxHighlightCodeBlock) + +## # +## # Register directives defined in a module named "odtwriter_plugins". +## # +## def load_plugins(): +## plugin_mod = None +## count = 0 +## try: +## name = 'odtwriter_plugins' +## fp, pathname, description = imp.find_module(name) +## plugin_mod = imp.load_module(name, fp, pathname, description) +## #import odtwriter_plugins +## #plugin_mod = odtwriter_plugins +## except ImportError, e: +## pass +## if plugin_mod is None: +## return count +## klasses = inspect.getmembers(plugin_mod, inspect.isclass) +## for klass in klasses: +## if register_plugin(*klass): +## count += 1 +## return count +## +## def register_plugin(name, klass): +## plugin_name = getattr(klass, 'plugin_name', None) +## if plugin_name is not None: +## rst.directives.register_directive(plugin_name, klass) +## +## load_plugins() WORD_SPLIT_PAT1 = re.compile(r'\b(\w*)\b\W*') @@ -527,17 +430,13 @@ class Writer(writers.Writer): 'ODF-Specific Options', None, ( - ('Specify a stylesheet URL, used verbatim. Overrides ' - '--stylesheet-path.', + ('Specify a stylesheet. ' + 'Default: "%s"' % default_stylesheet_path, ['--stylesheet'], - {'metavar': '<URL>', 'overrides': 'stylesheet_path'}), - ('Specify a stylesheet file, relative to the current working ' - 'directory. The path is adjusted relative to the output ODF ' - 'file. Overrides --stylesheet. Default: "%s"' - % default_stylesheet_path, - ['--stylesheet-path'], - {'metavar': '<file>', 'overrides': 'stylesheet', - 'default': default_stylesheet_path}), + { + 'default': default_stylesheet_path, + 'dest': 'stylesheet' + }), ('Specify a configuration/mapping file relative to the ' 'current working ' 'directory for additional ODF options. ' @@ -574,7 +473,7 @@ class Writer(writers.Writer): 'dest': 'add_syntax_highlighting', 'validator': frontend.validate_boolean}), ('Do not add syntax highlighting in literal code blocks. (default)', - ['--no-add-syntax-highlighting'], + ['--no-syntax-highlighting'], {'default': False, 'action': 'store_false', 'dest': 'add_syntax_highlighting', @@ -586,7 +485,7 @@ class Writer(writers.Writer): 'dest': 'create_sections', 'validator': frontend.validate_boolean}), ('Do not create sections for headers.', - ['--no-create-sections'], + ['--no-sections'], {'default': True, 'action': 'store_false', 'dest': 'create_sections', @@ -598,7 +497,7 @@ class Writer(writers.Writer): 'dest': 'create_links', 'validator': frontend.validate_boolean}), ('Do not create links. (default)', - ['--no-create-links'], + ['--no-links'], {'default': False, 'action': 'store_false', 'dest': 'create_links', @@ -617,7 +516,15 @@ class Writer(writers.Writer): 'action': 'store_false', 'dest': 'endnotes_end_doc', 'validator': frontend.validate_boolean}), - )) + ('Generate an oowriter table of contents, not ' + 'a list (default).', + ['--generate-oowriter-toc'], + {'default': False, + 'action': 'store_true', + 'dest': 'generate_oowriter_toc', + 'validator': frontend.validate_boolean}), + ) + ) settings_defaults = { 'output_encoding_error_handler': 'xmlcharrefreplace', @@ -695,8 +602,7 @@ class Writer(writers.Writer): """ modeled after get_stylesheet """ - stylespath = utils.get_stylesheet_reference(self.settings, - os.path.join(os.getcwd(), 'dummy')) + stylespath = self.settings.stylesheet zfile = zipfile.ZipFile(stylespath, 'r') s1 = zfile.read('settings.xml') zfile.close() @@ -706,8 +612,7 @@ class Writer(writers.Writer): """Retrieve the stylesheet from either a .xml file or from a .odt (zip) file. Return the content as a string. """ - stylespath = utils.get_stylesheet_reference(self.settings, - os.path.join(os.getcwd(), 'dummy')) + stylespath = self.settings.stylesheet ext = os.path.splitext(stylespath)[1] if ext == '.xml': stylesfile = open(stylespath, 'r') @@ -1320,17 +1225,20 @@ class ODFTranslator(nodes.GenericNodeVisitor): def visit_bullet_list(self, node): #ipshell('At visit_bullet_list') if self.in_table_of_contents: - if node.has_key('classes') and \ - 'auto-toc' in node.attributes['classes']: - el = SubElement(self.current_element, 'text:list', attrib={ - 'text:style-name': self.rststyle('tocenumlist'), - }) - self.list_style_stack.append(self.rststyle('enumitem')) + if self.settings.generate_oowriter_toc: + pass else: - el = SubElement(self.current_element, 'text:list', attrib={ - 'text:style-name': self.rststyle('tocbulletlist'), - }) - self.list_style_stack.append(self.rststyle('bulletitem')) + if node.has_key('classes') and \ + 'auto-toc' in node.attributes['classes']: + el = SubElement(self.current_element, 'text:list', attrib={ + 'text:style-name': self.rststyle('tocenumlist'), + }) + self.list_style_stack.append(self.rststyle('enumitem')) + else: + el = SubElement(self.current_element, 'text:list', attrib={ + 'text:style-name': self.rststyle('tocbulletlist'), + }) + self.list_style_stack.append(self.rststyle('bulletitem')) else: if self.blockstyle == self.rststyle('blockquote'): el = SubElement(self.current_element, 'text:list', attrib={ @@ -2143,8 +2051,10 @@ class ODFTranslator(nodes.GenericNodeVisitor): self.rststyle('codeblock'), ) source = node.astext() if (pygments and - self.settings.add_syntax_highlighting and - node.get('hilight', False)): + self.settings.add_syntax_highlighting + #and + #node.get('hilight', False) + ): language = node.get('language', 'python') source = self._add_syntax_highlighting(source, language) else: @@ -2690,11 +2600,26 @@ class ODFTranslator(nodes.GenericNodeVisitor): #ipshell('At visit_topic') if 'classes' in node.attributes: if 'contents' in node.attributes['classes']: - el = self.append_p('horizontalline') - el = self.append_p('centeredtextbody') - el1 = SubElement(el, 'text:span', - attrib={'text:style-name': self.rststyle('strong')}) - el1.text = 'Contents' + if self.settings.generate_oowriter_toc: + el1 = self.append_child('text:table-of-content', attrib={ + 'text:name': 'Table of Contents1', + 'text:protected': 'true', + 'text:style-name': 'Sect1', + }) + el2 = SubElement(el1, 'text:table-of-content-source', attrib={ + 'text:outline-level': '10', + }) + el3 =SubElement(el2, 'text:index-title-template', attrib={ + 'text:style-name': 'Contents_20_Heading', + }) + el3.text = 'Table of Contents' + raise nodes.SkipChildren() + else: + el = self.append_p('horizontalline') + el = self.append_p('centeredtextbody') + el1 = SubElement(el, 'text:span', + attrib={'text:style-name': self.rststyle('strong')}) + el1.text = 'Contents' self.in_table_of_contents = True elif 'abstract' in node.attributes['classes']: el = self.append_p('horizontalline') @@ -2707,7 +2632,10 @@ class ODFTranslator(nodes.GenericNodeVisitor): #ipshell('At depart_topic') if 'classes' in node.attributes: if 'contents' in node.attributes['classes']: - el = self.append_p('horizontalline') + if self.settings.generate_oowriter_toc: + pass + else: + el = self.append_p('horizontalline') self.in_table_of_contents = False def visit_transition(self, node): diff --git a/docutils/docutils/writers/odf_odt/pygmentsformatter.py b/docutils/docutils/writers/odf_odt/pygmentsformatter.py new file mode 100644 index 000000000..677519e29 --- /dev/null +++ b/docutils/docutils/writers/odf_odt/pygmentsformatter.py @@ -0,0 +1,121 @@ +# $Id$ +# Author: Dave Kuhlman <dkuhlman@rexx.com> +# Copyright: This module has been placed in the public domain. + +""" + +Additional support for Pygments formatter. + +""" + + +import pygments +import pygments.formatter + + +def escape_cdata(text): + text = text.replace("&", "&") + text = text.replace("<", "<") + text = text.replace(">", ">") + ascii = '' + for char in text: + if ord(char) >= ord("\x7f"): + ascii += "&#x%X;" % ( ord(char), ) + else: + ascii += char + return ascii + + +class OdtPygmentsFormatter(pygments.formatter.Formatter): + def __init__(self, rststyle_function): + pygments.formatter.Formatter.__init__(self) + self.rststyle_function = rststyle_function + + def rststyle(self, name, parameters=( )): + return self.rststyle_function(name, parameters) + + +class OdtPygmentsProgFormatter(OdtPygmentsFormatter): + def format(self, tokensource, outfile): + tokenclass = pygments.token.Token + for ttype, value in tokensource: + value = escape_cdata(value) + if ttype == tokenclass.Keyword: + s2 = self.rststyle('codeblock-keyword') + s1 = '<text:span text:style-name="%s">%s</text:span>' % \ + (s2, value, ) + elif ttype == tokenclass.Literal.String: + s2 = self.rststyle('codeblock-string') + s1 = '<text:span text:style-name="%s">%s</text:span>' % \ + (s2, value, ) + elif ttype in ( + tokenclass.Literal.Number.Integer, + tokenclass.Literal.Number.Integer.Long, + tokenclass.Literal.Number.Float, + tokenclass.Literal.Number.Hex, + tokenclass.Literal.Number.Oct, + tokenclass.Literal.Number, + ): + s2 = self.rststyle('codeblock-number') + s1 = '<text:span text:style-name="%s">%s</text:span>' % \ + (s2, value, ) + elif ttype == tokenclass.Operator: + s2 = self.rststyle('codeblock-operator') + s1 = '<text:span text:style-name="%s">%s</text:span>' % \ + (s2, value, ) + elif ttype == tokenclass.Comment: + s2 = self.rststyle('codeblock-comment') + s1 = '<text:span text:style-name="%s">%s</text:span>' % \ + (s2, value, ) + elif ttype == tokenclass.Name.Class: + s2 = self.rststyle('codeblock-classname') + s1 = '<text:span text:style-name="%s">%s</text:span>' % \ + (s2, value, ) + elif ttype == tokenclass.Name.Function: + s2 = self.rststyle('codeblock-functionname') + s1 = '<text:span text:style-name="%s">%s</text:span>' % \ + (s2, value, ) + elif ttype == tokenclass.Name: + s2 = self.rststyle('codeblock-name') + s1 = '<text:span text:style-name="%s">%s</text:span>' % \ + (s2, value, ) + else: + s1 = value + outfile.write(s1) + + +class OdtPygmentsLaTeXFormatter(OdtPygmentsFormatter): + def format(self, tokensource, outfile): + tokenclass = pygments.token.Token + for ttype, value in tokensource: + value = escape_cdata(value) + if ttype == tokenclass.Keyword: + s2 = self.rststyle('codeblock-keyword') + s1 = '<text:span text:style-name="%s">%s</text:span>' % \ + (s2, value, ) + elif ttype in (tokenclass.Literal.String, + tokenclass.Literal.String.Backtick, + ): + s2 = self.rststyle('codeblock-string') + s1 = '<text:span text:style-name="%s">%s</text:span>' % \ + (s2, value, ) + elif ttype == tokenclass.Name.Attribute: + s2 = self.rststyle('codeblock-operator') + s1 = '<text:span text:style-name="%s">%s</text:span>' % \ + (s2, value, ) + elif ttype == tokenclass.Comment: + if value[-1] == '\n': + s2 = self.rststyle('codeblock-comment') + s1 = '<text:span text:style-name="%s">%s</text:span>\n' % \ + (s2, value[:-1], ) + else: + s2 = self.rststyle('codeblock-comment') + s1 = '<text:span text:style-name="%s">%s</text:span>' % \ + (s2, value, ) + elif ttype == tokenclass.Name.Builtin: + s2 = self.rststyle('codeblock-name') + s1 = '<text:span text:style-name="%s">%s</text:span>' % \ + (s2, value, ) + else: + s1 = value + outfile.write(s1) diff --git a/docutils/setup.py b/docutils/setup.py index 355062ed4..924d8b991 100755 --- a/docutils/setup.py +++ b/docutils/setup.py @@ -121,6 +121,7 @@ what-you-see-is-what-you-get plaintext markup syntax.""", # wrap at col 60 'tools/rst2pseudoxml.py', 'tools/rstpep2html.py', 'tools/rst2odt.py', + 'tools/rst2odt_prepstyles.py', ],} """Distutils setup parameters.""" diff --git a/docutils/tools/rst2odt.py b/docutils/tools/rst2odt.py index db21f9165..369fa386f 100755 --- a/docutils/tools/rst2odt.py +++ b/docutils/tools/rst2odt.py @@ -15,9 +15,7 @@ try: except: pass -from docutils.core import publish_cmdline, default_description, \ - Publisher, default_usage -from docutils import io +from docutils.core import publish_cmdline_to_binary, default_description from docutils.writers.odf_odt import Writer, Reader @@ -25,59 +23,8 @@ description = ('Generates OpenDocument/OpenOffice/ODF documents from ' 'standalone reStructuredText sources. ' + default_description) -class BinaryFileOutput(io.FileOutput): - """ - A version of docutils.io.FileOutput which writes to a binary file. - """ - def open(self): - try: - self.destination = open(self.destination_path, 'wb') - except IOError, error: - if not self.handle_io_errors: - raise - print >>sys.stderr, '%s: %s' % (error.__class__.__name__, - error) - print >>sys.stderr, ('Unable to open destination file for writing ' - '(%r). Exiting.' % self.destination_path) - sys.exit(1) - self.opened = 1 - - -def publish_cmdline_to_binary(reader=None, reader_name='standalone', - parser=None, parser_name='restructuredtext', - writer=None, writer_name='pseudoxml', - settings=None, settings_spec=None, - settings_overrides=None, config_section=None, - enable_exit_status=1, argv=None, - usage=default_usage, description=default_description, - destination=None, destination_class=BinaryFileOutput - ): - """ - Set up & run a `Publisher` for command-line-based file I/O (input and - output file paths taken automatically from the command line). Return the - encoded string output also. - - This is just like publish_cmdline, except that it uses - io.BinaryFileOutput instead of io.FileOutput. - - Parameters: see `publish_programmatically` for the remainder. - - - `argv`: Command-line argument list to use instead of ``sys.argv[1:]``. - - `usage`: Usage string, output if there's a problem parsing the command - line. - - `description`: Program description, output for the "--help" option - (along with command-line option descriptions). - """ - pub = Publisher(reader, parser, writer, settings=settings, - destination_class=destination_class) - pub.set_components(reader_name, parser_name, writer_name) - output = pub.publish( - argv, usage, description, settings_spec, settings_overrides, - config_section=config_section, enable_exit_status=enable_exit_status) - return output - - writer = Writer() reader = Reader() -output = publish_cmdline_to_binary(reader=reader, writer=writer, description=description) - +output = publish_cmdline_to_binary(reader=reader, writer=writer, + description=description) + diff --git a/docutils/tools/rst2odt_prepstyles.py b/docutils/tools/rst2odt_prepstyles.py index 7fd28e31d..d20e0849c 100755 --- a/docutils/tools/rst2odt_prepstyles.py +++ b/docutils/tools/rst2odt_prepstyles.py @@ -1,4 +1,9 @@ #!/usr/bin/env python + +# $Id$ +# Author: Dave Kuhlman <dkuhlman@rexx.com> +# Copyright: This module has been placed in the public domain. + """ Fix a word-processor-generated styles.odt for odtwriter use: Drop page size specifications from styles.xml in STYLE_FILE.odt. |
