[Checkins] SVN: Sandbox/ulif/grok-reference-with-rest/doc/reference-new/ Stuff to develop more intuitive reference-build.

Uli Fouquet uli at gnufix.de
Mon Oct 1 01:51:42 EDT 2007


Log message for revision 80434:
  Stuff to develop more intuitive reference-build.

Changed:
  A   Sandbox/ulif/grok-reference-with-rest/doc/reference-new/
  A   Sandbox/ulif/grok-reference-with-rest/doc/reference-new/README.txt
  A   Sandbox/ulif/grok-reference-with-rest/doc/reference-new/components.rst
  A   Sandbox/ulif/grok-reference-with-rest/doc/reference-new/conf.py
  A   Sandbox/ulif/grok-reference-with-rest/doc/reference-new/contents.rst
  A   Sandbox/ulif/grok-reference-with-rest/doc/reference-new/core.rst
  A   Sandbox/ulif/grok-reference-with-rest/doc/reference-new/decorators.rst
  A   Sandbox/ulif/grok-reference-with-rest/doc/reference-new/directives.rst
  A   Sandbox/ulif/grok-reference-with-rest/doc/reference-new/events.rst
  A   Sandbox/ulif/grok-reference-with-rest/doc/reference-new/exceptions.rst
  A   Sandbox/ulif/grok-reference-with-rest/doc/reference-new/functions.rst
  A   Sandbox/ulif/grok-reference-with-rest/doc/reference-new/gen_all.sh
  A   Sandbox/ulif/grok-reference-with-rest/doc/reference-new/index.rst
  A   Sandbox/ulif/grok-reference-with-rest/doc/reference-new/latex_manual/
  A   Sandbox/ulif/grok-reference-with-rest/doc/reference-new/latex_manual/__init__.py
  A   Sandbox/ulif/grok-reference-with-rest/doc/reference-new/latex_manual/addnodes.py
  A   Sandbox/ulif/grok-reference-with-rest/doc/reference-new/latex_manual/directives.py
  A   Sandbox/ulif/grok-reference-with-rest/doc/reference-new/latex_manual/roles.py
  A   Sandbox/ulif/grok-reference-with-rest/doc/reference-new/model.rst
  A   Sandbox/ulif/grok-reference-with-rest/doc/reference-new/myother.rst
  A   Sandbox/ulif/grok-reference-with-rest/doc/reference-new/mytest.rst
  A   Sandbox/ulif/grok-reference-with-rest/doc/reference-new/mytest.tex
  A   Sandbox/ulif/grok-reference-with-rest/doc/reference-new/reference.rst
  A   Sandbox/ulif/grok-reference-with-rest/doc/reference-new/rst2html
  A   Sandbox/ulif/grok-reference-with-rest/doc/reference-new/rst2html.py
  A   Sandbox/ulif/grok-reference-with-rest/doc/reference-new/rst2manual.py

-=-
Added: Sandbox/ulif/grok-reference-with-rest/doc/reference-new/README.txt
===================================================================
--- Sandbox/ulif/grok-reference-with-rest/doc/reference-new/README.txt	                        (rev 0)
+++ Sandbox/ulif/grok-reference-with-rest/doc/reference-new/README.txt	2007-10-01 05:51:41 UTC (rev 80434)
@@ -0,0 +1,85 @@
+=========================
+The grok reference manual
+=========================
+
+The manual is written using ReStructured Text (ReST) with support for
+the Python documentation markup. The ReST sources can be compiled into
+HTML. To build the manual, you need some special tools described
+below.
+
+The current documents were converted from LaTeX to ReST using Georg
+Brandls converter.py tool, which is part of the current doctools
+trunk. You can find it here::
+
+   http://svn.python.org/projects/doctools/trunk/
+
+
+Hints for documentation writers
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+As the format was switched from LaTeX to ReST, you might want to read
+some hints about the changed notation of entities. Please read::
+
+   http://docs.python.org/dev/documenting/fromlatex.html
+
+to learn more about the differences. General information about the
+markup can be found here::
+
+   http://docs.python.org/dev/documenting/index.html
+
+
+Build the HTML
+~~~~~~~~~~~~~~
+
+Prerequisites:
+--------------
+
+The HTML is generated basically by the new sphinx package in
+docutils. This *requires*:
+
+ * Python >= v2.5
+
+ * docutils >= v0.4
+
+*Optional* you can install pygments for syntax highlithing.
+
+Basically, it should be sufficient, to check out sphinx and other
+helper tools from the docutils subversion repository::
+
+  $ cd doc/
+  $ svn co svn co http://svn.python.org/projects/doctools/trunk/ ref-tools
+
+Checking out in the ``reference`` directory itself will cause trouble,
+so do it in the ``doc`` or another directory, which will not be parsed for
+rst files.
+
+The current docutils tool-chain is pretty focused on Python
+documentation, including the original Python directory structure and
+other things more specific for Python documentation. I believe, that
+this will change but currently you have to tweak the original sources
+a bit, to run with other documentation.
+
+To generate Grok reference (and not pure Python documentation), the
+tools can be patched with the patch provided in ``reference/``.
+
+  $ patch -p0 ref-tools < reference/ref-tools.diff
+
+The patch applies some changes to leave the index page untouched and
+to display Grok as project name.
+
+
+Compiling the sources into HTML::
+---------------------------------
+
+Create a target directory::
+
+  $ mkdir ref-build
+
+and compile the ReST sources:
+
+  $ python2.5 ref-tools/sphinx-build.py -b html reference/ ref-build
+
+
+The build process is subject to change. The format will stay.
+
+

Added: Sandbox/ulif/grok-reference-with-rest/doc/reference-new/components.rst
===================================================================
--- Sandbox/ulif/grok-reference-with-rest/doc/reference-new/components.rst	                        (rev 0)
+++ Sandbox/ulif/grok-reference-with-rest/doc/reference-new/components.rst	2007-10-01 05:51:41 UTC (rev 80434)
@@ -0,0 +1,288 @@
+
+**********
+Components
+**********
+
+The :mod:`grok` module defines a set of components that provide basic Zope 3
+functionality in a convenient way.
+
+
+:class:`grok.Adapter`
+=====================
+
+Implementation, configuration, and registration of Zope 3 adapters.
+
+
+.. class:: grok.Adapter
+
+   Base class to define an adapter. Adapters are automatically registered when a
+   module is "grokked".
+
+
+   .. attribute:: context
+
+      The adapted object.
+
+   **Directives:**
+
+   :func:`grok.context(context_obj_or_interface)`
+      May be required. Identifies the type of objects or interface for the adaptation.
+
+      If Grok can determine a context for adaptation from the module, this directive
+      can be omitted. If the automatically determined context is not correct, or if no
+      context can be derived from the module the directive is required.
+
+   :func:`grok.implements(\*interfaces)`
+      Required. Identifies the interface(s) the adapter implements.
+
+   :func:`grok.name(name)`
+      Optional. Identifies the name used for the adapter registration. If ommitted, no
+      name will be used.
+
+      When a name is used for the adapter registration, the adapter can only be
+      retrieved by explicitely using its name.
+
+   :func:`grok.provides(name)`
+      Maybe required. If the adapter implements more than one interface,
+      :func:`grok.provides` is required to disambiguate for what interface the adapter
+      will be registered.
+ 
+   **Example:** ::
+
+      import grok
+      from zope import interface
+
+      class Cave(grok.Model):
+          pass
+
+      class IHome(interface.Interface):
+          pass
+
+      class Home(grok.Adapter):
+          grok.implements(IHome)
+
+      home = IHome(cave)
+
+   **Example 2:** ::
+
+      import grok
+      from zope import interface
+   
+      class Cave(grok.Model):
+          pass
+
+      class IHome(interface.Interface):
+          pass
+
+      class Home(grok.Adapter):
+          grok.implements(IHome)
+          grok.name('home')
+
+      from zope.component import getAdapter
+      home = getAdapter(cave, IHome, name='home')
+
+
+:class:`grok.AddForm`
+=====================
+
+
+:class:`grok.Annotation`
+========================
+
+
+:class:`grok.Application`
+=========================
+
+
+grok.ClassGrokker
+=================
+
+
+:class:`grok.Container`
+=======================
+
+
+.. class:: grok.Container
+
+   Mixin base class to define a container object. The container implements the
+   zope.app.container.interfaces.IContainer interface using a BTree, providing
+   reasonable performance for large collections of objects.
+
+
+:class:`grok.DisplayForm`
+=========================
+
+
+:class:`grok.EditForm`
+======================
+
+
+:class:`grok.Form`
+==================
+
+
+:class:`grok.GlobalUtility`
+===========================
+
+
+.. class:: grok.GlobalUtility
+
+   Base class to define a globally registered utility. Global utilities are
+   automatically registered when a module is "grokked".
+
+   **Directives:**
+
+   :func:`grok.implements(\*interfaces)`
+      Required. Identifies the interfaces(s) the utility implements.
+
+   :func:`grok.name(name)`
+      Optional. Identifies the name used for the adapter registration. If ommitted, no
+      name will be used.
+
+      When a name is used for the global utility registration, the global utility can
+      only be retrieved by explicitely using its name.
+
+   :func:`grok.provides(name)`
+      Maybe required. If the global utility implements more than one interface,
+      :func:`grok.provides` is required to disambiguate for what interface the global
+      utility will be registered.
+
+
+:class:`grok.Indexes`
+=====================
+
+
+grok.InstanceGrokker
+====================
+
+
+:class:`grok.JSON`
+==================
+
+
+:class:`grok.LocalUtility`
+==========================
+
+
+.. class:: grok.LocalUtility
+
+   Base class to define a utility that will be registered local to a
+   :class:`grok.Site` or :class:`grok.Application` object by using the
+   :func:`grok.local_utility` directive.
+
+   **Directives:**
+
+   :func:`grok.implements(\*interfaces)`
+      Optional. Identifies the interfaces(s) the utility implements.
+
+   :func:`grok.name(name)`
+      Optional. Identifies the name used for the adapter registration. If ommitted, no
+      name will be used.
+
+      When a name is used for the local utility registration, the local utility can
+      only be retrieved by explicitely using its name.
+
+   :func:`grok.provides(name)`
+      Maybe required. If the local utility implements more than one interface or if
+      the implemented interface cannot be determined, :func:`grok.provides` is
+      required to disambiguate for what interface the local utility will be
+      registered.
+
+.. seealso::
+
+  Local utilities need to be registered in the context of :class:`grok.Site` or
+  :class:`grok.Application` using the :func:`grok.local_utility` directive.
+
+
+:class:`grok.Model`
+===================
+
+Base class to define an application "content" or model object. Model objects
+provide persistence and containment.
+
+
+:class:`grok.ModuleGrokker`
+===========================
+
+
+:class:`grok.MultiAdapter`
+==========================
+
+
+.. class:: grok.MultiAdapter
+
+   Base class to define a multi adapter. MultiAdapters are automatically registered
+   when a module is "grokked".
+
+   **Directives:**
+
+   :func:`grok.adapts(\*objects_or_interfaces)`
+      Required. Identifies the combination of types of objects or interfaces for the
+      adaptation.
+
+   :func:`grok.implements(\*interfaces)`
+      Required. Identifies the interfaces(s) the adapter implements.
+
+   :func:`grok.name(name)`
+      Optional. Identifies the name used for the adapter registration. If ommitted, no
+      name will be used.
+
+      When a name is used for the adapter registration, the adapter can only be
+      retrieved by explicitely using its name.
+
+   :func:`grok.provides(name)`
+      Maybe required. If the adapter implements more than one interface,
+      :func:`grok.provides` is required to disambiguate for what interface the adapter
+      will be registered.
+
+**Example:** ::
+
+   import grok
+   from zope import interface
+
+   class Fireplace(grok.Model):
+       pass
+
+   class Cave(grok.Model):
+       pass
+
+   class IHome(interface.Interface):
+       pass
+
+   class Home(grok.MultiAdapter):
+       grok.adapts(Cave, Fireplace)
+       grok.implements(IHome)
+
+       def __init__(self, cave, fireplace):
+           self.cave = cave
+           self.fireplace = fireplace
+
+   home = IHome(cave, fireplace)
+
+
+grok.PageTemplate
+=================
+
+
+grok.PageTemplateFile
+=====================
+
+
+:class:`grok.Site`
+==================
+
+Base class to define an site object. Site objects provide persistence and
+containment.
+
+
+:class:`grok.Traverser`
+=======================
+
+
+:class:`grok.View`
+==================
+
+
+:class:`grok.XMLRPC`
+====================
+

Added: Sandbox/ulif/grok-reference-with-rest/doc/reference-new/conf.py
===================================================================
--- Sandbox/ulif/grok-reference-with-rest/doc/reference-new/conf.py	                        (rev 0)
+++ Sandbox/ulif/grok-reference-with-rest/doc/reference-new/conf.py	2007-10-01 05:51:41 UTC (rev 80434)
@@ -0,0 +1,56 @@
+# -*- coding: utf-8 -*-
+#
+# Python documentation build configuration file
+#
+# The contents of this file are pickled, so don't put values in the namespace
+# that aren't pickleable (module imports are okay, they're removed automatically).
+#
+
+# The default replacements for |version| and |release|.
+# If 'auto', Sphinx looks for the Include/patchlevel.h file in the current Python
+# source tree and replaces the values accordingly.
+#
+# The short X.Y version.
+# version = '2.6'
+version = '0.10'
+# The full version, including alpha/beta/rc tags.
+# release = '2.6a0'
+release = '0.10dev'
+
+# There are two options for replacing |today|: either, you set today to some
+# non-false value, then it is used:
+today = ''
+# Else, today_fmt is used as the format for a strftime call.
+today_fmt = '%B %d, %Y'
+
+# The base URL for download links.
+download_base_url = 'http://grok.zope.org/reference/'
+
+# List of files that shouldn't be included in the build.
+unused_files = [
+    'whatsnew/2.0.rst',
+    'whatsnew/2.1.rst',
+    'whatsnew/2.2.rst',
+    'whatsnew/2.3.rst',
+    'whatsnew/2.4.rst',
+    'whatsnew/2.5.rst',
+    'maclib/scrap.rst',
+    'library/xmllib.rst',
+    'library/xml.etree.rst',
+]
+
+# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
+# using the given strftime format.
+last_updated_format = '%b %d, %Y'
+
+# If true, SmartyPants will be used to convert quotes and dashes to
+# typographically correct entities.
+use_smartypants = True
+
+# If true, '()' will be appended to :func: etc. cross-reference text.
+add_function_parentheses = True
+
+# If true, the current module name will be prepended to all description
+# unit titles (such as .. function::).
+add_module_names = True
+

Added: Sandbox/ulif/grok-reference-with-rest/doc/reference-new/contents.rst
===================================================================
--- Sandbox/ulif/grok-reference-with-rest/doc/reference-new/contents.rst	                        (rev 0)
+++ Sandbox/ulif/grok-reference-with-rest/doc/reference-new/contents.rst	2007-10-01 05:51:41 UTC (rev 80434)
@@ -0,0 +1,18 @@
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+ Grok Documentation contents
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+.. toctree::
+
+   core.rst
+   components.rst
+   directives.rst
+   decorators.rst
+   functions.rst
+   events.rst
+   exceptions.rst
+
+bugs.rst
+about.rst
+license.rst
+copyright.rst

Added: Sandbox/ulif/grok-reference-with-rest/doc/reference-new/core.rst
===================================================================
--- Sandbox/ulif/grok-reference-with-rest/doc/reference-new/core.rst	                        (rev 0)
+++ Sandbox/ulif/grok-reference-with-rest/doc/reference-new/core.rst	2007-10-01 05:51:41 UTC (rev 80434)
@@ -0,0 +1,93 @@
+
+****
+Core
+****
+
+The :mod:`grok` module defines a few functions to interact with grok itself.
+
+
+:func:`grok.grok` -- Grok a package or module
+=============================================
+
+
+.. function:: grok.grok(dotted_name)
+
+   Grokking a package or module activates the contained
+   components(like models, views, adapters, templates, etc.) and
+   registers them with Zope 3's component architecture.
+
+   The `dotted_name` must specify either a Python module or package
+   that is available from the current PYTHONPATH.
+
+   Grokking a module:
+
+   #. Scan the module for known components: models, adapters, utilities, views,
+      traversers, templates and subscribers.
+
+   #. Check whether a directory with file system templates exists
+      (:file:`<modulename>_templates`).  If it exists, load the file
+      system templates into the template registry for this module.
+
+   #. Determine the module context.
+
+   #. Register all components with the Zope 3 component architecture.
+
+   #. Initialize schemata for registered models
+
+   Grokking a package:
+
+   #. Grok the package as a module.
+
+   #. Check for a static resource directory (:file:`static`) and
+      register it if it exists.
+
+   #. Recursively grok all sub-modules and sub-packages.
+
+.. raw:: latex
+
+    Grokking a module:
+
+    \begin{enumerate}
+
+        \item Scan the module for known components: models, adapters,
+              utilities, views, traversers, templates and subscribers.
+
+        \item Check whether a directory with file system templates
+              exists (\file{<modulename>_templates}).  If it exists,
+              load the file system templates into the template
+              registry for this module.
+
+        \item Determine the module context.
+
+        \item Register all components with the Zope 3 component architecture.
+
+        \item Initialize schemata for registered models
+
+    \end{enumerate}
+
+    Grokking a module:
+
+    \begin{enumerate}
+
+        \item {
+    Scan the module for known components: models, adapters,
+    utilities, views, traversers, templates and subscribers.
+    }
+
+        \item Check whether a directory with file system templates
+              exists (\file{<modulename>_templates}).  If it exists,
+              load the file system templates into the template
+              registry for this module.
+
+        \item Determine the module context.
+
+        \item Register all components with the Zope 3 component architecture.
+
+        \item Initialize schemata for registered models
+
+    \end{enumerate}
+
+    \begin{note}
+    \end{note}
+
+..
\ No newline at end of file

Added: Sandbox/ulif/grok-reference-with-rest/doc/reference-new/decorators.rst
===================================================================
--- Sandbox/ulif/grok-reference-with-rest/doc/reference-new/decorators.rst	                        (rev 0)
+++ Sandbox/ulif/grok-reference-with-rest/doc/reference-new/decorators.rst	2007-10-01 05:51:41 UTC (rev 80434)
@@ -0,0 +1,28 @@
+
+**********
+Decorators
+**********
+
+grok uses a few decorators to register functions or methods for specific
+functionality.
+
+
+:func:`grok.subscribe` -- Register a function as a subscriber for an event
+==========================================================================
+
+
+.. function:: subscribe(*classes_or_interfaces)
+
+   Declare that the decorated function subscribes to an event or a combination of
+   objects and events and register it.
+
+   Applicable on module-level for functions. Requires at least one class or
+   interface as argument.
+
+   (Similar to Zope 3's :func:`subscriber` decorator, but automatically performs
+   the registration of the component.)
+
+
+grok.action
+===========
+

