Skip to content

Commit ecc53e9

Browse files
committed
dded docutils library to allow RST to HTML transformation. See ietf-tools#908
- Legacy-Id: 5076
1 parent cffa96c commit ecc53e9

175 files changed

Lines changed: 44369 additions & 0 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

docutils/__init__.py

Lines changed: 214 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,214 @@
1+
# $Id: __init__.py 7446 2012-06-17 20:47:10Z grubert $
2+
# Author: David Goodger <goodger@python.org>
3+
# Copyright: This module has been placed in the public domain.
4+
5+
"""
6+
This is the Docutils (Python Documentation Utilities) package.
7+
8+
Package Structure
9+
=================
10+
11+
Modules:
12+
13+
- __init__.py: Contains component base classes, exception classes, and
14+
Docutils version information.
15+
16+
- core.py: Contains the ``Publisher`` class and ``publish_*()`` convenience
17+
functions.
18+
19+
- frontend.py: Runtime settings (command-line interface, configuration files)
20+
processing, for Docutils front-ends.
21+
22+
- io.py: Provides a uniform API for low-level input and output.
23+
24+
- nodes.py: Docutils document tree (doctree) node class library.
25+
26+
- statemachine.py: A finite state machine specialized for
27+
regular-expression-based text filters.
28+
29+
- urischemes.py: Contains a complete mapping of known URI addressing
30+
scheme names to descriptions.
31+
32+
Subpackages:
33+
34+
- languages: Language-specific mappings of terms.
35+
36+
- parsers: Syntax-specific input parser modules or packages.
37+
38+
- readers: Context-specific input handlers which understand the data
39+
source and manage a parser.
40+
41+
- transforms: Modules used by readers and writers to modify DPS
42+
doctrees.
43+
44+
- utils: Contains the ``Reporter`` system warning class and miscellaneous
45+
utilities used by readers, writers, and transforms.
46+
47+
- writers: Format-specific output translators.
48+
"""
49+
50+
__docformat__ = 'reStructuredText'
51+
52+
__version__ = '0.9.1'
53+
"""``major.minor.micro`` version number. The micro number is bumped for API
54+
changes, for new functionality, and for interim project releases. The minor
55+
number is bumped whenever there is a significant project release. The major
56+
number will be bumped when the project is feature-complete, and perhaps if
57+
there is a major change in the design."""
58+
59+
__version_details__ = 'release'
60+
"""Extra version details (e.g. 'snapshot 2005-05-29, r3410', 'repository',
61+
'release'), modified automatically & manually."""
62+
63+
import sys
64+
65+
class ApplicationError(StandardError):
66+
# Workaround:
67+
# In Python < 2.6, unicode(<exception instance>) calls `str` on the
68+
# arg and therefore, e.g., unicode(StandardError(u'\u234')) fails
69+
# with UnicodeDecodeError.
70+
if sys.version_info < (2,6):
71+
def __unicode__(self):
72+
return u', '.join(self.args)
73+
74+
class DataError(ApplicationError): pass
75+
76+
77+
class SettingsSpec:
78+
79+
"""
80+
Runtime setting specification base class.
81+
82+
SettingsSpec subclass objects used by `docutils.frontend.OptionParser`.
83+
"""
84+
85+
settings_spec = ()
86+
"""Runtime settings specification. Override in subclasses.
87+
88+
Defines runtime settings and associated command-line options, as used by
89+
`docutils.frontend.OptionParser`. This is a tuple of:
90+
91+
- Option group title (string or `None` which implies no group, just a list
92+
of single options).
93+
94+
- Description (string or `None`).
95+
96+
- A sequence of option tuples. Each consists of:
97+
98+
- Help text (string)
99+
100+
- List of option strings (e.g. ``['-Q', '--quux']``).
101+
102+
- Dictionary of keyword arguments sent to the OptionParser/OptionGroup
103+
``add_option`` method.
104+
105+
Runtime setting names are derived implicitly from long option names
106+
('--a-setting' becomes ``settings.a_setting``) or explicitly from the
107+
'dest' keyword argument.
108+
109+
Most settings will also have a 'validator' keyword & function. The
110+
validator function validates setting values (from configuration files
111+
and command-line option arguments) and converts them to appropriate
112+
types. For example, the ``docutils.frontend.validate_boolean``
113+
function, **required by all boolean settings**, converts true values
114+
('1', 'on', 'yes', and 'true') to 1 and false values ('0', 'off',
115+
'no', 'false', and '') to 0. Validators need only be set once per
116+
setting. See the `docutils.frontend.validate_*` functions.
117+
118+
See the optparse docs for more details.
119+
120+
- More triples of group title, description, options, as many times as
121+
needed. Thus, `settings_spec` tuples can be simply concatenated.
122+
"""
123+
124+
settings_defaults = None
125+
"""A dictionary of defaults for settings not in `settings_spec` (internal
126+
settings, intended to be inaccessible by command-line and config file).
127+
Override in subclasses."""
128+
129+
settings_default_overrides = None
130+
"""A dictionary of auxiliary defaults, to override defaults for settings
131+
defined in other components. Override in subclasses."""
132+
133+
relative_path_settings = ()
134+
"""Settings containing filesystem paths. Override in subclasses.
135+
Settings listed here are to be interpreted relative to the current working
136+
directory."""
137+
138+
config_section = None
139+
"""The name of the config file section specific to this component
140+
(lowercase, no brackets). Override in subclasses."""
141+
142+
config_section_dependencies = None
143+
"""A list of names of config file sections that are to be applied before
144+
`config_section`, in order (from general to specific). In other words,
145+
the settings in `config_section` are to be overlaid on top of the settings
146+
from these sections. The "general" section is assumed implicitly.
147+
Override in subclasses."""
148+
149+
150+
class TransformSpec:
151+
152+
"""
153+
Runtime transform specification base class.
154+
155+
TransformSpec subclass objects used by `docutils.transforms.Transformer`.
156+
"""
157+
158+
def get_transforms(self):
159+
"""Transforms required by this class. Override in subclasses."""
160+
if self.default_transforms != ():
161+
import warnings
162+
warnings.warn('default_transforms attribute deprecated.\n'
163+
'Use get_transforms() method instead.',
164+
DeprecationWarning)
165+
return list(self.default_transforms)
166+
return []
167+
168+
# Deprecated; for compatibility.
169+
default_transforms = ()
170+
171+
unknown_reference_resolvers = ()
172+
"""List of functions to try to resolve unknown references. Unknown
173+
references have a 'refname' attribute which doesn't correspond to any
174+
target in the document. Called when the transforms in
175+
`docutils.tranforms.references` are unable to find a correct target. The
176+
list should contain functions which will try to resolve unknown
177+
references, with the following signature::
178+
179+
def reference_resolver(node):
180+
'''Returns boolean: true if resolved, false if not.'''
181+
182+
If the function is able to resolve the reference, it should also remove
183+
the 'refname' attribute and mark the node as resolved::
184+
185+
del node['refname']
186+
node.resolved = 1
187+
188+
Each function must have a "priority" attribute which will affect the order
189+
the unknown_reference_resolvers are run::
190+
191+
reference_resolver.priority = 100
192+
193+
Override in subclasses."""
194+
195+
196+
class Component(SettingsSpec, TransformSpec):
197+
198+
"""Base class for Docutils components."""
199+
200+
component_type = None
201+
"""Name of the component type ('reader', 'parser', 'writer'). Override in
202+
subclasses."""
203+
204+
supported = ()
205+
"""Names for this component. Override in subclasses."""
206+
207+
def supports(self, format):
208+
"""
209+
Is `format` supported by this component?
210+
211+
To be used by transforms to ask the dependent component if it supports
212+
a certain input context or output format.
213+
"""
214+
return format in self.supported