Added: Sandbox/ulif/grok-reference-with-rest/doc/reference-new/directives.rst
===================================================================
--- Sandbox/ulif/grok-reference-with-rest/doc/reference-new/directives.rst	                        (rev 0)
+++ Sandbox/ulif/grok-reference-with-rest/doc/reference-new/directives.rst	2007-10-01 05:51:41 UTC (rev 80434)
@@ -0,0 +1,566 @@
+
+**********
+Directives
+**********
+
+The :mod:`grok` module defines a set of directives that allow you to configure
+and register your components. Most directives assume a default, based on the
+environment of a module. (For example, a view will be automatically associated
+with a model if the association can be made unambigously.)
+
+If no default can be assumed for a value, grok will explicitly tell you what is
+missing and how you can provide a default or explicit assignment for the value
+in question.
+
+
+:func:`grok.AutoFields` -- Deduce schema fields automatically
+=============================================================
+
+
+.. function:: grok.AutoFields(class_or_interface)
+
+   A class level directive, which can be used inside :class:`Form`
+   classes to automatically deduce the form fields from the schema of
+   the context `class_or_interface`.
+
+   Different to most other directives, :func:`grok.AutoFields` is used
+   more like a function and less like a pure declaration.
+
+   The following example makes use of the :func:`grok.AutoFields`
+   directive, in that one field is omitted from the form before
+   rendering:
+
+**Example:** ::
+
+   import grok
+   from zope import interface, schema
+
+   class IMammoth(interface.Interface):
+       name = schema.TextLine(title=u"Name")
+       size = schema.TextLine(title=u"Size", default=u"Quite normal")
+
+   class Mammoth(grok.Model):
+       interface.implements(IMammoth)
+
+   class Edit(grok.EditForm):
+       grok.context(Mammoth)
+
+       form_fields = grok.AutoFields(Mammoth).omit('size')
+
+In this example the ``size`` attribute will not show up in the
+resulting edit view.
+
+
+.. seealso::
+
+   :class:`grok.EditForm`, :func:`grok.Fields`
+
+
+:func:`grok.adapts` -- Declare that a class adapts certain objects
+==================================================================
+
+
+.. function:: grok.adapts(*classes_or_interfaces)
+
+   A class-level directive to declare that a class adapts objects of
+   the classes or interfaces given in `\*classes_or_interfaces`.
+
+   This directive accepts several arguments.
+
+   It works much like the :mod:`zope.component`\ s :func:`adapts()`,
+   but you do not have to make a ZCML entry to register the adapter.
+
+   **Example:** ::
+
+      import grok
+      from zope import interface, schema
+      from zope.size.interfaces import ISized
+
+      class IMammoth(interface.Interface):
+          name = schema.TextLine(title=u"Name")
+          size = schema.TextLine(title=u"Size", default=u"Quite normal")
+
+      class Mammoth(grok.Model):
+          interface.implements(IMammoth)
+
+      class MammothSize(object):
+          grok.implements(ISized)
+          grok.adapts(IMammoth)
+
+          def __init__(self, context):
+              self.context = context
+
+          def sizeForSorting(self):
+              return ('byte', 1000)
+
+          def sizeForDisplay(self):
+              return ('1000 bytes')
+
+   Having :class:`MammothSize` available, you can register it as an adapter,
+   without a single line of ZCML::
+
+      >>> manfred = Mammoth()
+      >>> from zope.component import provideAdapter
+      >>> provideAdapter(MammothSize)
+      >>> from zope.size.interfaces import ISized
+      >>> size = ISized(manfred)
+      >>> size.sizeForDisplay()
+      '1000 bytes'
+
+
+   .. seealso::
+
+      :func:`grok.implements`
+
+
+:func:`grok.baseclass` -- declare a class as base
+=================================================
+
+
+.. function:: grok.baseclass()
+
+   A class-level directive without argument to mark something as a
+   base class. Base classes are are not grokked.
+
+   Another way to indicate that something is a base class, is by
+   postfixing the classname with ``'Base'``.
+
+   The baseclass mark is not inherited by subclasses, so those
+   subclasses will be grokked (except they are explicitly declared as
+   baseclasses as well).
+
+   **Example:** ::
+
+      import grok
+
+      class ModelBase(grok.Model):
+          pass
+
+      class ViewBase(grok.View):
+          def render(self):
+              return "hello world"
+
+      class AnotherView(grok.View):
+          grok.baseclass()
+
+          def render(self):
+              return "hello world"
+
+      class WorkingView(grok.View):
+          pass
+
+   Using this example, only the :class:`WorkingView` will serve as a
+   view, while calling the :class:`ViewBase` or :class:`AnotherView`
+   will lead to a :exc:`ComponentLookupError`.
+
+
+:func:`grok.define_permission` -- define a permission
+=====================================================
+
+
+.. function:: grok.define_permission(name)
+
+   A module-level directive to define a permission with name
+   `name`. Usually permission names are prefixed by a component- or
+   application name and a dot to keep them unique.
+
+   Because in Grok by default everything is accessible by everybody,
+   it is important to define permissions, which restrict access to
+   certain principals or roles.
+
+   **Example:** ::
+
+      import grok
+      grok.define_permission('cave.enter')
+
+
+   .. seealso::
+
+      :func:`grok.require`, :class:`grok.Permission`, :class:`grok.Role`
+
+   .. versionchanged:: 0.11
+      replaced by :class:`grok.Permission`.
+
+
+:func:`grok.Fields` -- declare schema fields of a form
+======================================================
+
+.. function:: grok.Fields(**schemas)
+
+   A class level directive, which can be used inside :class:`grok.Form`
+   classes.
+
+   A :class:`grok.Fields` can receive keyword parameters with schema
+   fields. These should be available in the definition order.
+
+   **Example:** ::
+
+      import grok
+      from zope import schema
+
+      class Mammoth(grok.Model):
+          pass
+
+      class Edit(grok.EditForm):
+          fields = grok.Fields(
+              b = schema.TextLine(title=u"Beta"),
+              a = schema.TextLine(title=u"Alpha"),
+
+   Given the above code, when the :class:`Edit` form is rendered, the
+   :class:`Textlines` `b` and `a` will appear as input fields in that
+   order. This is due to the fact, that by default the `fields`
+   variable is taken into account, when rendering forms.
+
+   .. seealso::
+
+      :func:`grok.AutoFields`, :class:`grok.Form`
+
+
+:func:`grok.implements` -- indicate, that a class implements an interface
+=========================================================================
+
+
+.. function:: grok.implements(*interfaces)
+
+   A class level directive to declare one or more `interfaces`, as
+   implementers of the surrounding class. This directive allows
+   several parameters.
+
+   :func:`grok.implements` is currently an alias for 
+   :func:`zope.interface.implements`.
+
+   **Example:** ::
+
+      >>> import grok
+      >>> from zope import interface
+      >>> class IPaintable(interface.Interface):
+      ...   pass
+      ...
+      >>> class Cave(object):
+      ...   pass
+      ...
+      >>> cave = Cave()
+      >>> IPaintable.providedBy(cave)
+      False
+      >>> class PaintableCave(object):
+      ...   grok.implements(IPaintable)
+      ...
+      >>> cave = PaintableCave()
+      >>> IPaintable.providedBy(cave)
+      True
+
+
+:func:`grok.context` -- Declare the context for views, adapters, etc.
+=====================================================================
+
+
+.. function:: grok.context(*class_or_interface)
+
+   A class or module level directive to indicate the context for
+   something (class or module) in the same scope. When used on module
+   level, it will set the context for all views, adapters, etc. in
+   that module. When used on class level, it will set the context for
+   that particular class.
+
+   With Grok contexts are set automatically for some objects, if they
+   are unambigous. For example a :class:`grok.View` will get the only
+   :class:`grok.Application` or :class:`grok.Model` class as context,
+   iff there exists exactly one in the same module. If there are more
+   possible contexts or you want to set a type (class/interface) from
+   another module as context, than the one choosen by default, then
+   you have to call :func:`grok.context` explicitly.
+
+   **Example:**
+
+   Here the :func:`grok.context` directive indicates, that
+   :class:`Mammoth` instances will be the context of :class:`Index`
+   views (and not instances of :class:`Cave`) ::
+
+
+      import grok
+
+      class Mammoth(grok.Model):
+          pass
+
+      class Cave(grok.Model):
+          pass
+
+      class Index(grok.View):
+          grok.context(Mammoth)
+
+
+
+   .. seealso::
+
+      :class:`grok.View`, :class:`grok.Adapter`, :class:`grok.MultiAdapter`
+
+   
+
+
+:func:`grok.global_utility` -- register a global utility
+========================================================
+
+
+.. function:: grok.global_utility(factory[, provides=None[, name=u'']])
+
+   A module level directive to register a global utility.
+
+   `factory` - the factory that creates the utility.
+
+   `provides` - the interface the utility should be looked up with.
+
+   `name` - the name of the utility.
+
+   The latter two parameters are optional. 
+
+   To register the utility correctly, Grok must be able to identify an
+   interface provided by the utility. If none is given, Grok checks
+   whether (exactly) one interface is implemented by the factory to be
+   registered (see example below). If more than one interface is
+   implemented by a class, use :func:`grok.provides` to specify which
+   one to use. If no interface is implemented by the instances
+   delivered by the factory, use :func:`grok.implements` to specify
+   one.
+
+   Another way to register global utilities with Grok is to subclass
+   from :class:`grok.GlobalUtility`.
+
+
+   **Example:**
+
+      Given the following module code: ::
+
+         import grok
+         from zope import interface
+
+         class IFireplace(interface.Interface):
+             pass
+
+         class Fireplace(object):
+             grok.implements(IFireplace)
+
+         grok.global_utility(Fireplace)
+         grok.global_utility(Fireplace, name='hot')
+
+      Then the following works: ::
+
+         >>> from zope import component
+         >>> fireplace = component.getUtility(IFireplace)
+         >>> IFireplace.providedBy(fireplace)
+         True
+         >>> isinstance(fireplace, Fireplace)
+         True
+         
+         >>> fireplace = component.getUtility(IFireplace, name='hot')
+         >>> IFireplace.providedBy(fireplace)
+         True
+         >>> isinstance(fireplace, Fireplace)
+         True
+
+   .. seealso::
+
+      :class:`grok.GlobalUtility`, :func:`grok.provides`, 
+      :func:`grok.implements`
+
+
+:func:`grok.name` -- associate a component with a name
+======================================================
+
+
+.. function:: grok.name(name)
+
+   A class level directive used to associate a component with a single
+   name `name`. Typically this directive is optional. The default behaviour
+   when no name is given depends on the component. The same applies to
+   the semantics of this directive: for what exactly a name is set
+   when using this directive, depends on the component.
+
+   **Example:** ::
+
+      import grok
+
+      class Mammoth(grok.Model):
+         pass
+
+      class Index(grok.View):
+         grok.name('index')
+
+
+   .. seealso::
+
+      :class:`grok.Adapter`, :class:`grok.Annotation`,
+      :class:`grok.GlobalUtility`, :class:`grok.Indexes`, 
+      :class:`grok.MultiAdapter`, :class:`grok.Role`, 
+      :class:`grok.View`
+
+
+
+
+:func:`grok.local_utility` -- register a local utility
+======================================================
+
+
+.. function:: grok.local_utility(factory[, provides=None[, name=u''[, setup=None[, public=False[, name_in_container=None]]]]])
+
+   A class level directive to register a local utility.
+
+   `factory` -- the factory that creates the utility.
+
+   `provides` -- the interface the utility should be looked up with.
+
+   `name` -- the name of the utility.
+
+   `setup` -- a callable that receives the utility as its single
+      argument, it is called after the utility has been created and
+      stored.
+
+   `public` -- if `False`, the utility will be stored below
+      `++etc++site`.  If `True`, the utility will be stored directly
+      in the site.  The site should in this case be a container.
+
+   `name_in_container` -- the name to use for storing the utility.
+
+   All but the first parameter are optional. 
+
+   To register a local utility correctly, Grok must know about the
+   interface, the utility should be looked up with. If none is given,
+   Grok looks up any interfaces implemented by instances delivered by
+   `factory` and if exactly one can be found, it is taken. See
+   :func:`grok.global_utility`.
+
+   Every single combination of interfaces and names can only be
+   registered once per module.
+
+   It is not possible to declare a local utility as public, if the
+   site is not a container. Grok will remind you of this. To store a
+   utility in a container, a `name_in_container` is needed. If
+   none is given, Grok will make up one automatically.
+
+   An alternative way to define a local utility is to subclass from
+   :class:`grok.LocalUtility`.
+
+   **Example:**
+
+      The following code registers a local unnamed utility `fireplace` in
+      instances of :class:`Cave` ::
+
+         import grok
+         from zope import interface
+
+         class IFireplace(interface.Interface):
+             pass
+
+         class Fireplace(grok.LocalUtility):
+             grok.implements(IFireplace)
+
+         class Cave(grok.Container, grok.Site):
+             grok.local_utility(Fireplace, public=True, 
+                                name_in_container='fireplace')
+      
+
+   .. seealso::
+
+      :func:`grok.global_utility`, :class:`grok.LocalUtility`
+
+
+:func:`grok.provides`
+=====================
+
+
+.. function:: grok.provides(*arg)
+
+   foobar
+
+
+:func:`grok.resourcedir --- XXX Not implemented yet`
+====================================================
+
+
+.. function:: grok.resourcedir(*arg)
+
+   foobar
+
+   Resource directories are used to embed static resources like HTML-,
+   JavaScript-, CSS- and other files in your application.
+
+   XXX insert directive description here (first: define the name,
+   second: describe the default behaviour if the directive isn't
+   given)
+
+   A resource directory is created when a package contains a directory
+   with the name :file:`static`. All files from this directory become
+   accessible from a browser under the URL
+   :file:`http://<servername>/++resource++<packagename>/<filename>`.
+
+   **Example:** 
+
+   The package :mod:`a.b.c` is grokked and contains a directory
+   :file:`static` which contains the file :file:`example.css`. The
+   stylesheet will be available via
+   :file:`http://<servername>/++resource++a.b.c/example.css`.
+
+.. note::
+
+   A package can never have both a :file:`static` directory and a
+   Python module with the name :file:`static.py` at the same
+   time. grok will remind you of this conflict when grokking a package
+   by displaying an error message.
+
+
+Linking to resources from templates
+-----------------------------------
+
+grok provides a convenient way to calculate the URLs to static
+resource using the keyword :keyword:`static` in page templates::
+
+<link rel="stylesheet" tal:attributes="href static/example.css" type="text/css">
+
+The keyword :keyword:`static` will be replaced by the reference to
+the resource directory for the package in which the template was
+registered.
+
+
+:func:`grok.require`
+====================
+
+
+.. function:: grok.require(*arg)
+
+   foobar
+
+
+:func:`grok.site`
+=================
+
+
+.. function:: grok.site(*arg)
+
+   foobar
+
+
+:func:`grok.template`
+=====================
+
+
+.. function:: grok.template(*arg)
+
+   foobar
+
+
+:func:`grok.templatedir`
+========================
+
+
+.. function:: grok.templatedir(*arg)
+
+   foobar
+
+
+:func:`grok.title`
+========================
+
+
+.. function:: grok.title(*arg)
+
+   foobar
+

Added: Sandbox/ulif/grok-reference-with-rest/doc/reference-new/events.rst
===================================================================
--- Sandbox/ulif/grok-reference-with-rest/doc/reference-new/events.rst	                        (rev 0)
+++ Sandbox/ulif/grok-reference-with-rest/doc/reference-new/events.rst	2007-10-01 05:51:41 UTC (rev 80434)
@@ -0,0 +1,65 @@
+
+******
+Events
+******
+
+grok provides convenient access to a set of often-used events from Zope 3. Those
+events include object and containment events. All events are available as
+interface and implemented class.
+
+
+grok.IContainerModifiedEvent
+============================
+
+
+grok.IObjectAddedEvent
+======================
+
+
+grok.IObjectCopiedEvent
+=======================
+
+
+grok.IObjectCreatedEvent
+========================
+
+
+grok.IObjectModifiedEvent
+=========================
+
+
+grok.IObjectMovedEvent
+======================
+
+
+grok.IObjectRemovedEvent
+========================
+
+
+grok.ContainerModifiedEvent
+===========================
+
+
+grok.ObjectAddedEvent
+=====================
+
+
+grok.ObjectCopiedEvent
+======================
+
+
+grok.ObjectCreatedEvent
+=======================
+
+
+grok.ObjectModifiedEvent
+========================
+
+
+grok.ObjectMovedEvent
+=====================
+
+
+grok.ObjectRemovedEvent
+=======================
+

Added: Sandbox/ulif/grok-reference-with-rest/doc/reference-new/exceptions.rst
===================================================================
--- Sandbox/ulif/grok-reference-with-rest/doc/reference-new/exceptions.rst	                        (rev 0)
+++ Sandbox/ulif/grok-reference-with-rest/doc/reference-new/exceptions.rst	2007-10-01 05:51:41 UTC (rev 80434)
@@ -0,0 +1,59 @@
+
+**********
+Exceptions
+**********
+
+grok tries to inform you about errors early and with as much guidance as
+possible. grok can detect some errors already while importing a module, which
+will lead to the :class:`GrokImportError`.  Other errors require more context
+and can only be detected while executing the :func:`grok` function.
+
+
+:class:`grok.GrokImportError` -- errors while importing a module
+================================================================
+
+This exception is raised if a grok-specific problem was found while importing a
+module of your application. :class:`GrokImportError` means there was a problem
+in how you are using a part of grok. The error message tries to be as
+informative as possible tell you why something went wrong and how you can fix
+it.
+
+:class:`GrokImportError` is a subclass of Python's :class:`ImportError`.
+
+Examples of situations in which a GrokImportError occurs:
+
+* Using a directive in the wrong context (e.g. grok.templatedir on class-level
+  instead of module-level.)
+
+* Using a decorator with wrong arguments (e.g. grok.subscribe without any
+  argument)
+
+* ...
+
+
+:class:`grok.GrokError` -- errors while grokking a module
+=========================================================
+
+This exception is raised if an error occurs while grokking a module.
+
+Typically a :class:`GrokError` will be raised if one of your modules uses a
+feature of grok that requires some sort of unambigous context to establish a
+reasonable default.
+
+For example, the :class:`grok.View` requires exactly one model to be defined
+locally in the module to assume a default module to be associated with. Having
+no model defined, or more than one model, will lead to an error because the
+context is either underspecified or ambigous.
+
+The error message of a :class:`GrokError` will include the reason for the error,
+the place in your code that triggered the error, and a hint, to help you fix the
+error.
+
+
+.. class:: GrokError(Exception)
+
+
+   .. attribute:: GrokError.component
+
+      The component that was grokked and triggered the error.
+

Added: Sandbox/ulif/grok-reference-with-rest/doc/reference-new/functions.rst
===================================================================
--- Sandbox/ulif/grok-reference-with-rest/doc/reference-new/functions.rst	                        (rev 0)
+++ Sandbox/ulif/grok-reference-with-rest/doc/reference-new/functions.rst	2007-10-01 05:51:41 UTC (rev 80434)
@@ -0,0 +1,81 @@
+
+*********
+Functions
+*********
+
+The :mod:`grok` module provides a number of convenience functions to aid in
+common tasks.
+
+
+:func:`grok.getSite`
+====================
+
+
+.. function:: grok.getSite()
+
+   Get the current site object.
+
+
+   .. seealso::
+
+      Site objects are instances of :class:`grok.Site` and/or
+      :class:`grok.Application`.
+
+
+   .. seealso::
+
+      `Web Component Development With Zope 3, second edition <http://worldcookery.com/WhereToBuy>`_
+         By Philiip von Weitershaussen; Chapter 18 describes the use of Site objects.
+
+
+:func:`grok.notify`
+===================
+
+
+.. function:: grok.notify(event)
+
+   Send `event` to event subscribers.
+
+   Example::
+
+      import grok
+
+      class Mammoth(object):
+          def __init__(self, name):
+              self.name = name
+
+      manfred = Mammoth('manfred')
+
+      grok.notify(grok.ObjectCreatedEvent(manfred))
+
+
+   .. seealso::
+
+      Grok events provide a selection of common event types.
+
+
+   .. seealso::
+
+      `Web Component Development With Zope 3, second edition <http://worldcookery.com/WhereToBuy>`_
+         By Philiip von Weitershaussen; Chapter 16 describes the Zope 3 event system.
+
+
+:func:`grok.url`
+================
+
+
+.. function:: grok.url(request, object, [, name])
+
+   Construct a URL for the given `request` and `object`.
+
+   `name` may be a string that gets appended to the object URL. Commonly used to
+   construct an URL to a particular view on the object.
+
+   This function returns the constructed URL as a string.
+
+
+   .. seealso::
+
+      View classes derived from :class:`grok.View` have a similar :meth:`url` method
+      for constructing URLs.
+

Added: Sandbox/ulif/grok-reference-with-rest/doc/reference-new/gen_all.sh
===================================================================
--- Sandbox/ulif/grok-reference-with-rest/doc/reference-new/gen_all.sh	                        (rev 0)
+++ Sandbox/ulif/grok-reference-with-rest/doc/reference-new/gen_all.sh	2007-10-01 05:51:41 UTC (rev 80434)
@@ -0,0 +1,26 @@
+#!/bin/sh
+##
+## gen_all.sh
+## Login : <uli at pu.smp.net>
+## Started on  Fri Sep 28 05:06:00 2007 Uli Fouquet
+## $Id$
+## 
+## Copyright (C) 2007 Uli Fouquet
+## This program is free software; you can redistribute it and/or modify
+## it under the terms of the GNU General Public License as published by
+## the Free Software Foundation; either version 2 of the License, or
+## (at your option) any later version.
+## 
+## This program is distributed in the hope that it will be useful,
+## but WITHOUT ANY WARRANTY; without even the implied warranty of
+## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+## GNU General Public License for more details.
+## 
+## You should have received a copy of the GNU General Public License
+## along with this program; if not, write to the Free Software
+## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+##
+python rst2manual.py --traceback --documentclass manual --use-latex-toc --use-latex-docinfo --use-verbatim-when-possible mytest.rst mytest.tex
+
+mkhowto --html mytest.tex
+


Property changes on: Sandbox/ulif/grok-reference-with-rest/doc/reference-new/gen_all.sh
___________________________________________________________________
Name: svn:executable
   + *

Added: Sandbox/ulif/grok-reference-with-rest/doc/reference-new/index.rst
===================================================================
--- Sandbox/ulif/grok-reference-with-rest/doc/reference-new/index.rst	                        (rev 0)
+++ Sandbox/ulif/grok-reference-with-rest/doc/reference-new/index.rst	2007-10-01 05:51:41 UTC (rev 80434)
@@ -0,0 +1,36 @@
+.. _reference-index:
+
+#################################
+  Grok reference
+#################################
+
+:Release: |version|
+:Date: |today|
+
+   Grok means to understand so thoroughly that the observer becomes a part
+   of the observed -- merge, blend, intermarry, lose identity in group
+   experience. It means almost everything that we mean by religion,
+   philosophy, and science -- it means as little to us (because we are from
+   Earth) as color means to a blind man. -- `Robert A. Heinlein, Stranger in
+   a Strange Land`
+
+
+This is the grok reference documentation. It is organized by the Python
+artefacts that implement the concepts.
+
+Grok makes Zope 3 concepts more accessible for application developers. This
+reference is not intended as introductory material for those concepts. Please
+refer to the original Zope 3 documentation and the grok tutorial for
+introductory material.
+
+
+.. toctree::
+   :maxdepth: 2
+
+   core.rst
+   components.rst
+   directives.rst
+   decorators.rst
+   functions.rst
+   events.rst
+   exceptions.rst

Added: Sandbox/ulif/grok-reference-with-rest/doc/reference-new/latex_manual/__init__.py
===================================================================
--- Sandbox/ulif/grok-reference-with-rest/doc/reference-new/latex_manual/__init__.py	                        (rev 0)
+++ Sandbox/ulif/grok-reference-with-rest/doc/reference-new/latex_manual/__init__.py	2007-10-01 05:51:41 UTC (rev 80434)
@@ -0,0 +1,2201 @@
+# Author: Engelbert Gruber
+# Contact: grubert at users.sourceforge.net
+# Revision: $Revision: 4242 $
+# Date: $Date: 2006-01-06 00:28:53 +0100 (Fri, 06 Jan 2006) $
+# Copyright: This module has been placed in the public domain.
+
+"""
+LaTeX2e document tree Writer.
+
+Output suitable for use with `mkhowto'.
+"""
+
+__docformat__ = 'reStructuredText'
+
+# code contributions from several people included, thanks to all.
+# some named: David Abrahams, Julien Letessier, Lele Gaifax, and others.
+#
+# convention deactivate code by two # e.g. ##.
+
+import sys
+import time
+import re
+import string
+from types import ListType
+from docutils import frontend, nodes, languages, writers, utils
+from docutils.writers import latex2e
+from docutils.writers.latex2e import (DocumentClass, Table, Babel,
+                                      latex_headings)
+
+#class Writer(writers.Writer):
+class Writer(latex2e.Writer):    
+
+    supported = ('latex_manual')
+    """Formats this writer supports."""
+
+    settings_spec = (
+        'LaTeX-Specific Options',
+        'The LaTeX "--output-encoding" default is "latin-1:strict".',
+        (('Specify documentclass.  Default is "manual".',
+          ['--documentclass'],
+          {'default': 'manual', }),
+         ('Specify document options.  Multiple options can be given, '
+          'separated by commas.  Default is "10pt,a4paper".',
+          ['--documentoptions'],
+          {'default': '10pt,a4paper', }),
+         ('Use LaTeX footnotes. LaTeX supports only numbered footnotes (does it?). '
+          'Default: no, uses figures.',
+          ['--use-latex-footnotes'],
+          {'default': 0, 'action': 'store_true',
+           'validator': frontend.validate_boolean}),
+         ('Format for footnote references: one of "superscript" or '
+          '"brackets".  Default is "superscript".',
+          ['--footnote-references'],
+          {'choices': ['superscript', 'brackets'], 'default': 'superscript',
+           'metavar': '<format>',
+           'overrides': 'trim_footnote_reference_space'}),
+         ('Use LaTeX citations. '
+          'Default: no, uses figures which might get mixed with images.',
+          ['--use-latex-citations'],
+          {'default': 0, 'action': 'store_true',
+           'validator': frontend.validate_boolean}),
+         ('Format for block quote attributions: one of "dash" (em-dash '
+          'prefix), "parentheses"/"parens", or "none".  Default is "dash".',
+          ['--attribution'],
+          {'choices': ['dash', 'parentheses', 'parens', 'none'],
+           'default': 'dash', 'metavar': '<format>'}),
+         ('Specify a stylesheet file. The file will be "input" by latex in '
+          'the document header.  Default is no stylesheet ("").  '
+          'Overrides --stylesheet-path.',
+          ['--stylesheet'],
+          {'default': '', 'metavar': '<file>',
+           'overrides': 'stylesheet_path'}),
+         ('Specify a stylesheet file, relative to the current working '
+          'directory.  Overrides --stylesheet.',
+          ['--stylesheet-path'],
+          {'metavar': '<file>', 'overrides': 'stylesheet'}),
+         ('Table of contents by docutils (default) or latex. Latex (writer) '
+          'supports only one ToC per document, but docutils does not write '
+          'pagenumbers.',
+          ['--use-latex-toc'],
+          {'default': 0, 'action': 'store_true',
+           'validator': frontend.validate_boolean}),
+         ('Let LaTeX print author and date, do not show it in docutils '
+          'document info.',
+          ['--use-latex-docinfo'],
+          {'default': 0, 'action': 'store_true',
+           'validator': frontend.validate_boolean}),
+         ('Color of any hyperlinks embedded in text '
+          '(default: "blue", "0" to disable).',
+          ['--hyperlink-color'], {'default': 'blue'}),
+         ('Enable compound enumerators for nested enumerated lists '
+          '(e.g. "1.2.a.ii").  Default: disabled.',
+          ['--compound-enumerators'],
+          {'default': None, 'action': 'store_true',
+           'validator': frontend.validate_boolean}),
+         ('Disable compound enumerators for nested enumerated lists.  This is '
+          'the default.',
+          ['--no-compound-enumerators'],
+          {'action': 'store_false', 'dest': 'compound_enumerators'}),
+         ('Enable section ("." subsection ...) prefixes for compound '
+          'enumerators.  This has no effect without --compound-enumerators.  '
+          'Default: disabled.',
+          ['--section-prefix-for-enumerators'],
+          {'default': None, 'action': 'store_true',
+           'validator': frontend.validate_boolean}),
+         ('Disable section prefixes for compound enumerators.  '
+          'This is the default.',
+          ['--no-section-prefix-for-enumerators'],
+          {'action': 'store_false', 'dest': 'section_prefix_for_enumerators'}),
+         ('Set the separator between section number and enumerator '
+          'for compound enumerated lists.  Default is "-".',
+          ['--section-enumerator-separator'],
+          {'default': '-', 'metavar': '<char>'}),
+         ('When possibile, use verbatim for literal-blocks. '
+          'Default is to always use the mbox environment.',
+          ['--use-verbatim-when-possible'],
+          {'default': 0, 'action': 'store_true',
+           'validator': frontend.validate_boolean}),
+         ('Table style. "standard" with horizontal and vertical lines, '
+          '"booktabs" (LaTeX booktabs style) only horizontal lines '
+          'above and below the table and below the header or "nolines".  '
+          'Default: "standard"',
+          ['--table-style'],
+          {'choices': ['standard', 'booktabs','nolines'], 'default': 'standard',
+           'metavar': '<format>'}),
+         ('LaTeX graphicx package option. '
+          'Possible values are "dvips", "pdftex". "auto" includes LaTeX code '
+          'to use "pdftex" if processing with pdf(la)tex and dvips otherwise. '
+          'Default is no option.',
+          ['--graphicx-option'],
+          {'default': ''}),
+         ('LaTeX font encoding. '
+          'Possible values are "T1", "OT1", "" or some other fontenc option. '
+          'The font encoding influences available symbols, e.g. "<<" as one '
+          'character. Default is "" which leads to package "ae" (a T1 '
+          'emulation using CM fonts).',
+          ['--font-encoding'],
+          {'default': ''}),
+          ),)
+
+    settings_defaults = {'output_encoding': 'latin-1'}
+
+    relative_path_settings = ('stylesheet_path',)
+
+    config_section = 'latex2e writer'
+    config_section_dependencies = ('writers',)
+
+    output = None
+    """Final translated form of `document`."""
+
+    def __init__(self):
+        #latex2e.Writer.__init__(self)
+        writers.Writer.__init__(self)
+        self.translator_class = LaTeXManualTranslator
+
+    def translate(self):
+        visitor = self.translator_class(self.document)
+        self.document.walkabout(visitor)
+        self.output = visitor.astext()
+        self.head_prefix = visitor.head_prefix
+        self.head = visitor.head
+        self.body_prefix = visitor.body_prefix
+        self.body = visitor.body
+        self.body_suffix = visitor.body_suffix
+
+## """
+## Notes on LaTeX
+## --------------
+
+## * latex does not support multiple tocs in one document.
+##   (might be no limitation except for docutils documentation)
+
+## * width
+
+##   * linewidth - width of a line in the local environment
+##   * textwidth - the width of text on the page
+
+##   Maybe always use linewidth ?
+
+##   *Bug* inside a minipage a (e.g. Sidebar) the linewidth is
+##         not changed, needs fix in docutils so that tables
+##         are not too wide.
+
+##         So we add locallinewidth set it initially and
+##         on entering sidebar and reset on exit.
+## """
+
+## class Babel:
+##     """Language specifics for LaTeX."""
+##     # country code by a.schlock.
+##     # partly manually converted from iso and babel stuff, dialects and some
+##     _ISO639_TO_BABEL = {
+##         'no': 'norsk',     #XXX added by hand ( forget about nynorsk?)
+##         'gd': 'scottish',  #XXX added by hand
+##         'hu': 'magyar',    #XXX added by hand
+##         'pt': 'portuguese',#XXX added by hand
+##         'sl': 'slovenian',
+##         'af': 'afrikaans',
+##         'bg': 'bulgarian',
+##         'br': 'breton',
+##         'ca': 'catalan',
+##         'cs': 'czech',
+##         'cy': 'welsh',
+##         'da': 'danish',
+##         'fr': 'french',
+##         # french, francais, canadien, acadian
+##         'de': 'ngerman',  #XXX rather than german
+##         # ngerman, naustrian, german, germanb, austrian
+##         'el': 'greek',
+##         'en': 'english',
+##         # english, USenglish, american, UKenglish, british, canadian
+##         'eo': 'esperanto',
+##         'es': 'spanish',
+##         'et': 'estonian',
+##         'eu': 'basque',
+##         'fi': 'finnish',
+##         'ga': 'irish',
+##         'gl': 'galician',
+##         'he': 'hebrew',
+##         'hr': 'croatian',
+##         'hu': 'hungarian',
+##         'is': 'icelandic',
+##         'it': 'italian',
+##         'la': 'latin',
+##         'nl': 'dutch',
+##         'pl': 'polish',
+##         'pt': 'portuguese',
+##         'ro': 'romanian',
+##         'ru': 'russian',
+##         'sk': 'slovak',
+##         'sr': 'serbian',
+##         'sv': 'swedish',
+##         'tr': 'turkish',
+##         'uk': 'ukrainian'
+##     }
+
+##     def __init__(self,lang):
+##         self.language = lang
+##         # pdflatex does not produce double quotes for ngerman in tt.
+##         self.double_quote_replacment = None
+##         if re.search('^de',self.language):
+##             #self.quotes = ("\"`", "\"'")
+##             self.quotes = ('{\\glqq}', '{\\grqq}')
+##             self.double_quote_replacment = "{\\dq}"
+##         else:
+##             self.quotes = ("``", "''")
+##         self.quote_index = 0
+
+##     def next_quote(self):
+##         q = self.quotes[self.quote_index]
+##         self.quote_index = (self.quote_index+1)%2
+##         return q
+
+##     def quote_quotes(self,text):
+##         t = None
+##         for part in text.split('"'):
+##             if t == None:
+##                 t = part
+##             else:
+##                 t += self.next_quote() + part
+##         return t
+
+##     def double_quotes_in_tt (self,text):
+##         if not self.double_quote_replacment:
+##             return text
+##         return text.replace('"', self.double_quote_replacment)
+
+##     def get_language(self):
+##         if self._ISO639_TO_BABEL.has_key(self.language):
+##             return self._ISO639_TO_BABEL[self.language]
+##         else:
+##             # support dialects.
+##             l = self.language.split("_")[0]
+##             if self._ISO639_TO_BABEL.has_key(l):
+##                 return self._ISO639_TO_BABEL[l]
+##         return None
+
+
+## latex_headings = {
+##         'optionlist_environment' : [
+##               '\\newcommand{\\optionlistlabel}[1]{\\bf #1 \\hfill}\n'
+##               '\\newenvironment{optionlist}[1]\n'
+##               '{\\begin{list}{}\n'
+##               '  {\\setlength{\\labelwidth}{#1}\n'
+##               '   \\setlength{\\rightmargin}{1cm}\n'
+##               '   \\setlength{\\leftmargin}{\\rightmargin}\n'
+##               '   \\addtolength{\\leftmargin}{\\labelwidth}\n'
+##               '   \\addtolength{\\leftmargin}{\\labelsep}\n'
+##               '   \\renewcommand{\\makelabel}{\\optionlistlabel}}\n'
+##               '}{\\end{list}}\n',
+##               ],
+##         'lineblock_environment' : [
+##             '\\newlength{\\lineblockindentation}\n'
+##             '\\setlength{\\lineblockindentation}{2.5em}\n'
+##             '\\newenvironment{lineblock}[1]\n'
+##             '{\\begin{list}{}\n'
+##             '  {\\setlength{\\partopsep}{\\parskip}\n'
+##             '   \\addtolength{\\partopsep}{\\baselineskip}\n'
+##             '   \\topsep0pt\\itemsep0.15\\baselineskip\\parsep0pt\n'
+##             '   \\leftmargin#1}\n'
+##             ' \\raggedright}\n'
+##             '{\\end{list}}\n'
+##             ],
+##         'footnote_floats' : [
+##             '% begin: floats for footnotes tweaking.\n',
+##             '\\setlength{\\floatsep}{0.5em}\n',
+##             '\\setlength{\\textfloatsep}{\\fill}\n',
+##             '\\addtolength{\\textfloatsep}{3em}\n',
+##             '\\renewcommand{\\textfraction}{0.5}\n',
+##             '\\renewcommand{\\topfraction}{0.5}\n',
+##             '\\renewcommand{\\bottomfraction}{0.5}\n',
+##             '\\setcounter{totalnumber}{50}\n',
+##             '\\setcounter{topnumber}{50}\n',
+##             '\\setcounter{bottomnumber}{50}\n',
+##             '% end floats for footnotes\n',
+##             ],
+##         'some_commands' : [
+##             '% some commands, that could be overwritten in the style file.\n'
+##             '\\newcommand{\\rubric}[1]'
+##             '{\\subsection*{~\\hfill {\\it #1} \\hfill ~}}\n'
+##             '\\newcommand{\\titlereference}[1]{\\textsl{#1}}\n'
+##             '% end of "some commands"\n',
+##             ]
+##         }
+
+#class DocumentClass:
+class ManualDocumentClass(latex2e.DocumentClass):
+    """Details of a LaTeX document class."""
+
+    # BUG: LaTeX has no deeper sections (actually paragrah is no
+    # section either).
+    # BUG: No support for unknown document classes.  Make 'article'
+    # default?
+    _class_sections = {
+        'book': ( 'chapter', 'section', 'subsection', 'subsubsection' ),
+        'scrbook': ( 'chapter', 'section', 'subsection', 'subsubsection' ),
+        'report': ( 'chapter', 'section', 'subsection', 'subsubsection' ),
+        'scrreprt': ( 'chapter', 'section', 'subsection', 'subsubsection' ),
+        'article': ( 'section', 'subsection', 'subsubsection' ),
+        'scrartcl': ( 'section', 'subsection', 'subsubsection' ),
+        'manual': ( 'chapter', 'section', 'subsection', 'subsubsection' ),
+        }
+    _deepest_section = 'subsubsection'
+
+##     def __init__(self, document_class):
+##         self.document_class = document_class
+
+    def section(self, level):
+        """ Return the section name at the given level for the specific
+            document class.
+
+            Level is 1,2,3..., as level 0 is the title."""
+        print "SECTION IN DOC: ", level, "---------------------------------------------------------"
+        sections = self._class_sections[self.document_class]
+        if level <= len(sections):
+            return sections[level-1]
+        else:
+            return self._deepest_section
+
+## class Table:
+##     """ Manage a table while traversing.
+##         Maybe change to a mixin defining the visit/departs, but then
+##         class Table internal variables are in the Translator.
+##     """
+##     def __init__(self,latex_type,table_style):
+##         self._latex_type = latex_type
+##         self._table_style = table_style
+##         self._open = 0
+##         # miscellaneous attributes
+##         self._attrs = {}
+##         self._col_width = []
+##         self._rowspan = []
+
+##     def open(self):
+##         self._open = 1
+##         self._col_specs = []
+##         self.caption = None
+##         self._attrs = {}
+##         self._in_head = 0 # maybe context with search
+##     def close(self):
+##         self._open = 0
+##         self._col_specs = None
+##         self.caption = None
+##         self._attrs = {}
+##     def is_open(self):
+##         return self._open
+##     def used_packages(self):
+##         if self._table_style == 'booktabs':
+##             return '\\usepackage{booktabs}\n'
+##         return ''
+##     def get_latex_type(self):
+##         return self._latex_type
+
+##     def set(self,attr,value):
+##         self._attrs[attr] = value
+##     def get(self,attr):
+##         if self._attrs.has_key(attr):
+##             return self._attrs[attr]
+##         return None
+##     def get_vertical_bar(self):
+##         if self._table_style == 'standard':
+##             return '|'
+##         return ''
+##     # horizontal lines are drawn below a row, because we.
+##     def get_opening(self):
+##         return '\\begin{%s}[c]' % self._latex_type
+##     def get_closing(self):
+##         line = ""
+##         if self._table_style == 'booktabs':
+##             line = '\\bottomrule\n'
+##         elif self._table_style == 'standard':
+##             lines = '\\hline\n'
+##         return '%s\\end{%s}' % (line,self._latex_type)
+
+##     def visit_colspec(self,node):
+##         self._col_specs.append(node)
+
+##     def get_colspecs(self):
+##         """
+##         Return column specification for longtable.
+
+##         Assumes reST line length being 80 characters.
+##         Table width is hairy.
+
+##         === ===
+##         ABC DEF
+##         === ===
+
+##         usually gets to narrow, therefore we add 1 (fiddlefactor).
+##         """
+##         width = 80
+
+##         total_width = 0.0
+##         # first see if we get too wide.
+##         for node in self._col_specs:
+##             colwidth = float(node['colwidth']+1) / width
+##             total_width += colwidth
+##         self._col_width = []
+##         self._rowspan = []
+##         # donot make it full linewidth
+##         factor = 0.93
+##         if total_width > 1.0:
+##             factor /= total_width
+##         bar = self.get_vertical_bar()
+##         latex_table_spec = ""
+##         for node in self._col_specs:
+##             colwidth = factor * float(node['colwidth']+1) / width
+##             self._col_width.append(colwidth+0.005)
+##             self._rowspan.append(0)
+##             latex_table_spec += "%sp{%.2f\\locallinewidth}" % (bar,colwidth+0.005)
+##         return latex_table_spec+bar
+
+##     def get_column_width(self):
+##         """ return columnwidth for current cell (not multicell)
+##         """
+##         return "%.2f\\locallinewidth" % self._col_width[self._cell_in_row-1]
+
+##     def visit_thead(self):
+##         self._in_thead = 1
+##         if self._table_style == 'standard':
+##             return ['\\hline\n']
+##         elif self._table_style == 'booktabs':
+##             return ['\\toprule\n']
+##         return []
+##     def depart_thead(self):
+##         a = []
+##         #if self._table_style == 'standard':
+##         #    a.append('\\hline\n')
+##         if self._table_style == 'booktabs':
+##             a.append('\\midrule\n')
+##         a.append('\\endhead\n')
+##         # for longtable one could add firsthead, foot and lastfoot
+##         self._in_thead = 0
+##         return a
+##     def visit_row(self):
+##         self._cell_in_row = 0
+##     def depart_row(self):
+##         res = [' \\\\\n']
+##         self._cell_in_row = None  # remove cell counter
+##         for i in range(len(self._rowspan)):
+##             if (self._rowspan[i]>0):
+##                 self._rowspan[i] -= 1
+
+##         if self._table_style == 'standard':
+##             rowspans = []
+##             for i in range(len(self._rowspan)):
+##                 if (self._rowspan[i]<=0):
+##                     rowspans.append(i+1)
+##             if len(rowspans)==len(self._rowspan):
+##                 res.append('\\hline\n')
+##             else:
+##                 cline = ''
+##                 rowspans.reverse()
+##                 # TODO merge clines
+##                 while 1:
+##                     try:
+##                         c_start = rowspans.pop()
+##                     except:
+##                         break
+##                     cline += '\\cline{%d-%d}\n' % (c_start,c_start)
+##                 res.append(cline)
+##         return res
+
+##     def set_rowspan(self,cell,value):
+##         try:
+##             self._rowspan[cell] = value
+##         except:
+##             pass
+##     def get_rowspan(self,cell):
+##         try:
+##             return self._rowspan[cell]
+##         except:
+##             return 0
+##     def get_entry_number(self):
+##         return self._cell_in_row
+##     def visit_entry(self):
+##         self._cell_in_row += 1
+
+
+#class LaTeXTranslator(nodes.NodeVisitor):
+class LaTeXManualTranslator(latex2e.LaTeXTranslator):
+    # When options are given to the documentclass, latex will pass them
+    # to other packages, as done with babel.
+    # Dummy settings might be taken from document settings
+
+    latex_head = '\\documentclass[%s]{%s}\n'
+    encoding = '\\usepackage[%s]{inputenc}\n'
+    linking = '\\usepackage[colorlinks=%s,linkcolor=%s,urlcolor=%s]{hyperref}\n'
+    stylesheet = '\\input{%s}\n'
+    # add a generated on day , machine by user using docutils version.
+    generator = '%% generator Docutils: http://docutils.sourceforge.net/\n'
+
+    # use latex tableofcontents or let docutils do it.
+    use_latex_toc = 0
+
+    # TODO: use mixins for different implementations.
+    # list environment for option-list. else tabularx
+    use_optionlist_for_option_list = 1
+    # list environment for docinfo. else tabularx
+    use_optionlist_for_docinfo = 0 # NOT YET IN USE
+
+    # Use compound enumerations (1.A.1.)
+    compound_enumerators = 0
+
+    # If using compound enumerations, include section information.
+    section_prefix_for_enumerators = 0
+
+    # This is the character that separates the section ("." subsection ...)
+    # prefix from the regular list enumerator.
+    section_enumerator_separator = '-'
+
+    # default link color
+    hyperlink_color = "blue"
+    no_sections = False
+
+    def __init__(self, document):
+        nodes.NodeVisitor.__init__(self, document)
+        self.settings = settings = document.settings
+        self.latex_encoding = self.to_latex_encoding(settings.output_encoding)
+        self.use_latex_toc = settings.use_latex_toc
+        self.use_latex_docinfo = settings.use_latex_docinfo
+        self.use_latex_footnotes = settings.use_latex_footnotes
+        self._use_latex_citations = settings.use_latex_citations
+        self.hyperlink_color = settings.hyperlink_color
+        self.compound_enumerators = settings.compound_enumerators
+        self.font_encoding = settings.font_encoding
+        self.section_prefix_for_enumerators = (
+            settings.section_prefix_for_enumerators)
+        self.section_enumerator_separator = (
+            settings.section_enumerator_separator.replace('_', '\\_'))
+        if self.hyperlink_color == '0':
+            self.hyperlink_color = 'black'
+            self.colorlinks = 'false'
+        else:
+            self.colorlinks = 'true'
+
+        # language: labels, bibliographic_fields, and author_separators.
+        # to allow writing labes for specific languages.
+        self.language = languages.get_language(settings.language_code)
+        self.babel = Babel(settings.language_code)
+        self.author_separator = self.language.author_separators[0]
+        self.d_options = self.settings.documentoptions
+        if self.babel.get_language():
+            self.d_options += ',%s' % \
+                    self.babel.get_language()
+
+        self.d_class = ManualDocumentClass(settings.documentclass)
+        # object for a table while proccessing.
+        self.active_table = Table('longtable',settings.table_style)
+
+        # HACK.  Should have more sophisticated typearea handling.
+        if settings.documentclass.find('scr') == -1:
+            self.typearea = '\\usepackage[DIV12]{typearea}\n'
+        else:
+            if self.d_options.find('DIV') == -1 and self.d_options.find('BCOR') == -1:
+                self.typearea = '\\typearea{12}\n'
+            else:
+                self.typearea = ''
+
+        if self.font_encoding == 'OT1':
+            fontenc_header = ''
+        elif self.font_encoding == '':
+            fontenc_header = '\\usepackage{ae}\n\\usepackage{aeguill}\n'
+        else:
+            fontenc_header = '\\usepackage[%s]{fontenc}\n' % (self.font_encoding,)
+        input_encoding = self.encoding % self.latex_encoding
+        if self.settings.graphicx_option == '':
+            self.graphicx_package = '\\usepackage{graphicx}\n'
+        elif self.settings.graphicx_option.lower() == 'auto':
+            self.graphicx_package = '\n'.join(
+                ('%Check if we are compiling under latex or pdflatex',
+                 '\\ifx\\pdftexversion\\undefined',
+                 '  \\usepackage{graphicx}',
+                 '\\else',
+                 '  \\usepackage[pdftex]{graphicx}',
+                 '\\fi\n'))
+        else:
+            self.graphicx_package = (
+                '\\usepackage[%s]{graphicx}\n' % self.settings.graphicx_option)
+
+        self.head_prefix = [
+              self.latex_head % (self.d_options,self.settings.documentclass),
+              '\\usepackage{babel}\n',     # language is in documents settings.
+              fontenc_header,
+              '\\usepackage{shortvrb}\n',  # allows verb in footnotes.
+              input_encoding,
+              # * tabularx: for docinfo, automatic width of columns, always on one page.
+              '\\usepackage{tabularx}\n',
+              '\\usepackage{longtable}\n',
+              self.active_table.used_packages(),
+              # possible other packages.
+              # * fancyhdr
+              # * ltxtable is a combination of tabularx and longtable (pagebreaks).
+              #   but ??
+              #
+              # extra space between text in tables and the line above them
+              '\\setlength{\\extrarowheight}{2pt}\n',
+              '\\usepackage{amsmath}\n',   # what fore amsmath.
+              self.graphicx_package,
+              '\\usepackage{color}\n',
+              '\\usepackage{multirow}\n',
+              '\\usepackage{ifthen}\n',   # before hyperref!
+              self.linking % (self.colorlinks, self.hyperlink_color, self.hyperlink_color),
+              self.typearea,
+              self.generator,
+              # latex lengths
+              '\\newlength{\\admonitionwidth}\n',
+              '\\setlength{\\admonitionwidth}{0.9\\textwidth}\n'
+              # width for docinfo tablewidth
+              '\\newlength{\\docinfowidth}\n',
+              '\\setlength{\\docinfowidth}{0.9\\textwidth}\n'
+              # linewidth of current environment, so tables are not wider
+              # than the sidebar: using locallinewidth seems to defer evaluation
+              # of linewidth, this is fixing it.
+              '\\newlength{\\locallinewidth}\n',
+              # will be set later.
+              ]
+        self.head_prefix.extend( latex_headings['optionlist_environment'] )
+        self.head_prefix.extend( latex_headings['lineblock_environment'] )
+        self.head_prefix.extend( latex_headings['footnote_floats'] )
+        self.head_prefix.extend( latex_headings['some_commands'] )
+        ## stylesheet is last: so it might be possible to overwrite defaults.
+        stylesheet = utils.get_stylesheet_reference(settings)
+        if stylesheet:
+            settings.record_dependencies.add(stylesheet)
+            self.head_prefix.append(self.stylesheet % (stylesheet))
+
+        if self.linking: # and maybe check for pdf
+            self.pdfinfo = [ ]
+            self.pdfauthor = None
+            # pdftitle, pdfsubject, pdfauthor, pdfkeywords, pdfcreator, pdfproducer
+        else:
+            self.pdfinfo = None
+        # NOTE: Latex wants a date and an author, rst puts this into
+        #   docinfo, so normally we donot want latex author/date handling.
+        # latex article has its own handling of date and author, deactivate.
+        # So we always emit \title{...} \author{...} \date{...}, even if the
+        # "..." are empty strings.
+        self.head = [ ]
+        # separate title, so we can appen subtitle.
+        self.title = ''
+        # if use_latex_docinfo: collects lists of author/organization/contact/address lines
+        self.author_stack = []
+        self.date = ''
+
+        self.body_prefix = ['\\raggedbottom\n']
+        self.body = []
+        self.body_suffix = ['\n']
+        self.section_level = 0
+        self.context = []
+        self.topic_classes = []
+        # column specification for tables
+        self.table_caption = None
+        
+        # Flags to encode
+        # ---------------
+        # verbatim: to tell encode not to encode.
+        self.verbatim = 0
+        # insert_newline: to tell encode to replace blanks by "~".
+        self.insert_none_breaking_blanks = 0
+        # insert_newline: to tell encode to add latex newline.
+        self.insert_newline = 0
+        # mbox_newline: to tell encode to add mbox and newline.
+        self.mbox_newline = 0
+
+        # enumeration is done by list environment.
+        self._enum_cnt = 0
+
+        # Stack of section counters so that we don't have to use_latex_toc.
+        # This will grow and shrink as processing occurs.
+        # Initialized for potential first-level sections.
+        self._section_number = [0]
+
+        # The current stack of enumerations so that we can expand
+        # them into a compound enumeration
+        self._enumeration_counters = []
+
+        self._bibitems = []
+
+        # docinfo.
+        self.docinfo = None
+        # inside literal block: no quote mangling.
+        self.literal_block = 0
+        self.literal_block_stack = []
+        self.literal = 0
+        # true when encoding in math mode
+        self.mathmode = 0
+
+        # ULIKRAM...
+        self.release = 'unreleased'
+
+
+##     def to_latex_encoding(self,docutils_encoding):
+##         """
+##         Translate docutils encoding name into latex's.
+
+##         Default fallback method is remove "-" and "_" chars from docutils_encoding.
+
+##         """
+##         tr = {  "iso-8859-1": "latin1",     # west european
+##                 "iso-8859-2": "latin2",     # east european
+##                 "iso-8859-3": "latin3",     # esperanto, maltese
+##                 "iso-8859-4": "latin4",     # north european,scandinavian, baltic
+##                 "iso-8859-5": "iso88595",   # cyrillic (ISO)
+##                 "iso-8859-9": "latin5",     # turkish
+##                 "iso-8859-15": "latin9",    # latin9, update to latin1.
+##                 "mac_cyrillic": "maccyr",   # cyrillic (on Mac)
+##                 "windows-1251": "cp1251",   # cyrillic (on Windows)
+##                 "koi8-r": "koi8-r",         # cyrillic (Russian)
+##                 "koi8-u": "koi8-u",         # cyrillic (Ukrainian)
+##                 "windows-1250": "cp1250",   #
+##                 "windows-1252": "cp1252",   #
+##                 "us-ascii": "ascii",        # ASCII (US)
+##                 # unmatched encodings
+##                 #"": "applemac",
+##                 #"": "ansinew",  # windows 3.1 ansi
+##                 #"": "ascii",    # ASCII encoding for the range 32--127.
+##                 #"": "cp437",    # dos latine us
+##                 #"": "cp850",    # dos latin 1
+##                 #"": "cp852",    # dos latin 2
+##                 #"": "decmulti",
+##                 #"": "latin10",
+##                 #"iso-8859-6": ""   # arabic
+##                 #"iso-8859-7": ""   # greek
+##                 #"iso-8859-8": ""   # hebrew
+##                 #"iso-8859-10": ""   # latin6, more complete iso-8859-4
+##              }
+##         if tr.has_key(docutils_encoding.lower()):
+##             return tr[docutils_encoding.lower()]
+##         return docutils_encoding.translate(string.maketrans("",""),"_-").lower()
+
+##     def language_label(self, docutil_label):
+##         return self.language.labels[docutil_label]
+
+##     latex_equivalents = {
+##         u'\u00A0' : '~',
+##         u'\u2013' : '{--}',
+##         u'\u2014' : '{---}',
+##         u'\u2018' : '`',
+##         u'\u2019' : '\'',
+##         u'\u201A' : ',',
+##         u'\u201C' : '``',
+##         u'\u201D' : '\'\'',
+##         u'\u201E' : ',,',
+##         u'\u2020' : '{\\dag}',
+##         u'\u2021' : '{\\ddag}',
+##         u'\u2026' : '{\\dots}',
+##         u'\u2122' : '{\\texttrademark}',
+##         u'\u21d4' : '{$\\Leftrightarrow$}',
+##     }
+
+##     def unicode_to_latex(self,text):
+##         # see LaTeX codec
+##         # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252124
+##         # Only some special chracters are translated, for documents with many
+##         # utf-8 chars one should use the LaTeX unicode package.
+##         for uchar in self.latex_equivalents.keys():
+##             text = text.replace(uchar,self.latex_equivalents[uchar])
+##         return text
+
+    def encode(self, text):
+        """
+        Encode special characters (``# $ % & ~ _ ^ \ { }``) in `text` & return
+        """
+        # Escaping with a backslash does not help with backslashes, ~ and ^.
+
+        #     < > are only available in math-mode or tt font. (really ?)
+        #     $ starts math- mode.
+        # AND quotes
+        if self.verbatim:
+            return text
+        # compile the regexps once. do it here so one can see them.
+        #
+        # first the braces.
+        if not self.__dict__.has_key('encode_re_braces'):
+            self.encode_re_braces = re.compile(r'([{}])')
+        text = self.encode_re_braces.sub(r'{\\\1}',text)
+        if not self.__dict__.has_key('encode_re_bslash'):
+            # find backslash: except in the form '{\{}' or '{\}}'.
+            self.encode_re_bslash = re.compile(r'(?<!{)(\\)(?![{}]})')
+        # then the backslash: except in the form from line above:
+        # either '{\{}' or '{\}}'.
+        text = self.encode_re_bslash.sub(r'{\\textbackslash}', text)
+
+        # then dollar
+        text = text.replace("$", '{\\$}')
+        if not ( self.literal_block or self.literal or self.mathmode ):
+            # the vertical bar: in mathmode |,\vert or \mid
+            #   in textmode \textbar
+            text = text.replace("|", '{\\textbar}')
+            text = text.replace("<", '{\\textless}')
+            text = text.replace(">", '{\\textgreater}')
+        # then
+        text = text.replace("&", '{\\&}')
+        # the ^:
+        # * verb|^| does not work in mbox.
+        # * mathmode has wedge. hat{~} would also work.
+        # text = text.replace("^", '{\\ensuremath{^\\wedge}}')
+        text = text.replace("^", '{\\textasciicircum}')
+        text = text.replace("%", '{\\%}')
+        text = text.replace("#", '{\\#}')
+        text = text.replace("~", '{\\textasciitilde}')
+        # Separate compound characters, e.g. "--" to "-{}-".  (The
+        # actual separation is done later; see below.)
+        separate_chars = '-'
+        if self.literal_block or self.literal:
+            # In monospace-font, we also separate ",,", "``" and "''"
+            # and some other characters which can't occur in
+            # non-literal text.
+            separate_chars += ',`\'"<>'
+            # pdflatex does not produce doublequotes for ngerman.
+            text = self.babel.double_quotes_in_tt(text)
+            if self.font_encoding == 'OT1':
+                # We're using OT1 font-encoding and have to replace
+                # underscore by underlined blank, because this has
+                # correct width.
+                text = text.replace('_', '{\\underline{ }}')
+                # And the tt-backslash doesn't work in OT1, so we use
+                # a mirrored slash.
+                text = text.replace('\\textbackslash', '\\reflectbox{/}')
+            else:
+                text = text.replace('_', '{\\_}')
+        else:
+            text = self.babel.quote_quotes(text)
+            text = text.replace("_", '{\\_}')
+        for char in separate_chars * 2:
+            # Do it twice ("* 2") becaues otherwise we would replace
+            # "---" by "-{}--".
+            text = text.replace(char + char, char + '{}' + char)
+        if self.insert_newline or self.literal_block:
+            # Insert a blank before the newline, to avoid
+            # ! LaTeX Error: There's no line here to end.
+            text = text.replace("\n", '~\\\\\n')
+        elif self.mbox_newline:
+            if self.literal_block:
+                closings = "}" * len(self.literal_block_stack)
+                openings = "".join(self.literal_block_stack)
+            else:
+                closings = ""
+                openings = ""
+            text = text.replace("\n", "%s}\\\\\n\\mbox{%s" % (closings,openings))
+        text = text.replace('[', '{[}').replace(']', '{]}')
+        if self.insert_none_breaking_blanks:
+            text = text.replace(' ', '~')
+        if self.latex_encoding != 'utf8':
+            text = self.unicode_to_latex(text)
+        return text
+
+##     def attval(self, text,
+##                whitespace=re.compile('[\n\r\t\v\f]')):
+##         """Cleanse, encode, and return attribute value text."""
+##         return self.encode(whitespace.sub(' ', text))
+
+##     def astext(self):
+##         if self.pdfinfo is not None:
+##             if self.pdfauthor:
+##                 self.pdfinfo.append('pdfauthor={%s}' % self.pdfauthor)
+##         if self.pdfinfo:
+##             pdfinfo = '\\hypersetup{\n' + ',\n'.join(self.pdfinfo) + '\n}\n'
+##         else:
+##             pdfinfo = ''
+##         head = '\\title{%s}\n\\author{%s}\n\\date{%s}\n\\release{%s}\n' % \
+##                (self.title,
+##                 ' \\and\n'.join(['~\\\\\n'.join(author_lines)
+##                                  for author_lines in self.author_stack]),
+##                 self.date, self.release)
+##         return ''.join(self.head_prefix + [head] + self.head + [pdfinfo]
+##                         + self.body_prefix  + self.body + self.body_suffix)
+
+##     def visit_Text(self, node):
+##         self.body.append(self.encode(node.astext()))
+
+##     def depart_Text(self, node):
+##         pass
+
+##     def visit_address(self, node):
+##         self.visit_docinfo_item(node, 'address')
+
+##     def depart_address(self, node):
+##         self.depart_docinfo_item(node)
+
+    def visit_admonition(self, node, name=''):
+        self.body.append('\\begin{center}\\begin{sffamily}\n')
+        self.body.append('\\fbox{\\parbox{\\admonitionwidth}{\n')
+        if name:
+            self.body.append('\\textbf{\\large '+ self.language.labels[name] + '}\n');
+        self.body.append('\\vspace{2mm}\n')
+
+
+    def depart_admonition(self, node=None):
+        self.body.append('}}\n') # end parbox fbox
+        self.body.append('\\end{sffamily}\n\\end{center}\n');
+
+##     def visit_attention(self, node):
+##         self.visit_admonition(node, 'attention')
+
+##     def depart_attention(self, node):
+##         self.depart_admonition()
+
+##     def visit_release(self, node):
+##         self.visit_docinfo_item(node, 'release')
+
+##     def depart_release(self, node):
+##         self.depart_docinfo_item(node)
+
+##     def visit_author(self, node):
+##         self.visit_docinfo_item(node, 'author')
+
+##     def depart_author(self, node):
+##         self.depart_docinfo_item(node)
+
+##     def visit_authors(self, node):
+##         # not used: visit_author is called anyway for each author.
+##         pass
+
+##     def depart_authors(self, node):
+##         pass
+
+##     def visit_block_quote(self, node):
+##         self.body.append( '\\begin{quote}\n')
+
+##     def depart_block_quote(self, node):
+##         self.body.append( '\\end{quote}\n')
+
+    def visit_bullet_list(self, node):
+        if 'contents' in self.topic_classes:
+            if not self.use_latex_toc:
+                self.body.append( '\\begin{list}{}{}\n' )
+        else:
+            self.body.append( '\\begin{itemize}\n' )
+
+    def depart_bullet_list(self, node):
+        if 'contents' in self.topic_classes:
+            if not self.use_latex_toc:
+                self.body.append( '\\end{list}\n' )
+        else:
+            self.body.append( '\\end{itemize}\n' )
+
+    # Imperfect superscript/subscript handling: mathmode italicizes
+    # all letters by default.
+    def visit_superscript(self, node):
+        self.body.append('$^{')
+        self.mathmode = 1
+
+    def depart_superscript(self, node):
+        self.body.append('}$')
+        self.mathmode = 0
+
+    def visit_subscript(self, node):
+        self.body.append('$_{')
+        self.mathmode = 1
+
+    def depart_subscript(self, node):
+        self.body.append('}$')
+        self.mathmode = 0
+
+    def visit_caption(self, node):
+        self.body.append( '\\caption{' )
+
+    def depart_caption(self, node):
+        self.body.append('}')
+
+    def visit_caution(self, node):
+        self.visit_admonition(node, 'caution')
+
+    def depart_caution(self, node):
+        self.depart_admonition()
+
+    def visit_title_reference(self, node):
+        self.body.append( '\\titlereference{' )
+
+    def depart_title_reference(self, node):
+        self.body.append( '}' )
+
+    def visit_citation(self, node):
+        # TODO maybe use cite bibitems
+        if self._use_latex_citations:
+            self.context.append(len(self.body))
+        else:
+            self.body.append('\\begin{figure}[b]')
+            for id in node['ids']:
+                self.body.append('\\hypertarget{%s}' % id)
+
+    def depart_citation(self, node):
+        if self._use_latex_citations:
+            size = self.context.pop()
+            label = self.body[size]
+            text = ''.join(self.body[size+1:])
+            del self.body[size:]
+            self._bibitems.append([label, text])
+        else:
+            self.body.append('\\end{figure}\n')
+
+    def visit_citation_reference(self, node):
+        if self._use_latex_citations:
+            self.body.append('\\cite{')
+        else:
+            href = ''
+            if node.has_key('refid'):
+                href = node['refid']
+            elif node.has_key('refname'):
+                href = self.document.nameids[node['refname']]
+            self.body.append('[\\hyperlink{%s}{' % href)
+
+    def depart_citation_reference(self, node):
+        if self._use_latex_citations:
+            self.body.append('}')
+        else:
+            self.body.append('}]')
+
+    def visit_classifier(self, node):
+        self.body.append( '(\\textbf{' )
+
+    def depart_classifier(self, node):
+        self.body.append( '})\n' )
+
+    def visit_colspec(self, node):
+        self.active_table.visit_colspec(node)
+
+    def depart_colspec(self, node):
+        pass
+
+    def visit_comment(self, node):
+        # Escape end of line by a new comment start in comment text.
+        self.body.append('%% %s \n' % node.astext().replace('\n', '\n% '))
+        raise nodes.SkipNode
+
+    def visit_compound(self, node):
+        pass
+
+    def depart_compound(self, node):
+        pass
+
+    def visit_contact(self, node):
+        self.visit_docinfo_item(node, 'contact')
+
+    def depart_contact(self, node):
+        self.depart_docinfo_item(node)
+
+    def visit_container(self, node):
+        pass
+
+    def depart_container(self, node):
+        pass
+
+    def visit_copyright(self, node):
+        self.visit_docinfo_item(node, 'copyright')
+
+    def depart_copyright(self, node):
+        self.depart_docinfo_item(node)
+
+    def visit_danger(self, node):
+        self.visit_admonition(node, 'danger')
+
+    def depart_danger(self, node):
+        self.depart_admonition()
+
+    def visit_date(self, node):
+        self.visit_docinfo_item(node, 'date')
+
+    def depart_date(self, node):
+        self.depart_docinfo_item(node)
+
+    def visit_decoration(self, node):
+        pass
+
+    def depart_decoration(self, node):
+        pass
+
+    def visit_definition(self, node):
+        self.body.append('%[visit_definition]\n')
+
+    def depart_definition(self, node):
+        self.body.append('\n')
+        self.body.append('%[depart_definition]\n')
+
+    def visit_definition_list(self, node):
+        self.body.append( '\\begin{description}\n' )
+
+    def depart_definition_list(self, node):
+        self.body.append( '\\end{description}\n' )
+
+    def visit_definition_list_item(self, node):
+        print "DEF_LIST_ITEM: ", node, dir(node)
+        self.body.append('%[visit_definition_list_item]\n')
+
+    def depart_definition_list_item(self, node):
+        self.body.append('%[depart_definition_list_item]\n')
+
+    def visit_description(self, node):
+        if self.use_optionlist_for_option_list:
+            self.body.append( ' ' )
+        else:
+            self.body.append( ' & ' )
+
+    def depart_description(self, node):
+        pass
+
+    def visit_docinfo(self, node):
+        self.docinfo = []
+        self.docinfo.append('%' + '_'*75 + '\n')
+        self.docinfo.append('\\begin{center}\n')
+        self.docinfo.append('\\begin{tabularx}{\\docinfowidth}{lX}\n')
+
+    def depart_docinfo(self, node):
+        self.docinfo.append('\\end{tabularx}\n')
+        self.docinfo.append('\\end{center}\n')
+        self.body = self.docinfo + self.body
+        # clear docinfo, so field names are no longer appended.
+        self.docinfo = None
+
+    def visit_docinfo_item(self, node, name):
+        if name == 'author':
+            if not self.pdfinfo == None:
+                if not self.pdfauthor:
+                    self.pdfauthor = self.attval(node.astext())
+                else:
+                    self.pdfauthor += self.author_separator + self.attval(node.astext())
+        if self.use_latex_docinfo:
+            if name in ('author', 'organization', 'contact', 'address'):
+                # We attach these to the last author.  If any of them precedes
+                # the first author, put them in a separate "author" group (for
+                # no better semantics).
+                if name == 'author' or not self.author_stack:
+                    self.author_stack.append([])
+                if name == 'address':   # newlines are meaningful
+                    self.insert_newline = 1
+                    text = self.encode(node.astext())
+                    self.insert_newline = 0
+                else:
+                    text = self.attval(node.astext())
+                self.author_stack[-1].append(text)
+                raise nodes.SkipNode
+            elif name == 'date':
+                self.date = self.attval(node.astext())
+                raise nodes.SkipNode
+        self.docinfo.append('\\textbf{%s}: &\n\t' % self.language_label(name))
+        if name == 'address':
+            self.insert_newline = 1
+            self.docinfo.append('{\\raggedright\n')
+            self.context.append(' } \\\\\n')
+        else:
+            self.context.append(' \\\\\n')
+        self.context.append(self.docinfo)
+        self.context.append(len(self.body))
+
+    def depart_docinfo_item(self, node):
+        size = self.context.pop()
+        dest = self.context.pop()
+        tail = self.context.pop()
+        tail = self.body[size:] + [tail]
+        del self.body[size:]
+        dest.extend(tail)
+        # for address we did set insert_newline
+        self.insert_newline = 0
+
+    def visit_doctest_block(self, node):
+        self.body.append( '\\begin{verbatim}' )
+        self.verbatim = 1
+
+    def depart_doctest_block(self, node):
+        self.body.append( '\\end{verbatim}\n' )
+        self.verbatim = 0
+
+    def visit_document(self, node):
+        self.body_prefix.append('\\begin{document}\n')
+        # titled document?
+        if self.use_latex_docinfo or len(node) and isinstance(node[0], nodes.title):
+            self.body_prefix.append('\\maketitle\n\n')
+            # alternative use titlepage environment.
+            # \begin{titlepage}
+        self.body.append('\n\\setlength{\\locallinewidth}{\\linewidth}\n')
+
+    def depart_document(self, node):
+        # TODO insertion point of bibliography should none automatic.
+        if self._use_latex_citations and len(self._bibitems)>0:
+            widest_label = ""
+            for bi in self._bibitems:
+                if len(widest_label)<len(bi[0]):
+                    widest_label = bi[0]
+            self.body.append('\n\\begin{thebibliography}{%s}\n'%widest_label)
+            for bi in self._bibitems:
+                # cite_key: underscores must not be escaped
+                cite_key = bi[0].replace(r"{\_}","_")
+                self.body.append('\\bibitem[%s]{%s}{%s}\n' % (bi[0], cite_key, bi[1]))
+            self.body.append('\\end{thebibliography}\n')
+
+        self.body_suffix.append('\\end{document}\n')
+
+    def visit_emphasis(self, node):
+        self.body.append('\\emph{')
+        self.literal_block_stack.append('\\emph{')
+
+    def depart_emphasis(self, node):
+        self.body.append('}')
+        self.literal_block_stack.pop()
+
+    def visit_entry(self, node):
+        self.active_table.visit_entry()
+        # cell separation
+        if self.active_table.get_entry_number() == 1:
+            # if the firstrow is a multirow, this actually is the second row.
+            # this gets hairy if rowspans follow each other.
+            if self.active_table.get_rowspan(0):
+                count = 0
+                while self.active_table.get_rowspan(count):
+                    count += 1
+                    self.body.append(' & ')
+                self.active_table.visit_entry() # increment cell count
+        else:
+            self.body.append(' & ')
+
+        # multi{row,column}
+        # IN WORK BUG TODO HACK continues here
+        # multirow in LaTeX simply will enlarge the cell over several rows
+        # (the following n if n is positive, the former if negative).
+        if node.has_key('morerows') and node.has_key('morecols'):
+            raise NotImplementedError('Cells that '
+            'span multiple rows *and* columns are not supported, sorry.')
+        if node.has_key('morerows'):
+            count = node['morerows'] + 1
+            self.active_table.set_rowspan(self.active_table.get_entry_number()-1,count)
+            self.body.append('\\multirow{%d}{%s}{' % \
+                    (count,self.active_table.get_column_width()))
+            self.context.append('}')
+            # BUG following rows must have empty cells.
+        elif node.has_key('morecols'):
+            # the vertical bar before column is missing if it is the first column.
+            # the one after always.
+            if self.active_table.get_entry_number() == 1:
+                bar1 = self.active_table.get_vertical_bar()
+            else:
+                bar1 = ''
+            count = node['morecols'] + 1
+            self.body.append('\\multicolumn{%d}{%sl%s}{' % \
+                    (count, bar1, self.active_table.get_vertical_bar()))
+            self.context.append('}')
+        else:
+            self.context.append('')
+
+        # header / not header
+        if isinstance(node.parent.parent, nodes.thead):
+            self.body.append('\\textbf{')
+            self.context.append('}')
+        else:
+            self.context.append('')
+
+    def depart_entry(self, node):
+        self.body.append(self.context.pop()) # header / not header
+        self.body.append(self.context.pop()) # multirow/column
+        # if following row is spanned from above.
+        if self.active_table.get_rowspan(self.active_table.get_entry_number()):
+           self.body.append(' & ')
+           self.active_table.visit_entry() # increment cell count
+
+    def visit_row(self, node):
+        self.active_table.visit_row()
+
+    def depart_row(self, node):
+        self.body.extend(self.active_table.depart_row())
+
+    def visit_enumerated_list(self, node):
+        self.body.append('\\begin{enumerate}\n')
+        return
+        # We create our own enumeration list environment.
+        # This allows to set the style and starting value
+        # and unlimited nesting.
+        self._enum_cnt += 1
+
+        enum_style = {'arabic':'arabic',
+                'loweralpha':'alph',
+                'upperalpha':'Alph',
+                'lowerroman':'roman',
+                'upperroman':'Roman' }
+        enum_suffix = ""
+        if node.has_key('suffix'):
+            enum_suffix = node['suffix']
+        enum_prefix = ""
+        if node.has_key('prefix'):
+            enum_prefix = node['prefix']
+        if self.compound_enumerators:
+            pref = ""
+            if self.section_prefix_for_enumerators and self.section_level:
+                for i in range(self.section_level):
+                    pref += '%d.' % self._section_number[i]
+                pref = pref[:-1] + self.section_enumerator_separator
+                enum_prefix += pref
+            for counter in self._enumeration_counters:
+                enum_prefix += counter + '.'
+        enum_type = "arabic"
+        if node.has_key('enumtype'):
+            enum_type = node['enumtype']
+        if enum_style.has_key(enum_type):
+            enum_type = enum_style[enum_type]
+        counter_name = "listcnt%d" % self._enum_cnt;
+        self._enumeration_counters.append("\\%s{%s}" % (enum_type,counter_name))
+        self.body.append('\\newcounter{%s}\n' % counter_name)
+        self.body.append('\\begin{list}{%s\\%s{%s}%s}\n' % \
+            (enum_prefix,enum_type,counter_name,enum_suffix))
+        self.body.append('{\n')
+        self.body.append('\\usecounter{%s}\n' % counter_name)
+        # set start after usecounter, because it initializes to zero.
+        if node.has_key('start'):
+            self.body.append('\\addtocounter{%s}{%d}\n' \
+                    % (counter_name,node['start']-1))
+        ## set rightmargin equal to leftmargin
+        self.body.append('\\setlength{\\rightmargin}{\\leftmargin}\n')
+        self.body.append('}\n')
+
+    def depart_enumerated_list(self, node):
+        self.body.append('\\end{enumerate}\n')
+        #self.body.append('\\end{list}\n')
+        #self._enumeration_counters.pop()
+
+    def visit_error(self, node):
+        self.visit_admonition(node, 'error')
+
+    def depart_error(self, node):
+        self.depart_admonition()
+
+    def visit_field(self, node):
+        # real output is done in siblings: _argument, _body, _name
+        pass
+
+    def depart_field(self, node):
+        self.body.append('\n')
+        ##self.body.append('%[depart_field]\n')
+
+    def visit_field_argument(self, node):
+        self.body.append('%[visit_field_argument]\n')
+
+    def depart_field_argument(self, node):
+        self.body.append('%[depart_field_argument]\n')
+
+    def visit_field_body(self, node):
+        # BUG by attach as text we loose references.
+        if self.docinfo:
+            self.docinfo.append('%s \\\\\n' % self.encode(node.astext()))
+            raise nodes.SkipNode
+        # BUG: what happens if not docinfo
+
+    def depart_field_body(self, node):
+        self.body.append( '\n' )
+
+    def visit_field_list(self, node):
+        if not self.docinfo:
+            self.body.append('\\begin{quote}\n')
+            self.body.append('\\begin{description}\n')
+
+    def depart_field_list(self, node):
+        if not self.docinfo:
+            self.body.append('\\end{description}\n')
+            self.body.append('\\end{quote}\n')
+
+    def visit_field_name(self, node):
+        # BUG this duplicates docinfo_item
+        if self.docinfo:
+            self.docinfo.append('\\textbf{%s}: &\n\t' % self.encode(node.astext()))
+            raise nodes.SkipNode
+        else:
+            self.body.append('\\item [')
+
+    def depart_field_name(self, node):
+        if not self.docinfo:
+            self.body.append(':]')
+
+    def visit_figure(self, node):
+        if not node.attributes.has_key('align'):
+            align = 'center'
+        else:
+            align = 'flush'+node.attributes['align']
+        self.body.append( '\\begin{figure}[htbp]\\begin{%s}\n' % align )
+        self.context.append( '\\end{%s}\\end{figure}\n' % align )
+
+    def depart_figure(self, node):
+        self.body.append( self.context.pop() )
+
+    def visit_footer(self, node):
+        self.context.append(len(self.body))
+
+    def depart_footer(self, node):
+        start = self.context.pop()
+        footer = (['\n\\begin{center}\small\n']
+                  + self.body[start:] + ['\n\\end{center}\n'])
+        self.body_suffix[:0] = footer
+        del self.body[start:]
+
+    def visit_footnote(self, node):
+        if self.use_latex_footnotes:
+            num,text = node.astext().split(None,1)
+            num = self.encode(num.strip())
+            self.body.append('\\footnotetext['+num+']')
+            self.body.append('{')
+        else:
+            self.body.append('\\begin{figure}[b]')
+            for id in node['ids']:
+                self.body.append('\\hypertarget{%s}' % id)
+
+    def depart_footnote(self, node):
+        if self.use_latex_footnotes:
+            self.body.append('}\n')
+        else:
+            self.body.append('\\end{figure}\n')
+
+    def visit_footnote_reference(self, node):
+        if self.use_latex_footnotes:
+            self.body.append("\\footnotemark["+self.encode(node.astext())+"]")
+            raise nodes.SkipNode
+        href = ''
+        if node.has_key('refid'):
+            href = node['refid']
+        elif node.has_key('refname'):
+            href = self.document.nameids[node['refname']]
+        format = self.settings.footnote_references
+        if format == 'brackets':
+            suffix = '['
+            self.context.append(']')
+        elif format == 'superscript':
+            suffix = '\\raisebox{.5em}[0em]{\\scriptsize'
+            self.context.append('}')
+        else:                           # shouldn't happen
+            raise AssertionError('Illegal footnote reference format.')
+        self.body.append('%s\\hyperlink{%s}{' % (suffix,href))
+
+    def depart_footnote_reference(self, node):
+        if self.use_latex_footnotes:
+            return
+        self.body.append('}%s' % self.context.pop())
+
+    # footnote/citation label
+    def label_delim(self, node, bracket, superscript):
+        if isinstance(node.parent, nodes.footnote):
+            if self.use_latex_footnotes:
+                raise nodes.SkipNode
+            if self.settings.footnote_references == 'brackets':
+                self.body.append(bracket)
+            else:
+                self.body.append(superscript)
+        else:
+            assert isinstance(node.parent, nodes.citation)
+            if not self._use_latex_citations:
+                self.body.append(bracket)
+
+    def visit_label(self, node):
+        self.label_delim(node, '[', '$^{')
+
+    def depart_label(self, node):
+        self.label_delim(node, ']', '}$')
+
+    # elements generated by the framework e.g. section numbers.
+    def visit_generated(self, node):
+        print "GENERATED: ", node
+        pass
+
+    def depart_generated(self, node):
+        pass
+
+    def visit_header(self, node):
+        self.context.append(len(self.body))
+
+    def depart_header(self, node):
+        start = self.context.pop()
+        self.body_prefix.append('\n\\verb|begin_header|\n')
+        self.body_prefix.extend(self.body[start:])
+        self.body_prefix.append('\n\\verb|end_header|\n')
+        del self.body[start:]
+
+    def visit_hint(self, node):
+        self.visit_admonition(node, 'hint')
+
+    def depart_hint(self, node):
+        self.depart_admonition()
+
+    def visit_image(self, node):
+        attrs = node.attributes
+        # Add image URI to dependency list, assuming that it's
+        # referring to a local file.
+        self.settings.record_dependencies.add(attrs['uri'])
+        pre = []                        # in reverse order
+        post = []
+        include_graphics_options = ""
+        inline = isinstance(node.parent, nodes.TextElement)
+        if attrs.has_key('scale'):
+            # Could also be done with ``scale`` option to
+            # ``\includegraphics``; doing it this way for consistency.
+            pre.append('\\scalebox{%f}{' % (attrs['scale'] / 100.0,))
+            post.append('}')
+        if attrs.has_key('width'):
+            include_graphics_options = '[width=%s]' % attrs['width']
+        if attrs.has_key('align'):
+            align_prepost = {
+                # By default latex aligns the top of an image.
+                (1, 'top'): ('', ''),
+                (1, 'middle'): ('\\raisebox{-0.5\\height}{', '}'),
+                (1, 'bottom'): ('\\raisebox{-\\height}{', '}'),
+                (0, 'center'): ('{\\hfill', '\\hfill}'),
+                # These 2 don't exactly do the right thing.  The image should
+                # be floated alongside the paragraph.  See
+                # http://www.w3.org/TR/html4/struct/objects.html#adef-align-IMG
+                (0, 'left'): ('{', '\\hfill}'),
+                (0, 'right'): ('{\\hfill', '}'),}
+            try:
+                pre.append(align_prepost[inline, attrs['align']][0])
+                post.append(align_prepost[inline, attrs['align']][1])
+            except KeyError:
+                pass                    # XXX complain here?
+        if not inline:
+            pre.append('\n')
+            post.append('\n')
+        pre.reverse()
+        self.body.extend( pre )
+        self.body.append( '\\includegraphics%s{%s}' % (
+                include_graphics_options, attrs['uri'] ) )
+        self.body.extend( post )
+
+    def depart_image(self, node):
+        pass
+
+    def visit_important(self, node):
+        self.visit_admonition(node, 'important')
+
+    def depart_important(self, node):
+        self.depart_admonition()
+
+    def visit_interpreted(self, node):
+        # @@@ Incomplete, pending a proper implementation on the
+        # Parser/Reader end.
+        self.visit_literal(node)
+
+    def depart_interpreted(self, node):
+        self.depart_literal(node)
+
+    def visit_legend(self, node):
+        self.body.append('{\\small ')
+
+    def depart_legend(self, node):
+        self.body.append('}')
+
+    def visit_line(self, node):
+        self.body.append('\item[] ')
+
+    def depart_line(self, node):
+        self.body.append('\n')
+
+    def visit_line_block(self, node):
+        if isinstance(node.parent, nodes.line_block):
+            self.body.append('\\item[] \n'
+                             '\\begin{lineblock}{\\lineblockindentation}\n')
+        else:
+            self.body.append('\n\\begin{lineblock}{0em}\n')
+
+    def depart_line_block(self, node):
+        self.body.append('\\end{lineblock}\n')
+
+    def visit_list_item(self, node):
+        # Append "{}" in case the next character is "[", which would break
+        # LaTeX's list environment (no numbering and the "[" is not printed).
+        self.body.append('\\item { ')
+        #self.body.append('\\item {} ')
+
+    def depart_list_item(self, node):
+        self.body.append('}\n\n')
+
+    def visit_literal(self, node):
+        print "LITERAL: ", node
+        self.literal = 1
+        self.body.append('\\texttt{')
+
+    def depart_literal(self, node):
+        self.body.append('}')
+        self.literal = 0
+
+    def visit_literal_block(self, node):
+        """
+        Render a literal-block.
+
+        Literal blocks are used for "::"-prefixed literal-indented
+        blocks of text, where the inline markup is not recognized,
+        but are also the product of the parsed-literal directive,
+        where the markup is respected.
+        """
+        # In both cases, we want to use a typewriter/monospaced typeface.
+        # For "real" literal-blocks, we can use \verbatim, while for all
+        # the others we must use \mbox.
+        #
+        # We can distinguish between the two kinds by the number of
+        # siblings the compose this node: if it is composed by a
+        # single element, it's surely is either a real one, otherwise
+        # it's a parsed-literal that does not contain any markup.
+        #
+        if (self.settings.use_verbatim_when_possible and (len(node) == 1)
+              # in case of a parsed-literal containing just a "**bold**" word:
+              and isinstance(node[0], nodes.Text)):
+            self.verbatim = 1
+            self.body.append('\\begin{quote}\\begin{verbatim}\n')
+        else:
+            self.literal_block = 1
+            self.insert_none_breaking_blanks = 1
+            if self.active_table.is_open():
+                self.body.append('\n{\\ttfamily \\raggedright \\noindent\n')
+            else:
+                # no quote inside tables, to avoid vertical sppace between
+                # table border and literal block.
+                # BUG: fails if normal text preceeds the literal block.
+                self.body.append('\\begin{quote}')
+                self.body.append('{\\ttfamily \\raggedright \\noindent\n')
+            # * obey..: is from julien and never worked for me (grubert).
+            #   self.body.append('{\\obeylines\\obeyspaces\\ttfamily\n')
+
+    def depart_literal_block(self, node):
+        if self.verbatim:
+            self.body.append('\n\\end{verbatim}\\end{quote}\n')
+            self.verbatim = 0
+        else:
+            if self.active_table.is_open():
+                self.body.append('\n}\n')
+            else:
+                self.body.append('\n')
+                self.body.append('}\\end{quote}\n')
+            self.insert_none_breaking_blanks = 0
+            self.literal_block = 0
+            # obey end: self.body.append('}\n')
+
+    def visit_meta(self, node):
+        self.body.append('[visit_meta]\n')
+        # BUG maybe set keywords for pdf
+        ##self.head.append(self.starttag(node, 'meta', **node.attributes))
+
+    def depart_meta(self, node):
+        self.body.append('[depart_meta]\n')
+
+    def visit_note(self, node):
+        self.visit_admonition(node, 'note')
+
+    def depart_note(self, node):
+        self.depart_admonition()
+
+    def visit_option(self, node):
+        if self.context[-1]:
+            # this is not the first option
+            self.body.append(', ')
+
+    def depart_option(self, node):
+        # flag tha the first option is done.
+        self.context[-1] += 1
+
+    def visit_option_argument(self, node):
+        """The delimiter betweeen an option and its argument."""
+        self.body.append(node.get('delimiter', ' '))
+
+    def depart_option_argument(self, node):
+        pass
+
+    def visit_option_group(self, node):
+        if self.use_optionlist_for_option_list:
+            self.body.append('\\item [')
+        else:
+            if len(node.astext()) > 14:
+                self.body.append('\\multicolumn{2}{l}{')
+                self.context.append('} \\\\\n  ')
+            else:
+                self.context.append('')
+            self.body.append('\\texttt{')
+        # flag for first option
+        self.context.append(0)
+
+    def depart_option_group(self, node):
+        self.context.pop() # the flag
+        if self.use_optionlist_for_option_list:
+            self.body.append('] ')
+        else:
+            self.body.append('}')
+            self.body.append(self.context.pop())
+
+    def visit_option_list(self, node):
+        self.body.append('% [option list]\n')
+        if self.use_optionlist_for_option_list:
+            self.body.append('\\begin{optionlist}{3cm}\n')
+        else:
+            self.body.append('\\begin{center}\n')
+            # BUG: use admwidth or make it relative to textwidth ?
+            self.body.append('\\begin{tabularx}{.9\\linewidth}{lX}\n')
+
+    def depart_option_list(self, node):
+        if self.use_optionlist_for_option_list:
+            self.body.append('\\end{optionlist}\n')
+        else:
+            self.body.append('\\end{tabularx}\n')
+            self.body.append('\\end{center}\n')
+
+    def visit_option_list_item(self, node):
+        pass
+
+    def depart_option_list_item(self, node):
+        if not self.use_optionlist_for_option_list:
+            self.body.append('\\\\\n')
+
+    def visit_option_string(self, node):
+        ##self.body.append(self.starttag(node, 'span', '', CLASS='option'))
+        pass
+
+    def depart_option_string(self, node):
+        ##self.body.append('</span>')
+        pass
+
+    def visit_organization(self, node):
+        self.visit_docinfo_item(node, 'organization')
+
+    def depart_organization(self, node):
+        self.depart_docinfo_item(node)
+
+    def visit_paragraph(self, node):
+        index = node.parent.index(node)
+        if not ('contents' in self.topic_classes or
+                (isinstance(node.parent, nodes.compound) and
+                 index > 0 and
+                 not isinstance(node.parent[index - 1], nodes.paragraph) and
+                 not isinstance(node.parent[index - 1], nodes.compound))):
+            self.body.append('\n')
+
+    def depart_paragraph(self, node):
+        self.body.append('\n')
+
+    def visit_problematic(self, node):
+        self.body.append('{\\color{red}\\bfseries{}')
+
+    def depart_problematic(self, node):
+        self.body.append('}')
+
+    def visit_raw(self, node):
+        if 'latex' in node.get('format', '').split():
+            self.body.append(node.astext())
+        raise nodes.SkipNode
+
+    def visit_reference(self, node):
+        # BUG: hash_char "#" is trouble some in LaTeX.
+        # mbox and other environment do not like the '#'.
+        hash_char = '\\#'
+        if node.has_key('refuri'):
+            href = node['refuri'].replace('#',hash_char)
+        elif node.has_key('refid'):
+            href = hash_char + node['refid']
+        elif node.has_key('refname'):
+            href = hash_char + self.document.nameids[node['refname']]
+        else:
+            raise AssertionError('Unknown reference.')
+        self.body.append('\\href{%s}{' % href)
+
+    def depart_reference(self, node):
+        self.body.append('}')
+
+    def visit_revision(self, node):
+        self.visit_docinfo_item(node, 'revision')
+
+    def depart_revision(self, node):
+        self.depart_docinfo_item(node)
+
+    def visit_section(self, node):
+        self.section_level += 1
+        # Initialize counter for potential subsections:
+        self._section_number.append(0)
+        # Counter for this section's level (initialized by parent section):
+        self._section_number[self.section_level - 1] += 1
+
+    def depart_section(self, node):
+        # Remove counter for potential subsections:
+        self._section_number.pop()
+        self.section_level -= 1
+
+    def visit_sidebar(self, node):
+        # BUG:  this is just a hack to make sidebars render something
+        self.body.append('\n\\setlength{\\locallinewidth}{0.9\\admonitionwidth}\n')
+        self.body.append('\\begin{center}\\begin{sffamily}\n')
+        self.body.append('\\fbox{\\colorbox[gray]{0.80}{\\parbox{\\admonitionwidth}{\n')
+
+    def depart_sidebar(self, node):
+        self.body.append('}}}\n') # end parbox colorbox fbox
+        self.body.append('\\end{sffamily}\n\\end{center}\n');
+        self.body.append('\n\\setlength{\\locallinewidth}{\\linewidth}\n')
+
+
+    attribution_formats = {'dash': ('---', ''),
+                           'parentheses': ('(', ')'),
+                           'parens': ('(', ')'),
+                           'none': ('', '')}
+
+    def visit_attribution(self, node):
+        prefix, suffix = self.attribution_formats[self.settings.attribution]
+        self.body.append('\n\\begin{flushright}\n')
+        self.body.append(prefix)
+        self.context.append(suffix)
+
+    def depart_attribution(self, node):
+        self.body.append(self.context.pop() + '\n')
+        self.body.append('\\end{flushright}\n')
+
+    def visit_status(self, node):
+        self.visit_docinfo_item(node, 'status')
+
+    def depart_status(self, node):
+        self.depart_docinfo_item(node)
+
+    def visit_strong(self, node):
+        self.body.append('\\textbf{')
+        self.literal_block_stack.append('\\textbf{')
+
+    def depart_strong(self, node):
+        self.body.append('}')
+        self.literal_block_stack.pop()
+
+    def visit_substitution_definition(self, node):
+        raise nodes.SkipNode
+
+    def visit_substitution_reference(self, node):
+        self.unimplemented_visit(node)
+
+    def visit_subtitle(self, node):
+        if isinstance(node.parent, nodes.sidebar):
+            self.body.append('~\\\\\n\\textbf{')
+            self.context.append('}\n\\smallskip\n')
+        elif isinstance(node.parent, nodes.document):
+            self.title = self.title + \
+                '\\\\\n\\large{%s}\n' % self.encode(node.astext())
+            raise nodes.SkipNode
+        elif isinstance(node.parent, nodes.section):
+            self.body.append('\\textbf{')
+            self.context.append('}\\vspace{0.2cm}\n\n\\noindent ')
+
+    def depart_subtitle(self, node):
+        self.body.append(self.context.pop())
+
+    def visit_system_message(self, node):
+        pass
+
+    def depart_system_message(self, node):
+        self.body.append('\n')
+
+    def visit_table(self, node):
+        if self.active_table.is_open():
+            print 'nested tables are not supported'
+            raise AssertionError
+        self.active_table.open()
+        self.body.append('\n' + self.active_table.get_opening())
+
+    def depart_table(self, node):
+        self.body.append(self.active_table.get_closing() + '\n')
+        self.active_table.close()
+
+    def visit_target(self, node):
+        # BUG: why not (refuri or refid or refname) means not footnote ?
+        if not (node.has_key('refuri') or node.has_key('refid')
+                or node.has_key('refname')):
+            for id in node['ids']:
+                self.body.append('\\hypertarget{%s}{' % id)
+            self.context.append('}' * len(node['ids']))
+        else:
+            self.context.append('')
+
+    def depart_target(self, node):
+        self.body.append(self.context.pop())
+
+    def visit_tbody(self, node):
+        # BUG write preamble if not yet done (colspecs not [])
+        # for tables without heads.
+        if not self.active_table.get('preamble written'):
+            self.visit_thead(None)
+            # self.depart_thead(None)
+
+    def depart_tbody(self, node):
+        pass
+
+    def visit_term(self, node):
+        self.body.append('\\item[{')
+
+    def depart_term(self, node):
+        # definition list term.
+        self.body.append('}] ')
+
+    def visit_tgroup(self, node):
+        #self.body.append(self.starttag(node, 'colgroup'))
+        #self.context.append('</colgroup>\n')
+        pass
+
+    def depart_tgroup(self, node):
+        pass
+
+    def visit_thead(self, node):
+        self.body.append('{%s}\n' % self.active_table.get_colspecs())
+        if self.active_table.caption:
+            self.body.append('\\caption{%s}\\\\\n' % self.active_table.caption)
+        self.active_table.set('preamble written',1)
+        # TODO longtable supports firsthead and lastfoot too.
+        self.body.extend(self.active_table.visit_thead())
+
+    def depart_thead(self, node):
+        # the table header written should be on every page
+        # => \endhead
+        self.body.extend(self.active_table.depart_thead())
+        # and the firsthead => \endfirsthead
+        # BUG i want a "continued from previous page" on every not
+        # firsthead, but then we need the header twice.
+        #
+        # there is a \endfoot and \endlastfoot too.
+        # but we need the number of columns to
+        # self.body.append('\\multicolumn{%d}{c}{"..."}\n' % number_of_columns)
+        # self.body.append('\\hline\n\\endfoot\n')
+        # self.body.append('\\hline\n')
+        # self.body.append('\\endlastfoot\n')
+
+    def visit_tip(self, node):
+        self.visit_admonition(node, 'tip')
+
+    def depart_tip(self, node):
+        self.depart_admonition()
+
+    def bookmark(self, node):
+        """Append latex href and pdfbookmarks for titles.
+        """
+        if node.parent['ids']:
+            for id in node.parent['ids']:
+                #self.body.append('\\hypertarget{%s}{}\n' % id)
+                pass
+            if not self.use_latex_toc:
+                # BUG level depends on style. pdflatex allows level 0 to 3
+                # ToC would be the only on level 0 so i choose to decrement the rest.
+                # "Table of contents" bookmark to see the ToC. To avoid this
+                # we set all zeroes to one.
+                l = self.section_level
+                if l>0:
+                    l = l-1
+                # pdftex does not like "_" subscripts in titles
+                text = self.encode(node.astext())
+                for id in node.parent['ids']:
+                    self.body.append('\\pdfbookmark[%d]{%s}{%s}\n' % \
+                                     (l, text, id))
+
+    def visit_title(self, node):
+        """Only 3 section levels are supported by LaTeX article (AFAIR)."""
+        #print "TITLE: ", node, node.parent.__class__
+        if isinstance(node.parent, addnodes.seealso):
+            raise nodes.SkipNode
+        if isinstance(node.parent, nodes.topic):
+            # section titles before the table of contents.
+            self.bookmark(node)
+            # BUG: latex chokes on center environment with "perhaps a missing item".
+            # so we use hfill.
+            self.body.append('\\subsubsection*{~\\hfill ')
+            # the closing brace for subsection.
+            self.context.append('\\hfill ~}\n')
+        # TODO: for admonition titles before the first section
+        # either specify every possible node or ... ?
+        elif isinstance(node.parent, nodes.sidebar) \
+        or isinstance(node.parent, nodes.admonition):
+            self.body.append('\\textbf{\\large ')
+            self.context.append('}\n\\smallskip\n')
+        elif isinstance(node.parent, nodes.table):
+            # caption must be written after column spec
+            self.active_table.caption = self.encode(node.astext())
+            raise nodes.SkipNode
+        elif self.section_level == 0:
+            # document title
+            self.title = self.encode(node.astext())
+            if not self.pdfinfo == None:
+                self.pdfinfo.append( 'pdftitle={%s}' % self.encode(node.astext()) )
+            raise nodes.SkipNode
+        else:
+            self.body.append('\n\n')
+            self.body.append('%' + '_' * 75)
+            self.body.append('\n\n')
+            self.bookmark(node)
+
+            if self.use_latex_toc:
+                section_star = ""
+            else:
+                section_star = "*"
+
+            section_name = self.d_class.section(self.section_level)
+            self.body.append('\\%s%s{' % (section_name, section_star))
+
+            self.context.append('}\n')
+
+    def depart_title(self, node):
+        self.body.append(self.context.pop())
+
+    def visit_topic(self, node):
+        self.topic_classes = node['classes']
+        if 'contents' in node['classes'] and self.use_latex_toc:
+            self.body.append('\\tableofcontents\n\n\\bigskip\n')
+            self.topic_classes = []
+            raise nodes.SkipNode
+
+    def visit_inline(self, node): # titlereference
+        self.body.append( '\\docutilsrole%s{' % node.get('class'))
+
+    def depart_inline(self, node):
+        self.body.append( '}' )
+
+    def depart_topic(self, node):
+        self.topic_classes = []
+        self.body.append('\n')
+
+    def visit_rubric(self, node):
+        self.body.append('\\rubric{')
+        self.context.append('}\n')
+
+    def depart_rubric(self, node):
+        self.body.append(self.context.pop())
+
+    def visit_transition(self, node):
+        self.body.append('\n\n')
+        self.body.append('%' + '_' * 75)
+        self.body.append('\n\\hspace*{\\fill}\\hrulefill\\hspace*{\\fill}')
+        self.body.append('\n\n')
+
+    def depart_transition(self, node):
+        pass
+
+    def visit_version(self, node):
+        self.visit_docinfo_item(node, 'version')
+
+    def depart_version(self, node):
+        self.depart_docinfo_item(node)
+
+    def visit_warning(self, node):
+        self.visit_admonition(node, 'warning')
+
+    def depart_warning(self, node):
+        self.depart_admonition()
+
+    def visit_desc(self, node):
+        print "DESC: ", node
+        if node.attributes['desctype'] == 'function':
+            self.body.append('\\begin{funcdesc}')
+        elif node.attributes['desctype'] == 'class':
+            #print "CLASSDESC: ", node
+            self.body.append('\\begin{classdesc*}')
+        elif node.attributes['desctype'] == 'attribute':
+            self.body.append('\\begin{memberdesc}')
+        else:
+            print "DESC: ", node
+        pass
+        
+    def depart_desc(self, node):
+        if node.attributes['desctype'] == 'function':
+            self.body.append('\\end{funcdesc}\n')
+        elif node.attributes['desctype'] == 'class':
+            self.body.append('\\end{classdesc*}\n')
+        elif node.attributes['desctype'] == 'attribute':
+            self.body.append('\\end{memberdesc}\n')
+
+        pass
+
+    def visit_desc_signature(self, node):
+        print "SIG: ", node
+        self.body.append('')
+
+    def depart_desc_signature(self, node):
+        self.body.append('')
+        pass
+
+    def visit_desc_classname(self, node):
+        #print "CLASSNAME: ", node, node.parent.attributes, node.parent.__class__
+        self.body.append('{')
+        if node.astext() == 'None':
+            #self.body.append('}')
+            #raise nodes.SkipNode
+            node.clear()
+            pass
+
+        #raise nodes.SkipNode
+        #self.body.append('{')
+        pass
+
+    def depart_desc_classname(self, node):
+        #self.body.append('}')
+        pass
+
+    def visit_desc_name(self, node):
+        #print "NAME: ", node, node.parent.attributes, dir(node)
+        #self.body.append('{')
+        pass
+
+    def depart_desc_name(self, node):
+        self.body.append('}')
+        pass
+
+    def visit_desc_parameterlist(self, node):
+        #print "PARAMLIST: ", node
+        self.body.append('{')
+
+    def depart_desc_parameterlist(self, node):
+        self.body.append('}')
+        pass
+
+    def visit_desc_parameter(self, node):
+        #print "PARAM: ", node
+        pass
+
+    def depart_desc_parameter(self, node):
+        pass
+
+    def visit_desc_content(self, node):
+        #print "CONTENT: ", node
+        pass
+
+    def depart_desc_content(self, node):
+        pass
+
+
+    def visit_pending_xref(self, node):
+        #raise nodes.SkipNode()
+        print "XREF: ", node, dir(node)
+        pass
+
+    def depart_pending_xref(self, node):
+        pass
+
+    def visit_seealso(self, node):
+        print "SEEALSO: ", node, dir(node)
+        self.body.append('\\begin{seealso}\n')
+        #self.no_sections = True
+        #
+        #self.section_level += 1
+        ## Initialize counter for potential subsections:
+        #self._section_number.append(0)
+        ## Counter for this section's level (initialized by parent section):
+        #self._section_number[self.section_level - 1] += 1
+
+        #self.visit_admonition(node, 'attention')
+        
+    def depart_seealso(self, node):
+        self.body.append('\\end{seealso}\n\n')
+        #self.no_sections = False
+
+        #self._section_number.pop()
+        #self.section_level -= 1
+
+        #self.depart_admonition(node)
+
+    def visit_versionmodified(self, node):
+        raise nodes.SkipNode()
+
+    def depart_versionmodified(self, node):
+        pass
+
+    def visit_desc_optional(self, node):
+        raise nodes.SkipNode()
+
+    def depart_desc_optional(self, node):
+        pass
+        
+    def unimplemented_visit(self, node):
+        raise NotImplementedError('visiting unimplemented node type: %s'
+                                  % node.__class__.__name__)
+
+    def unknown_visit(self, node):
+        print "UNKNOWN: ", node
+        
+#    def default_visit(self, node):
+
+# vim: set ts=4 et ai :


Property changes on: Sandbox/ulif/grok-reference-with-rest/doc/reference-new/latex_manual/__init__.py
___________________________________________________________________
Name: svn:executable
   + *

Added: Sandbox/ulif/grok-reference-with-rest/doc/reference-new/latex_manual/addnodes.py
===================================================================
--- Sandbox/ulif/grok-reference-with-rest/doc/reference-new/latex_manual/addnodes.py	                        (rev 0)
+++ Sandbox/ulif/grok-reference-with-rest/doc/reference-new/latex_manual/addnodes.py	2007-10-01 05:51:41 UTC (rev 80434)
@@ -0,0 +1,65 @@
+# -*- coding: utf-8 -*-
+"""
+    sphinx.addnodes
+    ~~~~~~~~~~~~~~~
+
+    :copyright: 2007 by Georg Brandl.
+    :license: Python license.
+"""
+
+from docutils import nodes
+
+# index markup
+class index(nodes.Invisible, nodes.Inline, nodes.TextElement): pass
+
+# description units (classdesc, funcdesc etc.)
+class desc(nodes.Admonition, nodes.Element): pass
+class desc_content(nodes.General, nodes.Element): pass
+class desc_signature(nodes.Part, nodes.Inline, nodes.TextElement): pass
+class desc_classname(nodes.Part, nodes.Inline, nodes.TextElement): pass
+class desc_name(nodes.Part, nodes.Inline, nodes.TextElement): pass
+class desc_parameterlist(nodes.Part, nodes.Inline, nodes.TextElement): pass
+class desc_parameter(nodes.Part, nodes.Inline, nodes.TextElement): pass
+class desc_optional(nodes.Part, nodes.Inline, nodes.TextElement): pass
+
+# refcount annotation
+class refcount(nodes.emphasis): pass
+
+# \versionadded, \versionchanged, \deprecated
+class versionmodified(nodes.Admonition, nodes.TextElement): pass
+
+# seealso
+class seealso(nodes.Admonition, nodes.Element): pass
+
+# productionlist
+class productionlist(nodes.Admonition, nodes.Element): pass
+class production(nodes.Part, nodes.Inline, nodes.TextElement): pass
+
+# toc tree
+class toctree(nodes.General, nodes.Element): pass
+
+# centered
+class centered(nodes.Part, nodes.Element): pass
+
+# pending xref
+class pending_xref(nodes.Element): pass
+
+# compact paragraph -- never makes a <p>
+class compact_paragraph(nodes.paragraph): pass
+
+# sets the highlighting language for literal blocks
+class highlightlang(nodes.Element): pass
+
+# like emphasis, but doesn't apply further text processors, e.g. smartypants
+class literal_emphasis(nodes.emphasis): pass
+
+# glossary
+class glossary(nodes.Element): pass
+
+# make them known to docutils. this is needed, because the HTMl writer
+# will choke at some point if these are not added
+nodes._add_node_class_names("""index desc desc_content desc_signature
+      desc_classname desc_name desc_parameterlist desc_parameter desc_optional
+      centered versionmodified seealso productionlist production toctree
+      pending_xref compact_paragraph highlightlang literal_emphasis
+      glossary""".split())

Added: Sandbox/ulif/grok-reference-with-rest/doc/reference-new/latex_manual/directives.py
===================================================================
--- Sandbox/ulif/grok-reference-with-rest/doc/reference-new/latex_manual/directives.py	                        (rev 0)
+++ Sandbox/ulif/grok-reference-with-rest/doc/reference-new/latex_manual/directives.py	2007-10-01 05:51:41 UTC (rev 80434)
@@ -0,0 +1,620 @@
+# -*- coding: utf-8 -*-
+"""
+    sphinx.directives
+    ~~~~~~~~~~~~~~~~~
+
+    Handlers for additional ReST directives.
+
+    :copyright: 2007 by Georg Brandl.
+    :license: Python license.
+"""
+#from __future__ import with_statement
+
+import re
+import string
+from os import path
+
+from docutils import nodes
+from docutils.parsers.rst import directives, roles
+from docutils.parsers.rst.directives import admonitions
+
+import addnodes
+
+# ------ index markup --------------------------------------------------------------
+
+entrytypes = [
+    'single', 'pair', 'triple', 'quadruple',
+    'module', 'keyword', 'operator', 'object', 'exception', 'statement', 'builtin',
+]
+
+def index_directive(name, arguments, options, content, lineno,
+                    content_offset, block_text, state, state_machine):
+    arguments = arguments[0].split('\n')
+    env = state.document.settings.env
+    targetid = 'index-%s' % env.index_num
+    env.index_num += 1
+    targetnode = nodes.target('', '', ids=[targetid])
+    state.document.note_explicit_target(targetnode)
+    indexnode = addnodes.index()
+    indexnode['entries'] = arguments
+    for entry in arguments:
+        try:
+            type, string = entry.split(':', 1)
+            env.note_index_entry(type.strip(), string.strip(),
+                                 targetid, string.strip())
+        except ValueError:
+            continue
+    return [indexnode, targetnode]
+
+index_directive.arguments = (1, 0, 1)
+directives.register_directive('index', index_directive)
+
+# ------ information units ---------------------------------------------------------
+
+def desc_index_text(desctype, currmodule, name):
+    if desctype == 'function':
+        if not currmodule:
+            return '%s() (built-in function)' % name
+        return '%s() (in module %s)' % (name, currmodule)
+    elif desctype == 'data':
+        if not currmodule:
+            return '%s (built-in variable)' % name
+        return '%s (in module %s)' % (name, currmodule)
+    elif desctype == 'class':
+        return '%s (class in %s)' % (name, currmodule)
+    elif desctype == 'exception':
+        return name
+    elif desctype == 'method':
+        try:
+            clsname, methname = name.rsplit('.', 1)
+        except:
+            if currmodule:
+                return '%s() (in module %s)' % (name, currmodule)
+            else:
+                return '%s()' % name
+        if currmodule:
+            return '%s() (%s.%s method)' % (methname, currmodule, clsname)
+        else:
+            return '%s() (%s method)' % (methname, clsname)
+    elif desctype == 'attribute':
+        try:
+            clsname, attrname = name.rsplit('.', 1)
+        except:
+            if currmodule:
+                return '%s (in module %s)' % (name, currmodule)
+            else:
+                return name
+        if currmodule:
+            return '%s (%s.%s attribute)' % (attrname, currmodule, clsname)
+        else:
+            return '%s (%s attribute)' % (attrname, clsname)
+    elif desctype == 'opcode':
+        return '%s (opcode)' % name
+    elif desctype == 'cfunction':
+        return '%s (C function)' % name
+    elif desctype == 'cmember':
+        return '%s (C member)' % name
+    elif desctype == 'cmacro':
+        return '%s (C macro)' % name
+    elif desctype == 'ctype':
+        return '%s (C type)' % name
+    elif desctype == 'cvar':
+        return '%s (C variable)' % name
+    else:
+        raise ValueError("unhandled descenv: %s" % desctype)
+
+
+# ------ functions to parse a Python or C signature and create desc_* nodes.
+
+py_sig_re = re.compile(r'''^([\w.]*\.)?        # class names
+                           (\w+)  \s*          # thing name
+                           (?: \((.*)\) )? $   # optionally arguments
+                        ''', re.VERBOSE)
+
+py_paramlist_re = re.compile(r'([\[\],])')  # split at '[', ']' and ','
+
+def parse_py_signature(signode, sig, desctype, env):
+    """
+    Transform a python signature into RST nodes.
+    Return (fully qualified name of the thing, classname if any).
+
+    If inside a class, the current class name is handled intelligently:
+    * it is stripped from the displayed name if present
+    * it is added to the full name (return value) if not present
+    """
+    m = py_sig_re.match(sig)
+    if m is None: raise ValueError
+    classname, name, arglist = m.groups()
+
+##     if env.currclass:
+##         if classname and classname.startswith(env.currclass):
+##             fullname = classname + name
+##             classname = classname[len(env.currclass):].lstrip('.')
+##         elif classname:
+##             fullname = env.currclass + '.' + classname + name
+##         else:
+##             fullname = env.currclass + '.' + name
+##     else:
+##         ### fullname = classname + name if classname else name
+    fullname = classname and classname + name or name
+
+    # exceptions are a special case, since they are documented in the
+    # 'exceptions' module.
+##     if env.config.get('add_module_names', True) and \
+##            env.currmodule and env.currmodule != 'exceptions':
+##         nodetext = env.currmodule + '.'
+##         if classname:
+##             nodetext += classname
+##         signode += addnodes.desc_classname(nodetext, nodetext)
+##     elif classname:
+    signode += addnodes.desc_classname(classname, classname)
+
+    signode += addnodes.desc_name(name, name)
+    if not arglist:
+        if desctype in ('function', 'method'):
+            # for callables, add an empty parameter list
+            signode += addnodes.desc_parameterlist()
+        return fullname, classname
+    signode += addnodes.desc_parameterlist()
+
+    stack = [signode[-1]]
+    for token in py_paramlist_re.split(arglist):
+        if token == '[':
+            opt = addnodes.desc_optional()
+            stack[-1] += opt
+            stack.append(opt)
+        elif token == ']':
+            try: stack.pop()
+            except IndexError: raise ValueError
+        elif not token or token == ',' or token.isspace():
+            pass
+        else:
+            token = token.strip()
+            stack[-1] += addnodes.desc_parameter(token, token)
+    if len(stack) != 1: raise ValueError
+    return fullname, classname
+
+
+c_sig_re = re.compile(
+    r'''^([^(]*?)          # return type
+        (\w+)  \s*         # thing name
+        (?: \((.*)\) )? $  # optionally arguments
+    ''', re.VERBOSE)
+c_funcptr_sig_re = re.compile(
+    r'''^([^(]+?)          # return type
+        (\( [^()]+ \)) \s* # name in parentheses
+        \( (.*) \) $       # arguments
+    ''', re.VERBOSE)
+
+# RE to split at word boundaries
+wsplit_re = re.compile(r'(\W+)')
+
+# These C types aren't described in the reference, so don't try to create
+# a cross-reference to them
+stopwords = set(('const', 'void', 'char', 'int', 'long', 'FILE', 'struct'))
+
+def parse_c_type(node, ctype):
+    # add cross-ref nodes for all words
+    for part in filter(None, wsplit_re.split(ctype)):
+        tnode = nodes.Text(part, part)
+        if part[0] in string.letters+'_' and part not in stopwords:
+            pnode = addnodes.pending_xref(
+                '', reftype='ctype', reftarget=part, modname=None, classname=None)
+            pnode += tnode
+            node += pnode
+        else:
+            node += tnode
+
+def parse_c_signature(signode, sig, desctype):
+    """Transform a C-language signature into RST nodes."""
+    # first try the function pointer signature regex, it's more specific
+    m = c_funcptr_sig_re.match(sig)
+    if m is None:
+        m = c_sig_re.match(sig)
+    if m is None:
+        raise ValueError('no match')
+    rettype, name, arglist = m.groups()
+
+    parse_c_type(signode, rettype)
+    signode += addnodes.desc_name(name, name)
+    if not arglist:
+        if desctype == 'cfunction':
+            # for functions, add an empty parameter list
+            signode += addnodes.desc_parameterlist()
+        return name
+
+    paramlist = addnodes.desc_parameterlist()
+    arglist = arglist.replace('`', '').replace('\\ ', '') # remove markup
+    # this messes up function pointer types, but not too badly ;)
+    args = arglist.split(',')
+    for arg in args:
+        arg = arg.strip()
+        param = addnodes.desc_parameter('', '', noemph=True)
+        try:
+            ctype, argname = arg.rsplit(' ', 1)
+        except ValueError:
+            # no argument name given, only the type
+            parse_c_type(param, arg)
+        else:
+            parse_c_type(param, ctype)
+            param += nodes.emphasis(' '+argname, ' '+argname)
+        paramlist += param
+    signode += paramlist
+    return name
+
+
+opcode_sig_re = re.compile(r'(\w+(?:\+\d)?)\s*\((.*)\)')
+
+def parse_opcode_signature(signode, sig, desctype):
+    """Transform an opcode signature into RST nodes."""
+    m = opcode_sig_re.match(sig)
+    if m is None: raise ValueError
+    opname, arglist = m.groups()
+    signode += addnodes.desc_name(opname, opname)
+    paramlist = addnodes.desc_parameterlist()
+    signode += paramlist
+    paramlist += addnodes.desc_parameter(arglist, arglist)
+    return opname.strip()
+
+
+def add_refcount_annotation(env, node, name):
+    """Add a reference count annotation. Return None."""
+    entry = env.refcounts.get(name)
+    if not entry:
+        return
+    elif entry.result_type not in ("PyObject*", "PyVarObject*"):
+        return
+    rc = 'Return value: '
+    if entry.result_refs is None:
+        rc += "Always NULL."
+    else:
+        rc += (entry.result_refs and "New" or "Borrowed") + " reference."
+    node += addnodes.refcount(rc, rc)
+
+
+def desc_directive(desctype, arguments, options, content, lineno,
+                   content_offset, block_text, state, state_machine):
+    #env = state.document.settings.env
+    env = None
+    node = addnodes.desc()
+    node['desctype'] = desctype
+
+    noindex = ('noindex' in options)
+    signatures = map(lambda s: s.strip(), arguments[0].split('\n'))
+    names = []
+    clsname = None
+    for i, sig in enumerate(signatures):
+        # add a signature node for each signature in the current unit
+        # and add a reference target for it
+        sig = sig.strip()
+        signode = addnodes.desc_signature(sig, '')
+        signode['first'] = False
+        node.append(signode)
+        try:
+            if desctype in ('function', 'data', 'class', 'exception',
+                            'method', 'attribute'):
+                name, clsname = parse_py_signature(signode, sig, desctype, env)
+            elif desctype in ('cfunction', 'cmember', 'cmacro', 'ctype', 'cvar'):
+                name = parse_c_signature(signode, sig, desctype)
+            elif desctype == 'opcode':
+                name = parse_opcode_signature(signode, sig, desctype)
+            else:
+                # describe: use generic fallback
+                raise ValueError
+        except ValueError, err:
+            signode.clear()
+            signode += addnodes.desc_name(sig, sig)
+            continue             # we don't want an index entry here
+        # only add target and index entry if this is the first description of the
+        # function name in this desc block
+        if not noindex and name not in names:
+            ### fullname = (env.currmodule + env.currmodule and '.' or '') + name
+            fullname = name
+            # note target
+            if fullname not in state.document.ids:
+                signode['names'].append(fullname)
+                signode['ids'].append(fullname)
+                signode['first'] = (not names)
+                state.document.note_explicit_target(signode)
+                #env.note_descref(fullname, desctype)
+            names.append(name)
+
+##             env.note_index_entry('single',
+##                                  desc_index_text(desctype, env.currmodule, name),
+##                                  fullname, fullname)
+
+    subnode = addnodes.desc_content()
+    if desctype == 'cfunction':
+        add_refcount_annotation(env, subnode, name)
+    # needed for automatic qualification of members
+    clsname_set = False
+    if desctype == 'class' and names:
+        #env.currclass = names[0]
+        clsname_set = True
+##     elif desctype in ('method', 'attribute') and clsname and not env.currclass:
+##         #env.currclass = clsname.strip('.')
+##         clsname_set = True
+    # needed for association of version{added,changed} directives
+    if names:
+        ###env.currdesc = names[0]
+        pass
+    state.nested_parse(content, content_offset, subnode)
+    if clsname_set:
+        #env.currclass = None
+        pass
+    ###env.currdesc = None
+    node.append(subnode)
+    return [node]
+
+desc_directive.content = 1
+desc_directive.arguments = (1, 0, 1)
+desc_directive.options = {'noindex': directives.flag}
+
+desctypes = [
+    # the Python ones
+    'function',
+    'data',
+    'class',
+    'method',
+    'attribute',
+    'exception',
+    # the C ones
+    'cfunction',
+    'cmember',
+    'cmacro',
+    'ctype',
+    'cvar',
+    # the odd one
+    'opcode',
+    # the generic one
+    'describe',
+]
+
+for name in desctypes:
+    directives.register_directive(name, desc_directive)
+
+
+# ------ versionadded/versionchanged -----------------------------------------------
+
+def version_directive(name, arguments, options, content, lineno,
+                      content_offset, block_text, state, state_machine):
+    node = addnodes.versionmodified()
+    node['type'] = name
+    node['version'] = arguments[0]
+    if len(arguments) == 2:
+        inodes, messages = state.inline_text(arguments[1], lineno+1)
+        node.extend(inodes)
+        if content:
+            state.nested_parse(content, content_offset, node)
+        ret = [node] + messages
+    else:
+        ret = [node]
+    #env = state.document.settings.env
+    #env.note_versionchange(node['type'], node['version'], node)
+    return ret
+
+version_directive.arguments = (1, 1, 1)
+version_directive.content = 1
+
+directives.register_directive('deprecated', version_directive)
+directives.register_directive('versionadded', version_directive)
+directives.register_directive('versionchanged', version_directive)
+
+
+# ------ see also ------------------------------------------------------------------
+
+def seealso_directive(name, arguments, options, content, lineno,
+                      content_offset, block_text, state, state_machine):
+    rv = admonitions.make_admonition(
+        addnodes.seealso, name, ['See also'], options, content,
+        lineno, content_offset, block_text, state, state_machine)
+    return rv
+
+seealso_directive.content = 1
+seealso_directive.arguments = (0, 0, 0)
+directives.register_directive('seealso', seealso_directive)
+
+
+# ------ production list (for the reference) ---------------------------------------
+
+token_re = re.compile('`([a-z_]+)`')
+
+def token_xrefs(text, env):
+    retnodes = []
+    pos = 0
+    for m in token_re.finditer(text):
+        if m.start() > pos:
+            txt = text[pos:m.start()]
+            retnodes.append(nodes.Text(txt, txt))
+        refnode = addnodes.pending_xref(m.group(1))
+        refnode['reftype'] = 'token'
+        refnode['reftarget'] = m.group(1)
+        refnode['modname'] = env.currmodule
+        refnode['classname'] = env.currclass
+        refnode += nodes.literal(m.group(1), m.group(1), classes=['xref'])
+        retnodes.append(refnode)
+        pos = m.end()
+    if pos < len(text):
+        retnodes.append(nodes.Text(text[pos:], text[pos:]))
+    return retnodes
+
+def productionlist_directive(name, arguments, options, content, lineno,
+                             content_offset, block_text, state, state_machine):
+    env = state.document.settings.env
+    node = addnodes.productionlist()
+    messages = []
+    i = 0
+
+    for rule in arguments[0].split('\n'):
+        if i == 0 and ':' not in rule:
+            # production group
+            continue
+        i += 1
+        try:
+            name, tokens = rule.split(':', 1)
+        except ValueError:
+            break
+        subnode = addnodes.production()
+        subnode['tokenname'] = name.strip()
+        if subnode['tokenname']:
+            idname = 'grammar-token-%s' % subnode['tokenname']
+            if idname not in state.document.ids:
+                subnode['ids'].append(idname)
+            state.document.note_implicit_target(subnode, subnode)
+            env.note_token(subnode['tokenname'])
+        subnode.extend(token_xrefs(tokens, env))
+        node.append(subnode)
+    return [node] + messages
+
+productionlist_directive.content = 0
+productionlist_directive.arguments = (1, 0, 1)
+directives.register_directive('productionlist', productionlist_directive)
+
+# ------ section metadata ----------------------------------------------------------
+
+def module_directive(name, arguments, options, content, lineno,
+                     content_offset, block_text, state, state_machine):
+    env = state.document.settings.env
+    modname = arguments[0].strip()
+    env.currmodule = modname
+    env.note_module(modname, options.get('synopsis', ''),
+                    options.get('platform', ''),
+                    'deprecated' in options)
+    ret = []
+    targetnode = nodes.target('', '', ids=['module-' + modname])
+    state.document.note_explicit_target(targetnode)
+    ret.append(targetnode)
+    if 'platform' in options:
+        node = nodes.paragraph()
+        node += nodes.emphasis('Platforms: ', 'Platforms: ')
+        node += nodes.Text(options['platform'], options['platform'])
+        ret.append(node)
+    # the synopsis isn't printed; in fact, it is only used in the modindex currently
+    env.note_index_entry('single', '%s (module)' % modname, 'module-' + modname,
+                         modname)
+    return ret
+
+module_directive.arguments = (1, 0, 0)
+module_directive.options = {'platform': lambda x: x,
+                            'synopsis': lambda x: x,
+                            'deprecated': directives.flag}
+directives.register_directive('module', module_directive)
+
+
+def author_directive(name, arguments, options, content, lineno,
+                     content_offset, block_text, state, state_machine):
+    # The author directives aren't included in the built document
+    return []
+
+author_directive.arguments = (1, 0, 1)
+directives.register_directive('sectionauthor', author_directive)
+directives.register_directive('moduleauthor', author_directive)
+
+
+# ------ toctree directive ---------------------------------------------------------
+
+def toctree_directive(name, arguments, options, content, lineno,
+                      content_offset, block_text, state, state_machine):
+    env = state.document.settings.env
+    dirname = path.dirname(env.filename)
+
+    subnode = addnodes.toctree()
+    includefiles = filter(None, content)
+    # absolutize filenames
+    includefiles = map(lambda x: path.normpath(path.join(dirname, x)), includefiles)
+    subnode['includefiles'] = includefiles
+    subnode['maxdepth'] = options.get('maxdepth', -1)
+    return [subnode]
+
+toctree_directive.content = 1
+toctree_directive.options = {'maxdepth': int}
+directives.register_directive('toctree', toctree_directive)
+
+
+# ------ centered directive ---------------------------------------------------------
+
+def centered_directive(name, arguments, options, content, lineno,
+                       content_offset, block_text, state, state_machine):
+    if not arguments:
+        return []
+    subnode = addnodes.centered()
+    inodes, messages = state.inline_text(arguments[0], lineno)
+    subnode.extend(inodes)
+    return [subnode] + messages
+
+centered_directive.arguments = (1, 0, 1)
+directives.register_directive('centered', centered_directive)
+
+
+# ------ highlightlanguage directive ------------------------------------------------
+
+def highlightlang_directive(name, arguments, options, content, lineno,
+                            content_offset, block_text, state, state_machine):
+    return [addnodes.highlightlang(lang=arguments[0].strip())]
+
+highlightlang_directive.content = 0
+highlightlang_directive.arguments = (1, 0, 0)
+directives.register_directive('highlightlang', highlightlang_directive)
+
+
+# ------ literalinclude directive ---------------------------------------------------
+
+def literalinclude_directive(name, arguments, options, content, lineno,
+                             content_offset, block_text, state, state_machine):
+    """Like .. include:: :literal:, but only warns if the include file is not found."""
+    if not state.document.settings.file_insertion_enabled:
+        return [state.document.reporter.warning('File insertion disabled', line=lineno)]
+    env = state.document.settings.env
+    fn = arguments[0]
+    source_dir = path.dirname(path.abspath(state_machine.input_lines.source(
+        lineno - state_machine.input_offset - 1)))
+    fn = path.normpath(path.join(source_dir, fn))
+
+    try:
+        #with open(fn) as f:
+        f = open(fn)
+        text = f.read()
+        f.close()
+    except (IOError, OSError):
+        retnode = state.document.reporter.warning('Include file %r not found' %
+                                                  arguments[0], line=lineno)
+    else:
+        retnode = nodes.literal_block(text, text, source=fn)
+        retnode.line = 1
+    return [retnode]
+
+literalinclude_directive.content = 0
+literalinclude_directive.arguments = (1, 0, 0)
+directives.register_directive('literalinclude', literalinclude_directive)
+
+
+# ------ glossary directive ---------------------------------------------------------
+
+def glossary_directive(name, arguments, options, content, lineno,
+                       content_offset, block_text, state, state_machine):
+    """Glossary with cross-reference targets for :dfn: roles."""
+    env = state.document.settings.env
+    node = addnodes.glossary()
+    state.nested_parse(content, content_offset, node)
+
+    # the content should be definition lists
+    dls = [child for child in node if isinstance(child, nodes.definition_list)]
+    # now, extract definition terms to enable cross-reference creation
+    for dl in dls:
+        dl['classes'].append('glossary')
+        for li in dl.children:
+            if not li.children or not isinstance(li[0], nodes.term):
+                continue
+            termtext = li.children[0].astext()
+            new_id = 'term-' + nodes.make_id(termtext)
+            if new_id in env.gloss_entries:
+                new_id = 'term-' + str(len(env.gloss_entries))
+            env.gloss_entries.add(new_id)
+            li[0]['names'].append(new_id)
+            li[0]['ids'].append(new_id)
+            state.document.settings.env.note_glossaryterm(termtext, new_id)
+    return [node]
+
+glossary_directive.content = 1
+glossary_directive.arguments = (0, 0, 0)
+directives.register_directive('glossary', glossary_directive)

Added: Sandbox/ulif/grok-reference-with-rest/doc/reference-new/latex_manual/roles.py
===================================================================
--- Sandbox/ulif/grok-reference-with-rest/doc/reference-new/latex_manual/roles.py	                        (rev 0)
+++ Sandbox/ulif/grok-reference-with-rest/doc/reference-new/latex_manual/roles.py	2007-10-01 05:51:41 UTC (rev 80434)
@@ -0,0 +1,176 @@
+# -*- coding: utf-8 -*-
+"""
+    sphinx.roles
+    ~~~~~~~~~~~~
+
+    Handlers for additional ReST roles.
+
+    :copyright: 2007 by Georg Brandl.
+    :license: Python license.
+"""
+
+import re
+
+from docutils import nodes, utils
+from docutils.parsers.rst import roles
+
+import addnodes
+
+ws_re = re.compile(r'\s+')
+
+generic_docroles = {
+    'command' : nodes.strong,
+    'dfn' : nodes.emphasis,
+    'guilabel' : nodes.strong,
+    'kbd' : nodes.literal,
+    'keyword' : nodes.literal,
+    'mailheader' : addnodes.literal_emphasis,
+    'makevar' : nodes.Text,
+    'manpage' : addnodes.literal_emphasis,
+    'mimetype' : addnodes.literal_emphasis,
+    'newsgroup' : addnodes.literal_emphasis,
+    'option' : addnodes.literal_emphasis,
+    'program' : nodes.strong,
+    'regexp' : nodes.literal,
+}
+
+for rolename, nodeclass in generic_docroles.iteritems():
+    roles.register_generic_role(rolename, nodeclass)
+
+
+def indexmarkup_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
+    env = inliner.document.settings.env
+    text = utils.unescape(text)
+    targetid = 'index-%s' % env.index_num
+    env.index_num += 1
+    targetnode = nodes.target('', '', ids=[targetid])
+    inliner.document.note_explicit_target(targetnode)
+    if typ == 'envvar':
+        env.note_index_entry('single', '%s' % text,
+                             targetid, text)
+        env.note_index_entry('single', 'environment variables!%s' % text,
+                             targetid, text)
+        textnode = nodes.strong(text, text)
+        return [targetnode, textnode], []
+    elif typ == 'pep':
+        env.note_index_entry('single', 'Python Enhancement Proposals!PEP %s' % text,
+                             targetid, 'PEP %s' % text)
+        try:
+            pepnum = int(text)
+        except ValueError:
+            msg = inliner.reporter.error('invalid PEP number %s' % text, line=lineno)
+            prb = inliner.problematic(rawtext, rawtext, msg)
+            return [prb], [msg]
+        ref = inliner.document.settings.pep_base_url + 'pep-%04d' % pepnum
+        sn = nodes.strong('PEP '+text, 'PEP '+text)
+        rn = nodes.reference('', '', refuri=ref)
+        rn += sn
+        return [targetnode, rn], []
+    elif typ == 'rfc':
+        env.note_index_entry('single', 'RFC!RFC %s' % text,
+                             targetid, 'RFC %s' % text)
+        try:
+            rfcnum = int(text)
+        except ValueError:
+            msg = inliner.reporter.error('invalid RFC number %s' % text, line=lineno)
+            prb = inliner.problematic(rawtext, rawtext, msg)
+            return [prb], [msg]
+        ref = inliner.document.settings.rfc_base_url + inliner.rfc_url % rfcnum
+        sn = nodes.strong('RFC '+text, 'RFC '+text)
+        rn = nodes.reference('', '', refuri=ref)
+        rn += sn
+        return [targetnode, rn], []
+
+roles.register_canonical_role('envvar', indexmarkup_role)
+roles.register_local_role('pep', indexmarkup_role)
+roles.register_local_role('rfc', indexmarkup_role)
+
+
+# default is `literal`
+innernodetypes = {
+    'ref': nodes.emphasis,
+    'term': nodes.emphasis,
+    'token': nodes.strong,
+}
+
+def xfileref_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
+    print inliner
+    import sys
+    #sys.exit(0)
+    #env = inliner.document.settings.env
+    text = utils.unescape(text)
+    if typ in ('func', 'meth', 'cfunc'):
+        #text += '()'
+        pass
+    #if typ in ('func', 'meth', 'cfunc') and \
+    #       env.config.get('add_function_parentheses', True):
+    #    text += '()'
+    # if the first character is a bang, don't cross-reference at all
+    if text[0:1] == '!':
+        text = text[1:]
+        return [innernodetypes.get(typ, nodes.literal)(
+            rawtext, text, classes=['xref'])], []
+    pnode = addnodes.pending_xref(rawtext)
+    pnode['reftype'] = typ
+    # if the first character is a dot, search more specific namespaces first
+    # else search builtins first
+    if text[0:1] == '.' and \
+       typ in ('data', 'exc', 'func', 'class', 'const', 'attr', 'meth'):
+        text = text[1:]
+        pnode['refspecific'] = True
+    pnode['reftarget'] = ws_re.sub((typ == 'term' and ' ' or ''), text)
+    #pnode['modname'] = env.currmodule
+    #pnode['classname'] = env.currclass
+    pnode += innernodetypes.get(typ, nodes.literal)(rawtext, text, classes=['xref'])
+    return [pnode], []
+
+
+def menusel_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
+    return [nodes.emphasis(
+        rawtext, utils.unescape(text).replace('-->', u'\N{TRIANGULAR BULLET}'))], []
+
+
+_litvar_re = re.compile('{([^}]+)}')
+
+def emph_literal_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
+    text = utils.unescape(text)
+    retnodes = []
+    pos = 0
+    for m in _litvar_re.finditer(text):
+        if m.start() > pos:
+            txt = text[pos:m.start()]
+            retnodes.append(nodes.literal(txt, txt))
+        retnodes.append(nodes.emphasis('', '', nodes.literal(m.group(1), m.group(1))))
+        pos = m.end()
+    if pos < len(text):
+        retnodes.append(nodes.literal(text[pos:], text[pos:]))
+    return retnodes, []
+
+
+specific_docroles = {
+    'data': xfileref_role,
+    'exc': xfileref_role,
+    'func': xfileref_role,
+    'class': xfileref_role,
+    'const': xfileref_role,
+    'attr': xfileref_role,
+    'meth': xfileref_role,
+
+    'cfunc' : xfileref_role,
+    'cdata' : xfileref_role,
+    'ctype' : xfileref_role,
+    'cmacro' : xfileref_role,
+
+    'mod' : xfileref_role,
+
+    'ref': xfileref_role,
+    'token' : xfileref_role,
+    'term': xfileref_role,
+
+    'menuselection' : menusel_role,
+    'file' : emph_literal_role,
+    'samp' : emph_literal_role,
+}
+
+for rolename, func in specific_docroles.iteritems():
+    roles.register_canonical_role(rolename, func)

Added: Sandbox/ulif/grok-reference-with-rest/doc/reference-new/model.rst
===================================================================
--- Sandbox/ulif/grok-reference-with-rest/doc/reference-new/model.rst	                        (rev 0)
+++ Sandbox/ulif/grok-reference-with-rest/doc/reference-new/model.rst	2007-10-01 05:51:41 UTC (rev 80434)
@@ -0,0 +1,9 @@
+
+**********
+grok.Model
+**********
+
+
+Models
+======
+

Added: Sandbox/ulif/grok-reference-with-rest/doc/reference-new/myother.rst
===================================================================
--- Sandbox/ulif/grok-reference-with-rest/doc/reference-new/myother.rst	                        (rev 0)
+++ Sandbox/ulif/grok-reference-with-rest/doc/reference-new/myother.rst	2007-10-01 05:51:41 UTC (rev 80434)
@@ -0,0 +1,6 @@
+
+An external chapter
+===================
+
+This is an external chapter.
+

Added: Sandbox/ulif/grok-reference-with-rest/doc/reference-new/mytest.rst
===================================================================
--- Sandbox/ulif/grok-reference-with-rest/doc/reference-new/mytest.rst	                        (rev 0)
+++ Sandbox/ulif/grok-reference-with-rest/doc/reference-new/mytest.rst	2007-10-01 05:51:41 UTC (rev 80434)
@@ -0,0 +1,59 @@
+==================
+The Grok Reference
+==================
+
+:Author: The grok team
+
+:Release: "0.10"
+
+:Date: 01/01/01
+
+..
+
+   "Grok means to understand so thoroughly that the observer becomes a
+   part of the observed --- merge, blend, intermarry, lose identity in
+   group experience. It means almost everything that we mean by religion,
+   philosophy, and science --- it means as little to us (because we are from
+   Earth) as color means to a blind man." 
+
+   -- `Robert A. Heinlein, Stranger in a Strange Land`
+
+This is the grok reference documentation. It is organized by the Python
+artefacts that implement the concepts.
+
+Grok makes Zope 3 concepts more accessible for application
+developers. This reference is not intended as introductory material
+for those concepts. Please refer to the original Zope 3
+documentation and the grok tutorial for introductory material.
+
+
+.. contents:: Table of Contents
+
+.. include:: core.rst
+
+.. include:: components.rst
+
+.. include:: directives.rst
+
+
+A First Chapter
+===============
+
+This is a first paragraph.
+
+   "Grok means to understand so thoroughly that the observer becomes a
+   part of the observed --- merge, blend, intermarry, lose identity in
+   group experience. It means almost everything that we mean by religion,
+   philosophy, and science --- it means as little to us (because we are from
+   Earth) as color means to a blind man." 
+
+   -- `Robert A. Heinlein, Stranger in a Strange Land`
+
+
+
+Another Chapter
+===============
+
+This is another chapter.
+
+.. include:: myother.rst
\ No newline at end of file

Added: Sandbox/ulif/grok-reference-with-rest/doc/reference-new/mytest.tex
===================================================================
--- Sandbox/ulif/grok-reference-with-rest/doc/reference-new/mytest.tex	                        (rev 0)
+++ Sandbox/ulif/grok-reference-with-rest/doc/reference-new/mytest.tex	2007-10-01 05:51:41 UTC (rev 80434)
@@ -0,0 +1,1187 @@
+\documentclass[10pt,a4paper,english]{manual}
+\usepackage{babel}
+\usepackage{ae}
+\usepackage{aeguill}
+\usepackage{shortvrb}
+\usepackage[latin1]{inputenc}
+\usepackage{tabularx}
+\usepackage{longtable}
+\setlength{\extrarowheight}{2pt}
+\usepackage{amsmath}
+\usepackage{graphicx}
+\usepackage{color}
+\usepackage{multirow}
+\usepackage{ifthen}
+\usepackage[colorlinks=true,linkcolor=blue,urlcolor=blue]{hyperref}
+\usepackage[DIV12]{typearea}
+%% generator Docutils: http://docutils.sourceforge.net/
+\newlength{\admonitionwidth}
+\setlength{\admonitionwidth}{0.9\textwidth}
+\newlength{\docinfowidth}
+\setlength{\docinfowidth}{0.9\textwidth}
+\newlength{\locallinewidth}
+\newcommand{\optionlistlabel}[1]{\bf #1 \hfill}
+\newenvironment{optionlist}[1]
+{\begin{list}{}
+  {\setlength{\labelwidth}{#1}
+   \setlength{\rightmargin}{1cm}
+   \setlength{\leftmargin}{\rightmargin}
+   \addtolength{\leftmargin}{\labelwidth}
+   \addtolength{\leftmargin}{\labelsep}
+   \renewcommand{\makelabel}{\optionlistlabel}}
+}{\end{list}}
+\newlength{\lineblockindentation}
+\setlength{\lineblockindentation}{2.5em}
+\newenvironment{lineblock}[1]
+{\begin{list}{}
+  {\setlength{\partopsep}{\parskip}
+   \addtolength{\partopsep}{\baselineskip}
+   \topsep0pt\itemsep0.15\baselineskip\parsep0pt
+   \leftmargin#1}
+ \raggedright}
+{\end{list}}
+% begin: floats for footnotes tweaking.
+\setlength{\floatsep}{0.5em}
+\setlength{\textfloatsep}{\fill}
+\addtolength{\textfloatsep}{3em}
+\renewcommand{\textfraction}{0.5}
+\renewcommand{\topfraction}{0.5}
+\renewcommand{\bottomfraction}{0.5}
+\setcounter{totalnumber}{50}
+\setcounter{topnumber}{50}
+\setcounter{bottomnumber}{50}
+% end floats for footnotes
+% some commands, that could be overwritten in the style file.
+\newcommand{\rubric}[1]{\subsection*{~\hfill {\it #1} \hfill ~}}
+\newcommand{\titlereference}[1]{\textsl{#1}}
+% end of "some commands"
+\title{The Grok Reference}
+\author{The grok team}
+\date{01/01/01}
+\hypersetup{
+pdftitle={The Grok Reference},
+pdfauthor={The grok team}
+}
+\raggedbottom
+\begin{document}
+\maketitle
+
+%___________________________________________________________________________
+\begin{center}
+\begin{tabularx}{\docinfowidth}{lX}
+\textbf{Release}: &
+	``0.10'' \\
+\end{tabularx}
+\end{center}
+
+\setlength{\locallinewidth}{\linewidth}
+
+%  
+\begin{quote}
+
+``Grok means to understand so thoroughly that the observer becomes a
+part of the observed -{}-{}- merge, blend, intermarry, lose identity in
+group experience. It means almost everything that we mean by religion,
+philosophy, and science -{}-{}- it means as little to us (because we are from
+Earth) as color means to a blind man.''
+
+\begin{flushright}
+---\titlereference{Robert A. Heinlein, Stranger in a Strange Land}
+\end{flushright}
+\end{quote}
+
+This is the grok reference documentation. It is organized by the Python
+artefacts that implement the concepts.
+
+Grok makes Zope 3 concepts more accessible for application
+developers. This reference is not intended as introductory material
+for those concepts. Please refer to the original Zope 3
+documentation and the grok tutorial for introductory material.
+\tableofcontents
+
+\bigskip
+
+
+%___________________________________________________________________________
+
+\chapter{Core}
+
+The \texttt{grok} module defines a few functions to interact with grok itself.
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.grok} -{}- Grok a package or module}
+\begin{funcdesc}{grok.grok}{dotted{\_}name}
+Grokking a package or module activates the contained
+components(like models, views, adapters, templates, etc.) and
+registers them with Zope 3's component architecture.
+
+The \titlereference{dotted{\_}name} must specify either a Python module or package
+that is available from the current PYTHONPATH.
+
+Grokking a module:
+\begin{enumerate}
+\item { 
+Scan the module for known components: models, adapters, utilities, views,
+traversers, templates and subscribers.
+}
+
+\item { 
+Check whether a directory with file system templates exists
+(\texttt{<modulename>{\_}templates}).  If it exists, load the file
+system templates into the template registry for this module.
+}
+
+\item { 
+Determine the module context.
+}
+
+\item { 
+Register all components with the Zope 3 component architecture.
+}
+
+\item { 
+Initialize schemata for registered models
+}
+
+\end{enumerate}
+
+Grokking a package:
+\begin{enumerate}
+\item { 
+Grok the package as a module.
+}
+
+\item { 
+Check for a static resource directory (\texttt{static}) and
+register it if it exists.
+}
+
+\item { 
+Recursively grok all sub-modules and sub-packages.
+}
+
+\end{enumerate}
+\end{funcdesc}
+Grokking a module:
+
+\begin{enumerate}
+
+    \item Scan the module for known components: models, adapters,
+          utilities, views, traversers, templates and subscribers.
+
+    \item Check whether a directory with file system templates
+          exists (\file{<modulename>_templates}).  If it exists,
+          load the file system templates into the template
+          registry for this module.
+
+    \item Determine the module context.
+
+    \item Register all components with the Zope 3 component architecture.
+
+    \item Initialize schemata for registered models
+
+\end{enumerate}
+
+Grokking a module:
+
+\begin{enumerate}
+
+    \item {
+Scan the module for known components: models, adapters,
+utilities, views, traversers, templates and subscribers.
+}
+
+    \item Check whether a directory with file system templates
+          exists (\file{<modulename>_templates}).  If it exists,
+          load the file system templates into the template
+          registry for this module.
+
+    \item Determine the module context.
+
+    \item Register all components with the Zope 3 component architecture.
+
+    \item Initialize schemata for registered models
+
+\end{enumerate}
+
+\begin{note}
+\end{note}%  
+
+
+%___________________________________________________________________________
+
+\chapter{Components}
+
+The \texttt{grok} module defines a set of components that provide basic Zope 3
+functionality in a convenient way.
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.Adapter}}
+
+Implementation, configuration, and registration of Zope 3 adapters.
+\begin{classdesc*}{grok.Adapter}
+Base class to define an adapter. Adapters are automatically registered when a
+module is ``grokked''.
+\begin{memberdesc}{context}
+The adapted object.
+\end{memberdesc}
+
+\textbf{Directives:}
+\begin{description}
+%[visit_definition_list_item]
+\item[{\texttt{grok.context(context{\_}obj{\_}or{\_}interface)}}] %[visit_definition]
+
+May be required. Identifies the type of objects or interface for the adaptation.
+
+If Grok can determine a context for adaptation from the module, this directive
+can be omitted. If the automatically determined context is not correct, or if no
+context can be derived from the module the directive is required.
+
+%[depart_definition]
+%[depart_definition_list_item]
+%[visit_definition_list_item]
+\item[{\texttt{grok.implements(*interfaces)}}] %[visit_definition]
+
+Required. Identifies the interface(s) the adapter implements.
+
+%[depart_definition]
+%[depart_definition_list_item]
+%[visit_definition_list_item]
+\item[{\texttt{grok.name(name)}}] %[visit_definition]
+
+Optional. Identifies the name used for the adapter registration. If ommitted, no
+name will be used.
+
+When a name is used for the adapter registration, the adapter can only be
+retrieved by explicitely using its name.
+
+%[depart_definition]
+%[depart_definition_list_item]
+%[visit_definition_list_item]
+\item[{\texttt{grok.provides(name)}}] %[visit_definition]
+
+Maybe required. If the adapter implements more than one interface,
+\texttt{grok.provides} is required to disambiguate for what interface the adapter
+will be registered.
+
+%[depart_definition]
+%[depart_definition_list_item]
+\end{description}
+
+\textbf{Example:}
+\begin{quote}\begin{verbatim}
+import grok
+from zope import interface
+
+class Cave(grok.Model):
+    pass
+
+class IHome(interface.Interface):
+    pass
+
+class Home(grok.Adapter):
+    grok.implements(IHome)
+
+home = IHome(cave)
+\end{verbatim}\end{quote}
+
+\textbf{Example 2:}
+\begin{quote}\begin{verbatim}
+import grok
+from zope import interface
+
+class Cave(grok.Model):
+    pass
+
+class IHome(interface.Interface):
+    pass
+
+class Home(grok.Adapter):
+    grok.implements(IHome)
+    grok.name('home')
+
+from zope.component import getAdapter
+home = getAdapter(cave, IHome, name='home')
+\end{verbatim}\end{quote}
+\end{classdesc*}
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.AddForm}}
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.Annotation}}
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.Application}}
+
+
+%___________________________________________________________________________
+
+\section{grok.ClassGrokker}
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.Container}}
+\begin{classdesc*}{grok.Container}
+Mixin base class to define a container object. The container implements the
+zope.app.container.interfaces.IContainer interface using a BTree, providing
+reasonable performance for large collections of objects.
+\end{classdesc*}
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.DisplayForm}}
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.EditForm}}
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.Form}}
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.GlobalUtility}}
+\begin{classdesc*}{grok.GlobalUtility}
+Base class to define a globally registered utility. Global utilities are
+automatically registered when a module is ``grokked''.
+
+\textbf{Directives:}
+\begin{description}
+%[visit_definition_list_item]
+\item[{\texttt{grok.implements(*interfaces)}}] %[visit_definition]
+
+Required. Identifies the interfaces(s) the utility implements.
+
+%[depart_definition]
+%[depart_definition_list_item]
+%[visit_definition_list_item]
+\item[{\texttt{grok.name(name)}}] %[visit_definition]
+
+Optional. Identifies the name used for the adapter registration. If ommitted, no
+name will be used.
+
+When a name is used for the global utility registration, the global utility can
+only be retrieved by explicitely using its name.
+
+%[depart_definition]
+%[depart_definition_list_item]
+%[visit_definition_list_item]
+\item[{\texttt{grok.provides(name)}}] %[visit_definition]
+
+Maybe required. If the global utility implements more than one interface,
+\texttt{grok.provides} is required to disambiguate for what interface the global
+utility will be registered.
+
+%[depart_definition]
+%[depart_definition_list_item]
+\end{description}
+\end{classdesc*}
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.Indexes}}
+
+
+%___________________________________________________________________________
+
+\section{grok.InstanceGrokker}
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.JSON}}
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.LocalUtility}}
+\begin{classdesc*}{grok.LocalUtility}
+Base class to define a utility that will be registered local to a
+\texttt{grok.Site} or \texttt{grok.Application} object by using the
+\texttt{grok.local{\_}utility} directive.
+
+\textbf{Directives:}
+\begin{description}
+%[visit_definition_list_item]
+\item[{\texttt{grok.implements(*interfaces)}}] %[visit_definition]
+
+Optional. Identifies the interfaces(s) the utility implements.
+
+%[depart_definition]
+%[depart_definition_list_item]
+%[visit_definition_list_item]
+\item[{\texttt{grok.name(name)}}] %[visit_definition]
+
+Optional. Identifies the name used for the adapter registration. If ommitted, no
+name will be used.
+
+When a name is used for the local utility registration, the local utility can
+only be retrieved by explicitely using its name.
+
+%[depart_definition]
+%[depart_definition_list_item]
+%[visit_definition_list_item]
+\item[{\texttt{grok.provides(name)}}] %[visit_definition]
+
+Maybe required. If the local utility implements more than one interface or if
+the implemented interface cannot be determined, \texttt{grok.provides} is
+required to disambiguate for what interface the local utility will be
+registered.
+
+%[depart_definition]
+%[depart_definition_list_item]
+\end{description}
+\end{classdesc*}
+\begin{seealso}
+
+Local utilities need to be registered in the context of \texttt{grok.Site} or
+\texttt{grok.Application} using the \texttt{grok.local{\_}utility} directive.
+\end{seealso}
+
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.Model}}
+
+Base class to define an application ``content'' or model object. Model objects
+provide persistence and containment.
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.ModuleGrokker}}
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.MultiAdapter}}
+\begin{classdesc*}{grok.MultiAdapter}
+Base class to define a multi adapter. MultiAdapters are automatically registered
+when a module is ``grokked''.
+
+\textbf{Directives:}
+\begin{description}
+%[visit_definition_list_item]
+\item[{\texttt{grok.adapts(*objects{\_}or{\_}interfaces)}}] %[visit_definition]
+
+Required. Identifies the combination of types of objects or interfaces for the
+adaptation.
+
+%[depart_definition]
+%[depart_definition_list_item]
+%[visit_definition_list_item]
+\item[{\texttt{grok.implements(*interfaces)}}] %[visit_definition]
+
+Required. Identifies the interfaces(s) the adapter implements.
+
+%[depart_definition]
+%[depart_definition_list_item]
+%[visit_definition_list_item]
+\item[{\texttt{grok.name(name)}}] %[visit_definition]
+
+Optional. Identifies the name used for the adapter registration. If ommitted, no
+name will be used.
+
+When a name is used for the adapter registration, the adapter can only be
+retrieved by explicitely using its name.
+
+%[depart_definition]
+%[depart_definition_list_item]
+%[visit_definition_list_item]
+\item[{\texttt{grok.provides(name)}}] %[visit_definition]
+
+Maybe required. If the adapter implements more than one interface,
+\texttt{grok.provides} is required to disambiguate for what interface the adapter
+will be registered.
+
+%[depart_definition]
+%[depart_definition_list_item]
+\end{description}
+\end{classdesc*}
+
+\textbf{Example:}
+\begin{quote}\begin{verbatim}
+import grok
+from zope import interface
+
+class Fireplace(grok.Model):
+    pass
+
+class Cave(grok.Model):
+    pass
+
+class IHome(interface.Interface):
+    pass
+
+class Home(grok.MultiAdapter):
+    grok.adapts(Cave, Fireplace)
+    grok.implements(IHome)
+
+    def __init__(self, cave, fireplace):
+        self.cave = cave
+        self.fireplace = fireplace
+
+home = IHome(cave, fireplace)
+\end{verbatim}\end{quote}
+
+
+%___________________________________________________________________________
+
+\section{grok.PageTemplate}
+
+
+%___________________________________________________________________________
+
+\section{grok.PageTemplateFile}
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.Site}}
+
+Base class to define an site object. Site objects provide persistence and
+containment.
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.Traverser}}
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.View}}
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.XMLRPC}}
+
+
+%___________________________________________________________________________
+
+\chapter{Directives}
+
+The \texttt{grok} module defines a set of directives that allow you to configure
+and register your components. Most directives assume a default, based on the
+environment of a module. (For example, a view will be automatically associated
+with a model if the association can be made unambigously.)
+
+If no default can be assumed for a value, grok will explicitly tell you what is
+missing and how you can provide a default or explicit assignment for the value
+in question.
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.AutoFields} -{}- Deduce schema fields automatically}
+\begin{funcdesc}{grok.AutoFields}{class{\_}or{\_}interface}
+A class level directive, which can be used inside \texttt{Form}
+classes to automatically deduce the form fields from the schema of
+the context \titlereference{class{\_}or{\_}interface}.
+
+Different to most other directives, \texttt{grok.AutoFields} is used
+more like a function and less like a pure declaration.
+
+The following example makes use of the \texttt{grok.AutoFields}
+directive, in that one field is omitted from the form before
+rendering:
+\end{funcdesc}
+
+\textbf{Example:}
+\begin{quote}\begin{verbatim}
+import grok
+from zope import interface, schema
+
+class IMammoth(interface.Interface):
+    name = schema.TextLine(title=u"Name")
+    size = schema.TextLine(title=u"Size", default=u"Quite normal")
+
+class Mammoth(grok.Model):
+    interface.implements(IMammoth)
+
+class Edit(grok.EditForm):
+    grok.context(Mammoth)
+
+    form_fields = grok.AutoFields(Mammoth).omit('size')
+\end{verbatim}\end{quote}
+
+In this example the \texttt{size} attribute will not show up in the
+resulting edit view.
+\begin{seealso}
+
+\texttt{grok.EditForm}, \texttt{grok.Fields}
+\end{seealso}
+
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.adapts} -{}- Declare that a class adapts certain objects}
+\begin{funcdesc}{grok.adapts}{*classes{\_}or{\_}interfaces}
+A class-level directive to declare that a class adapts objects of
+the classes or interfaces given in \titlereference{*classes{\_}or{\_}interfaces}.
+
+This directive accepts several arguments.
+
+It works much like the \texttt{zope.component}s \texttt{adapts()},
+but you do not have to make a ZCML entry to register the adapter.
+
+\textbf{Example:}
+\begin{quote}\begin{verbatim}
+import grok
+from zope import interface, schema
+from zope.size.interfaces import ISized
+
+class IMammoth(interface.Interface):
+    name = schema.TextLine(title=u"Name")
+    size = schema.TextLine(title=u"Size", default=u"Quite normal")
+
+class Mammoth(grok.Model):
+    interface.implements(IMammoth)
+
+class MammothSize(object):
+    grok.implements(ISized)
+    grok.adapts(IMammoth)
+
+    def __init__(self, context):
+        self.context = context
+
+    def sizeForSorting(self):
+        return ('byte', 1000)
+
+    def sizeForDisplay(self):
+        return ('1000 bytes')
+\end{verbatim}\end{quote}
+
+Having \texttt{MammothSize} available, you can register it as an adapter,
+without a single line of ZCML:
+\begin{quote}\begin{verbatim}
+>>> manfred = Mammoth()
+>>> from zope.component import provideAdapter
+>>> provideAdapter(MammothSize)
+>>> from zope.size.interfaces import ISized
+>>> size = ISized(manfred)
+>>> size.sizeForDisplay()
+'1000 bytes'
+\end{verbatim}\end{quote}
+\begin{seealso}
+
+\texttt{grok.implements}
+\end{seealso}
+
+\end{funcdesc}
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.baseclass} -{}- declare a class as base}
+\begin{funcdesc}{grok.baseclass}{}
+A class-level directive without argument to mark something as a
+base class. Base classes are are not grokked.
+
+Another way to indicate that something is a base class, is by
+postfixing the classname with \texttt{'Base'}.
+
+The baseclass mark is not inherited by subclasses, so those
+subclasses will be grokked (except they are explicitly declared as
+baseclasses as well).
+
+\textbf{Example:}
+\begin{quote}\begin{verbatim}
+import grok
+
+class ModelBase(grok.Model):
+    pass
+
+class ViewBase(grok.View):
+    def render(self):
+        return "hello world"
+
+class AnotherView(grok.View):
+    grok.baseclass()
+
+    def render(self):
+        return "hello world"
+
+class WorkingView(grok.View):
+    pass
+\end{verbatim}\end{quote}
+
+Using this example, only the \texttt{WorkingView} will serve as a
+view, while calling the \texttt{ViewBase} or \texttt{AnotherView}
+will lead to a \texttt{ComponentLookupError}.
+\end{funcdesc}
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.define{\_}permission} -{}- define a permission}
+\begin{funcdesc}{grok.define{\_}permission}{name}
+A module-level directive to define a permission with name
+\titlereference{name}. Usually permission names are prefixed by a component- or
+application name and a dot to keep them unique.
+
+Because in Grok by default everything is accessible by everybody,
+it is important to define permissions, which restrict access to
+certain principals or roles.
+
+\textbf{Example:}
+\begin{quote}\begin{verbatim}
+import grok
+grok.define_permission('cave.enter')
+\end{verbatim}\end{quote}
+\begin{seealso}
+
+\texttt{grok.require}, \texttt{grok.Permission}, \texttt{grok.Role}
+\end{seealso}
+
+\end{funcdesc}
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.Fields} -{}- declare schema fields of a form}
+\begin{funcdesc}{grok.Fields}{**schemas}
+A class level directive, which can be used inside \texttt{grok.Form}
+classes.
+
+A \texttt{grok.Fields} can receive keyword parameters with schema
+fields. These should be available in the definition order.
+
+\textbf{Example:}
+\begin{quote}\begin{verbatim}
+import grok
+from zope import schema
+
+class Mammoth(grok.Model):
+    pass
+
+class Edit(grok.EditForm):
+    fields = grok.Fields(
+        b = schema.TextLine(title=u"Beta"),
+        a = schema.TextLine(title=u"Alpha"),
+\end{verbatim}\end{quote}
+
+Given the above code, when the \texttt{Edit} form is rendered, the
+\texttt{Textlines} \titlereference{b} and \titlereference{a} will appear as input fields in that
+order. This is due to the fact, that by default the \titlereference{fields}
+variable is taken into account, when rendering forms.
+\begin{seealso}
+
+\texttt{grok.AutoFields}, \texttt{grok.Form}
+\end{seealso}
+
+\end{funcdesc}
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.implements} -{}- indicate, that a class implements an interface}
+\begin{funcdesc}{grok.implements}{*interfaces}
+A class level directive to declare one or more \titlereference{interfaces}, as
+implementers of the surrounding class. This directive allows
+several parameters.
+
+\texttt{grok.implements} is currently an alias for
+\texttt{zope.interface.implements}.
+
+\textbf{Example:}
+\begin{quote}\begin{verbatim}
+>>> import grok
+>>> from zope import interface
+>>> class IPaintable(interface.Interface):
+...   pass
+...
+>>> class Cave(object):
+...   pass
+...
+>>> cave = Cave()
+>>> IPaintable.providedBy(cave)
+False
+>>> class PaintableCave(object):
+...   grok.implements(IPaintable)
+...
+>>> cave = PaintableCave()
+>>> IPaintable.providedBy(cave)
+True
+\end{verbatim}\end{quote}
+\end{funcdesc}
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.context} -{}- Declare the context for views, adapters, etc.}
+\begin{funcdesc}{grok.context}{*class{\_}or{\_}interface}
+A class or module level directive to indicate the context for
+something (class or module) in the same scope. When used on module
+level, it will set the context for all views, adapters, etc. in
+that module. When used on class level, it will set the context for
+that particular class.
+
+With Grok contexts are set automatically for some objects, if they
+are unambigous. For example a \texttt{grok.View} will get the only
+\texttt{grok.Application} or \texttt{grok.Model} class as context,
+iff there exists exactly one in the same module. If there are more
+possible contexts or you want to set a type (class/interface) from
+another module as context, than the one choosen by default, then
+you have to call \texttt{grok.context} explicitly.
+
+\textbf{Example:}
+
+Here the \texttt{grok.context} directive indicates, that
+\texttt{Mammoth} instances will be the context of \texttt{Index}
+views (and not instances of \texttt{Cave})
+\begin{quote}\begin{verbatim}
+import grok
+
+class Mammoth(grok.Model):
+    pass
+
+class Cave(grok.Model):
+    pass
+
+class Index(grok.View):
+    grok.context(Mammoth)
+\end{verbatim}\end{quote}
+\begin{seealso}
+
+\texttt{grok.View}, \texttt{grok.Adapter}, \texttt{grok.MultiAdapter}
+\end{seealso}
+
+\end{funcdesc}
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.global{\_}utility} -{}- register a global utility}
+\begin{funcdesc}{grok.global{\_}utility}{factory}
+A module level directive to register a global utility.
+
+\titlereference{factory} - the factory that creates the utility.
+
+\titlereference{provides} - the interface the utility should be looked up with.
+
+\titlereference{name} - the name of the utility.
+
+The latter two parameters are optional.
+
+To register the utility correctly, Grok must be able to identify an
+interface provided by the utility. If none is given, Grok checks
+whether (exactly) one interface is implemented by the factory to be
+registered (see example below). If more than one interface is
+implemented by a class, use \texttt{grok.provides} to specify which
+one to use. If no interface is implemented by the instances
+delivered by the factory, use \texttt{grok.implements} to specify
+one.
+
+Another way to register global utilities with Grok is to subclass
+from \texttt{grok.GlobalUtility}.
+
+\textbf{Example:}
+\begin{quote}
+
+Given the following module code:
+\begin{quote}\begin{verbatim}
+import grok
+from zope import interface
+
+class IFireplace(interface.Interface):
+    pass
+
+class Fireplace(object):
+    grok.implements(IFireplace)
+
+grok.global_utility(Fireplace)
+grok.global_utility(Fireplace, name='hot')
+\end{verbatim}\end{quote}
+
+Then the following works:
+\begin{quote}\begin{verbatim}
+>>> from zope import component
+>>> fireplace = component.getUtility(IFireplace)
+>>> IFireplace.providedBy(fireplace)
+True
+>>> isinstance(fireplace, Fireplace)
+True
+
+>>> fireplace = component.getUtility(IFireplace, name='hot')
+>>> IFireplace.providedBy(fireplace)
+True
+>>> isinstance(fireplace, Fireplace)
+True
+\end{verbatim}\end{quote}
+\end{quote}
+\begin{seealso}
+
+\texttt{grok.GlobalUtility}, \texttt{grok.provides},
+\texttt{grok.implements}
+\end{seealso}
+
+\end{funcdesc}
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.name} -{}- associate a component with a name}
+\begin{funcdesc}{grok.name}{name}
+A class level directive used to associate a component with a single
+name \titlereference{name}. Typically this directive is optional. The default behaviour
+when no name is given depends on the component. The same applies to
+the semantics of this directive: for what exactly a name is set
+when using this directive, depends on the component.
+
+\textbf{Example:}
+\begin{quote}\begin{verbatim}
+import grok
+
+class Mammoth(grok.Model):
+   pass
+
+class Index(grok.View):
+   grok.name('index')
+\end{verbatim}\end{quote}
+\begin{seealso}
+
+\texttt{grok.Adapter}, \texttt{grok.Annotation},
+\texttt{grok.GlobalUtility}, \texttt{grok.Indexes},
+\texttt{grok.MultiAdapter}, \texttt{grok.Role},
+\texttt{grok.View}
+\end{seealso}
+
+\end{funcdesc}
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.local{\_}utility} -{}- register a local utility}
+\begin{funcdesc}{grok.local{\_}utility}{factory}
+A class level directive to register a local utility.
+
+\titlereference{factory} -{}- the factory that creates the utility.
+
+\titlereference{provides} -{}- the interface the utility should be looked up with.
+
+\titlereference{name} -{}- the name of the utility.
+\begin{description}
+%[visit_definition_list_item]
+\item[{\titlereference{setup} -{}- a callable that receives the utility as its single}] %[visit_definition]
+
+argument, it is called after the utility has been created and
+stored.
+
+%[depart_definition]
+%[depart_definition_list_item]
+%[visit_definition_list_item]
+\item[{\titlereference{public} -{}- if \titlereference{False}, the utility will be stored below}] %[visit_definition]
+
+\titlereference{++etc++site}.  If \titlereference{True}, the utility will be stored directly
+in the site.  The site should in this case be a container.
+
+%[depart_definition]
+%[depart_definition_list_item]
+\end{description}
+
+\titlereference{name{\_}in{\_}container} -{}- the name to use for storing the utility.
+
+All but the first parameter are optional.
+
+To register a local utility correctly, Grok must know about the
+interface, the utility should be looked up with. If none is given,
+Grok looks up any interfaces implemented by instances delivered by
+\titlereference{factory} and if exactly one can be found, it is taken. See
+\texttt{grok.global{\_}utility}.
+
+Every single combination of interfaces and names can only be
+registered once per module.
+
+It is not possible to declare a local utility as public, if the
+site is not a container. Grok will remind you of this. To store a
+utility in a container, a \titlereference{name{\_}in{\_}container} is needed. If
+none is given, Grok will make up one automatically.
+
+An alternative way to define a local utility is to subclass from
+\texttt{grok.LocalUtility}.
+
+\textbf{Example:}
+\begin{quote}
+
+The following code registers a local unnamed utility \titlereference{fireplace} in
+instances of \texttt{Cave}
+\begin{quote}\begin{verbatim}
+import grok
+from zope import interface
+
+class IFireplace(interface.Interface):
+    pass
+
+class Fireplace(grok.LocalUtility):
+    grok.implements(IFireplace)
+
+class Cave(grok.Container, grok.Site):
+    grok.local_utility(Fireplace, public=True,
+                       name_in_container='fireplace')
+\end{verbatim}\end{quote}
+\end{quote}
+\begin{seealso}
+
+\texttt{grok.global{\_}utility}, \texttt{grok.LocalUtility}
+\end{seealso}
+
+\end{funcdesc}
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.provides}}
+\begin{funcdesc}{grok.provides}{*arg}
+foobar
+\end{funcdesc}
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.resourcedir -{}-{}- XXX Not implemented yet}}
+\begin{funcdesc}{grok.resourcedir}{*arg}
+foobar
+
+Resource directories are used to embed static resources like HTML-,
+JavaScript-, CSS- and other files in your application.
+
+XXX insert directive description here (first: define the name,
+second: describe the default behaviour if the directive isn't
+given)
+
+A resource directory is created when a package contains a directory
+with the name \texttt{static}. All files from this directory become
+accessible from a browser under the URL
+\texttt{http://<servername>/++resource++<packagename>/<filename>}.
+
+\textbf{Example:}
+
+The package \texttt{a.b.c} is grokked and contains a directory
+\texttt{static} which contains the file \texttt{example.css}. The
+stylesheet will be available via
+\texttt{http://<servername>/++resource++a.b.c/example.css}.
+\end{funcdesc}
+\begin{center}\begin{sffamily}
+\fbox{\parbox{\admonitionwidth}{
+\textbf{\large Note}
+\vspace{2mm}
+
+A package can never have both a \texttt{static} directory and a
+Python module with the name \texttt{static.py} at the same
+time. grok will remind you of this conflict when grokking a package
+by displaying an error message.
+}}
+\end{sffamily}
+\end{center}
+
+
+%___________________________________________________________________________
+
+\subsection{Linking to resources from templates}
+
+grok provides a convenient way to calculate the URLs to static
+resource using the keyword \texttt{static} in page templates:
+\begin{quote}\begin{verbatim}
+<link rel="stylesheet" tal:attributes="href static/example.css" type="text/css">
+\end{verbatim}\end{quote}
+
+The keyword \texttt{static} will be replaced by the reference to
+the resource directory for the package in which the template was
+registered.
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.require}}
+\begin{funcdesc}{grok.require}{*arg}
+foobar
+\end{funcdesc}
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.site}}
+\begin{funcdesc}{grok.site}{*arg}
+foobar
+\end{funcdesc}
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.template}}
+\begin{funcdesc}{grok.template}{*arg}
+foobar
+\end{funcdesc}
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.templatedir}}
+\begin{funcdesc}{grok.templatedir}{*arg}
+foobar
+\end{funcdesc}
+
+
+%___________________________________________________________________________
+
+\section{\texttt{grok.title}}
+\begin{funcdesc}{grok.title}{*arg}
+foobar
+\end{funcdesc}
+
+
+%___________________________________________________________________________
+
+\section{A First Chapter}
+
+This is a first paragraph.
+\begin{quote}
+
+``Grok means to understand so thoroughly that the observer becomes a
+part of the observed -{}-{}- merge, blend, intermarry, lose identity in
+group experience. It means almost everything that we mean by religion,
+philosophy, and science -{}-{}- it means as little to us (because we are from
+Earth) as color means to a blind man.''
+
+\begin{flushright}
+---\titlereference{Robert A. Heinlein, Stranger in a Strange Land}
+\end{flushright}
+\end{quote}
+
+
+%___________________________________________________________________________
+
+\section{Another Chapter}
+
+This is another chapter.
+
+
+%___________________________________________________________________________
+
+\section{An external chapter}
+
+This is an external chapter.
+
+\end{document}

Added: Sandbox/ulif/grok-reference-with-rest/doc/reference-new/reference.rst
===================================================================
--- Sandbox/ulif/grok-reference-with-rest/doc/reference-new/reference.rst	                        (rev 0)
+++ Sandbox/ulif/grok-reference-with-rest/doc/reference-new/reference.rst	2007-10-01 05:51:41 UTC (rev 80434)
@@ -0,0 +1,36 @@
+.. _reference-index:
+
+#################################
+  Grok reference
+#################################
+
+:Release: |version|
+:Date: |today|
+
+   Grok means to understand so thoroughly that the observer becomes a part
+   of the observed -- merge, blend, intermarry, lose identity in group
+   experience. It means almost everything that we mean by religion,
+   philosophy, and science -- it means as little to us (because we are from
+   Earth) as color means to a blind man. -- `Robert A. Heinlein, Stranger in
+   a Strange Land`
+
+
+This is the grok reference documentation. It is organized by the Python
+artefacts that implement the concepts.
+
+Grok makes Zope 3 concepts more accessible for application developers. This
+reference is not intended as introductory material for those concepts. Please
+refer to the original Zope 3 documentation and the grok tutorial for
+introductory material.
+
+
+.. toctree::
+   :maxdepth: 2
+
+   core.rst
+   components.rst
+   directives.rst
+   decorators.rst
+   functions.rst
+   events.rst
+   exceptions.rst