docutils/_compat.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# $Id: _compat.py 7316 2012-01-19 11:31:58Z milde $
2+
# Author: Georg Brandl <georg@python.org>
3+
# Copyright: This module has been placed in the public domain.
4+
5+
"""
6+
Python 2/3 compatibility definitions.
7+
8+
This module currently provides the following helper symbols:
9+
10+
* bytes (name of byte string type; str in 2.x, bytes in 3.x)
11+
* b (function converting a string literal to an ASCII byte string;
12+
can be also used to convert a Unicode string into a byte string)
13+
* u_prefix (unicode repr prefix: 'u' in 2.x, '' in 3.x)
14+
(Required in docutils/test/test_publisher.py)
15+
* BytesIO (a StringIO class that works with bytestrings)
16+
"""
17+
18+
import sys
19+
20+
if sys.version_info < (3,0):
21+
b = bytes = str
22+
u_prefix = 'u'
23+
from StringIO import StringIO as BytesIO
24+
else:
25+
import builtins
26+
bytes = builtins.bytes
27+
u_prefix = ''
28+
def b(s):
29+
if isinstance(s, str):
30+
return s.encode('latin1')
31+
elif isinstance(s, bytes):
32+
return s
33+
else:
34+
raise TypeError("Invalid argument %r for b()" % (s,))
35+
# using this hack since 2to3 "fixes" the relative import
36+
# when using ``from io import BytesIO``
37+
BytesIO = __import__('io').BytesIO
Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf8 -*-
3+
4+
# string_template_compat.py: string.Template for Python <= 2.4
5+
# =====================================================
6+
7+
# This is just an excerpt of the standard string module to provide backwards
8+
# compatibility.
9+
10+
import re as _re
11+
12+
class _multimap:
13+
"""Helper class for combining multiple mappings.
14+
15+
Used by .{safe_,}substitute() to combine the mapping and keyword
16+
arguments.
17+
"""
18+
def __init__(self, primary, secondary):
19+
self._primary = primary
20+
self._secondary = secondary
21+
22+
def __getitem__(self, key):
23+
try:
24+
return self._primary[key]
25+
except KeyError:
26+
return self._secondary[key]
27+
28+
29+
class _TemplateMetaclass(type):
30+
pattern = r"""
31+
%(delim)s(?:
32+
(?P<escaped>%(delim)s) | # Escape sequence of two delimiters
33+
(?P<named>%(id)s) | # delimiter and a Python identifier
34+
{(?P<braced>%(id)s)} | # delimiter and a braced identifier
35+
(?P<invalid>) # Other ill-formed delimiter exprs
36+
)
37+
"""
38+
39+
def __init__(cls, name, bases, dct):
40+
super(_TemplateMetaclass, cls).__init__(name, bases, dct)
41+
if 'pattern' in dct:
42+
pattern = cls.pattern
43+
else:
44+
pattern = _TemplateMetaclass.pattern % {
45+
'delim' : _re.escape(cls.delimiter),
46+
'id' : cls.idpattern,
47+
}
48+
cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE)
49+
50+
51+
class Template:
52+
"""A string class for supporting $-substitutions."""
53+
__metaclass__ = _TemplateMetaclass
54+
55+
delimiter = '$'
56+
idpattern = r'[_a-z][_a-z0-9]*'
57+
58+
def __init__(self, template):
59+
self.template = template
60+
61+
# Search for $$, $identifier, ${identifier}, and any bare $'s
62+
63+
def _invalid(self, mo):
64+
i = mo.start('invalid')
65+
lines = self.template[:i].splitlines(True)
66+
if not lines:
67+
colno = 1
68+
lineno = 1
69+
else:
70+
colno = i - len(''.join(lines[:-1]))
71+
lineno = len(lines)
72+
raise ValueError('Invalid placeholder in string: line %d, col %d' %
73+
(lineno, colno))
74+
75+
def substitute(self, *args, **kws):
76+
if len(args) > 1:
77+
raise TypeError('Too many positional arguments')
78+
if not args:
79+
mapping = kws
80+
elif kws:
81+
mapping = _multimap(kws, args[0])
82+
else:
83+
mapping = args[0]
84+
# Helper function for .sub()
85+
def convert(mo):
86+
# Check the most common path first.
87+
named = mo.group('named') or mo.group('braced')
88+
if named is not None:
89+
val = mapping[named]
90+
# We use this idiom instead of str() because the latter will
91+
# fail if val is a Unicode containing non-ASCII characters.
92+
return '%s' % (val,)
93+
if mo.group('escaped') is not None:
94+
return self.delimiter
95+
if mo.group('invalid') is not None:
96+
self._invalid(mo)
97+
raise ValueError('Unrecognized named group in pattern',
98+
self.pattern)
99+
return self.pattern.sub(convert, self.template)
100+
101+
def safe_substitute(self, *args, **kws):
102+
if len(args) > 1:
103+
raise TypeError('Too many positional arguments')
104+
if not args:
105+
mapping = kws
106+
elif kws:
107+
mapping = _multimap(kws, args[0])
108+
else:
109+
mapping = args[0]
110+
# Helper function for .sub()
111+
def convert(mo):
112+
named = mo.group('named')
113+
if named is not None:
114+
try:
115+
# We use this idiom instead of str() because the latter
116+
# will fail if val is a Unicode containing non-ASCII
117+
return '%s' % (mapping[named],)
118+
except KeyError:
119+
return self.delimiter + named
120+
braced = mo.group('braced')
121+
if braced is not None:
122+
try:
123+
return '%s' % (mapping[braced],)
124+
except KeyError:
125+
return self.delimiter + '{' + braced + '}'
126+
if mo.group('escaped') is not None:
127+
return self.delimiter
128+
if mo.group('invalid') is not None:
129+
return self.delimiter
130+
raise ValueError('Unrecognized named group in pattern',
131+
self.pattern)
132+
return self.pattern.sub(convert, self.template)
133+

0 commit comments

Comments
 (0)