Added: Sandbox/ulif/grok-reference-with-rest/doc/reference-new/rst2html
===================================================================
--- Sandbox/ulif/grok-reference-with-rest/doc/reference-new/rst2html	                        (rev 0)
+++ Sandbox/ulif/grok-reference-with-rest/doc/reference-new/rst2html	2007-10-01 05:51:41 UTC (rev 80434)
@@ -0,0 +1,25 @@
+#!/usr/bin/python
+
+# Author: David Goodger
+# Contact: goodger at python.org
+# Revision: $Revision$
+# Date: $Date$
+# Copyright: This module has been placed in the public domain.
+
+"""
+A minimal front end to the Docutils Publisher, producing HTML.
+"""
+
+try:
+    import locale
+    locale.setlocale(locale.LC_ALL, '')
+except:
+    pass
+
+from docutils.core import publish_cmdline, default_description
+
+
+description = ('Generates (X)HTML documents from standalone reStructuredText '
+               'sources.  ' + default_description)
+
+publish_cmdline(writer_name='html', description=description)


Property changes on: Sandbox/ulif/grok-reference-with-rest/doc/reference-new/rst2html
___________________________________________________________________
Name: svn:executable
   + *

Added: Sandbox/ulif/grok-reference-with-rest/doc/reference-new/rst2html.py
===================================================================
--- Sandbox/ulif/grok-reference-with-rest/doc/reference-new/rst2html.py	                        (rev 0)
+++ Sandbox/ulif/grok-reference-with-rest/doc/reference-new/rst2html.py	2007-10-01 05:51:41 UTC (rev 80434)
@@ -0,0 +1,5 @@
+#!/usr/bin/python2.4
+# EASY-INSTALL-SCRIPT: 'docutils==0.4','rst2html.py'
+__requires__ = 'docutils==0.4'
+import pkg_resources
+pkg_resources.run_script('docutils==0.4', 'rst2html.py')


Property changes on: Sandbox/ulif/grok-reference-with-rest/doc/reference-new/rst2html.py
___________________________________________________________________
Name: svn:executable
   + *

Added: Sandbox/ulif/grok-reference-with-rest/doc/reference-new/rst2manual.py
===================================================================
--- Sandbox/ulif/grok-reference-with-rest/doc/reference-new/rst2manual.py	                        (rev 0)
+++ Sandbox/ulif/grok-reference-with-rest/doc/reference-new/rst2manual.py	2007-10-01 05:51:41 UTC (rev 80434)
@@ -0,0 +1,41 @@
+#!/usr/bin/python
+
+# Author: David Goodger
+# Contact: goodger at users.sourceforge.net
+# Revision: $Revision$
+# Date: $Date$
+# Copyright: This module has been placed in the public domain.
+
+"""
+A minimal front end to the Docutils Publisher, producing LaTeX.
+"""
+
+try:
+    import locale
+    locale.setlocale(locale.LC_ALL, '')
+except:
+    pass
+
+
+from docutils.core import publish_cmdline, default_description
+import latex_manual
+import latex_manual.roles
+import latex_manual.directives
+
+class Environment(object):
+    currmodlue = None
+
+env = Environment()
+
+#import latex_manual.addnodes
+
+#env.currmodule = ''
+
+description = ('Generates LaTeX documents from standalone reStructuredText '
+               'sources.  ' + default_description)
+
+publish_cmdline(writer_name='latex_manual', description=description)
+
+
+
+


Property changes on: Sandbox/ulif/grok-reference-with-rest/doc/reference-new/rst2manual.py
___________________________________________________________________
Name: svn:executable
   + *



More information about the Checkins mailing list