~ubuntu-branches/ubuntu/jaunty/python-docutils/jaunty

« back to all changes in this revision

Viewing changes to docutils/parsers/rst/directives/__init__.py

  • Committer: Bazaar Package Importer
  • Author(s): Simon McVittie
  • Date: 2008-07-24 10:39:53 UTC
  • mfrom: (1.1.4 upstream) (3.1.7 intrepid)
  • Revision ID: james.westby@ubuntu.com-20080724103953-8gh4uezg17g9ysgy
Tags: 0.5-2
* Upload docutils 0.5 to unstable
* Update rst.el to upstream Subversion r5596, which apparently fixes
  all its performance problems (17_speed_up_rst_el.dpatch, closes: #474941)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Author: David Goodger
2
 
# Contact: goodger@python.org
3
 
# Revision: $Revision: 4229 $
4
 
# Date: $Date: 2005-12-23 00:46:16 +0100 (Fri, 23 Dec 2005) $
 
1
# $Id: __init__.py 4667 2006-07-12 21:40:56Z wiemann $
 
2
# Author: David Goodger <goodger@python.org>
5
3
# Copyright: This module has been placed in the public domain.
6
4
 
7
5
"""
8
6
This package contains directive implementation modules.
9
 
 
10
 
The interface for directive functions is as follows::
11
 
 
12
 
    def directive_fn(name, arguments, options, content, lineno,
13
 
                     content_offset, block_text, state, state_machine):
14
 
        code...
15
 
 
16
 
    # Set function attributes:
17
 
    directive_fn.arguments = ...
18
 
    directive_fn.options = ...
19
 
    direcitve_fn.content = ...
20
 
 
21
 
Parameters:
22
 
 
23
 
- ``name`` is the directive type or name (string).
24
 
 
25
 
- ``arguments`` is a list of positional arguments (strings).
26
 
 
27
 
- ``options`` is a dictionary mapping option names (strings) to values (type
28
 
  depends on option conversion functions; see below).
29
 
 
30
 
- ``content`` is a list of strings, the directive content.
31
 
 
32
 
- ``lineno`` is the line number of the first line of the directive.
33
 
 
34
 
- ``content_offset`` is the line offset of the first line of the content from
35
 
  the beginning of the current input.  Used when initiating a nested parse.
36
 
 
37
 
- ``block_text`` is a string containing the entire directive.  Include it as
38
 
  the content of a literal block in a system message if there is a problem.
39
 
 
40
 
- ``state`` is the state which called the directive function.
41
 
 
42
 
- ``state_machine`` is the state machine which controls the state which called
43
 
  the directive function.
44
 
 
45
 
Function attributes, interpreted by the directive parser (which calls the
46
 
directive function):
47
 
 
48
 
- ``arguments``: A 3-tuple specifying the expected positional arguments, or
49
 
  ``None`` if the directive has no arguments.  The 3 items in the tuple are
50
 
  ``(required, optional, whitespace OK in last argument)``:
51
 
 
52
 
  1. The number of required arguments.
53
 
  2. The number of optional arguments.
54
 
  3. A boolean, indicating if the final argument may contain whitespace.
55
 
 
56
 
  Arguments are normally single whitespace-separated words.  The final
57
 
  argument may contain whitespace if the third item in the argument spec tuple
58
 
  is 1/True.  If the form of the arguments is more complex, specify only one
59
 
  argument (either required or optional) and indicate that final whitespace is
60
 
  OK; the client code must do any context-sensitive parsing.
61
 
 
62
 
- ``options``: A dictionary, mapping known option names to conversion
63
 
  functions such as `int` or `float`.  ``None`` or an empty dict implies no
64
 
  options to parse.  Several directive option conversion functions are defined
65
 
  in this module.
66
 
 
67
 
  Option conversion functions take a single parameter, the option argument (a
68
 
  string or ``None``), validate it and/or convert it to the appropriate form.
69
 
  Conversion functions may raise ``ValueError`` and ``TypeError`` exceptions.
70
 
 
71
 
- ``content``: A boolean; true if content is allowed.  Client code must handle
72
 
  the case where content is required but not supplied (an empty content list
73
 
  will be supplied).
74
 
 
75
 
Directive functions return a list of nodes which will be inserted into the
76
 
document tree at the point where the directive was encountered (can be an
77
 
empty list).
78
 
 
79
 
See `Creating reStructuredText Directives`_ for more information.
80
 
 
81
 
.. _Creating reStructuredText Directives:
82
 
   http://docutils.sourceforge.net/docs/howto/rst-directives.html
83
7
"""
84
8
 
85
9
__docformat__ = 'reStructuredText'
91
15
 
92
16
 
93
17
_directive_registry = {
94
 
      'attention': ('admonitions', 'attention'),
95
 
      'caution': ('admonitions', 'caution'),
96
 
      'danger': ('admonitions', 'danger'),
97
 
      'error': ('admonitions', 'error'),
98
 
      'important': ('admonitions', 'important'),
99
 
      'note': ('admonitions', 'note'),
100
 
      'tip': ('admonitions', 'tip'),
101
 
      'hint': ('admonitions', 'hint'),
102
 
      'warning': ('admonitions', 'warning'),
103
 
      'admonition': ('admonitions', 'admonition'),
104
 
      'sidebar': ('body', 'sidebar'),
105
 
      'topic': ('body', 'topic'),
106
 
      'line-block': ('body', 'line_block'),
107
 
      'parsed-literal': ('body', 'parsed_literal'),
108
 
      'rubric': ('body', 'rubric'),
109
 
      'epigraph': ('body', 'epigraph'),
110
 
      'highlights': ('body', 'highlights'),
111
 
      'pull-quote': ('body', 'pull_quote'),
112
 
      'compound': ('body', 'compound'),
113
 
      'container': ('body', 'container'),
 
18
      'attention': ('admonitions', 'Attention'),
 
19
      'caution': ('admonitions', 'Caution'),
 
20
      'danger': ('admonitions', 'Danger'),
 
21
      'error': ('admonitions', 'Error'),
 
22
      'important': ('admonitions', 'Important'),
 
23
      'note': ('admonitions', 'Note'),
 
24
      'tip': ('admonitions', 'Tip'),
 
25
      'hint': ('admonitions', 'Hint'),
 
26
      'warning': ('admonitions', 'Warning'),
 
27
      'admonition': ('admonitions', 'Admonition'),
 
28
      'sidebar': ('body', 'Sidebar'),
 
29
      'topic': ('body', 'Topic'),
 
30
      'line-block': ('body', 'LineBlock'),
 
31
      'parsed-literal': ('body', 'ParsedLiteral'),
 
32
      'rubric': ('body', 'Rubric'),
 
33
      'epigraph': ('body', 'Epigraph'),
 
34
      'highlights': ('body', 'Highlights'),
 
35
      'pull-quote': ('body', 'PullQuote'),
 
36
      'compound': ('body', 'Compound'),
 
37
      'container': ('body', 'Container'),
114
38
      #'questions': ('body', 'question_list'),
115
 
      'table': ('tables', 'table'),
116
 
      'csv-table': ('tables', 'csv_table'),
117
 
      'list-table': ('tables', 'list_table'),
118
 
      'image': ('images', 'image'),
119
 
      'figure': ('images', 'figure'),
120
 
      'contents': ('parts', 'contents'),
121
 
      'sectnum': ('parts', 'sectnum'),
122
 
      'header': ('parts', 'header'),
123
 
      'footer': ('parts', 'footer'),
 
39
      'table': ('tables', 'RSTTable'),
 
40
      'csv-table': ('tables', 'CSVTable'),
 
41
      'list-table': ('tables', 'ListTable'),
 
42
      'image': ('images', 'Image'),
 
43
      'figure': ('images', 'Figure'),
 
44
      'contents': ('parts', 'Contents'),
 
45
      'sectnum': ('parts', 'Sectnum'),
 
46
      'header': ('parts', 'Header'),
 
47
      'footer': ('parts', 'Footer'),
124
48
      #'footnotes': ('parts', 'footnotes'),
125
49
      #'citations': ('parts', 'citations'),
126
 
      'target-notes': ('references', 'target_notes'),
127
 
      'meta': ('html', 'meta'),
 
50
      'target-notes': ('references', 'TargetNotes'),
 
51
      'meta': ('html', 'Meta'),
128
52
      #'imagemap': ('html', 'imagemap'),
129
 
      'raw': ('misc', 'raw'),
130
 
      'include': ('misc', 'include'),
131
 
      'replace': ('misc', 'replace'),
132
 
      'unicode': ('misc', 'unicode_directive'),
133
 
      'class': ('misc', 'class_directive'),
134
 
      'role': ('misc', 'role'),
135
 
      'default-role': ('misc', 'default_role'),
136
 
      'title': ('misc', 'title'),
137
 
      'date': ('misc', 'date'),
138
 
      'restructuredtext-test-directive': ('misc', 'directive_test_function'),}
139
 
"""Mapping of directive name to (module name, function name).  The directive
140
 
name is canonical & must be lowercase.  Language-dependent names are defined
141
 
in the ``language`` subpackage."""
142
 
 
143
 
_modules = {}
144
 
"""Cache of imported directive modules."""
 
53
      'raw': ('misc', 'Raw'),
 
54
      'include': ('misc', 'Include'),
 
55
      'replace': ('misc', 'Replace'),
 
56
      'unicode': ('misc', 'Unicode'),
 
57
      'class': ('misc', 'Class'),
 
58
      'role': ('misc', 'Role'),
 
59
      'default-role': ('misc', 'DefaultRole'),
 
60
      'title': ('misc', 'Title'),
 
61
      'date': ('misc', 'Date'),
 
62
      'restructuredtext-test-directive': ('misc', 'TestDirective'),}
 
63
"""Mapping of directive name to (module name, class name).  The
 
64
directive name is canonical & must be lowercase.  Language-dependent
 
65
names are defined in the ``language`` subpackage."""
145
66
 
146
67
_directives = {}
147
 
"""Cache of imported directive functions."""
 
68
"""Cache of imported directives."""
148
69
 
149
70
def directive(directive_name, language_module, document):
150
71
    """
181
102
            '\n'.join(msg_text), line=document.current_line)
182
103
        messages.append(message)
183
104
    try:
184
 
        modulename, functionname = _directive_registry[canonicalname]
 
105
        modulename, classname = _directive_registry[canonicalname]
185
106
    except KeyError:
186
107
        # Error handling done by caller.
187
108
        return None, messages
188
 
    if _modules.has_key(modulename):
189
 
        module = _modules[modulename]
190
 
    else:
191
 
        try:
192
 
            module = __import__(modulename, globals(), locals())
193
 
        except ImportError, detail:
194
 
            messages.append(document.reporter.error(
195
 
                'Error importing directive module "%s" (directive "%s"):\n%s'
196
 
                % (modulename, directive_name, detail),
197
 
                line=document.current_line))
198
 
            return None, messages
199
 
    try:
200
 
        function = getattr(module, functionname)
201
 
        _directives[normname] = function
 
109
    try:
 
110
        module = __import__(modulename, globals(), locals())
 
111
    except ImportError, detail:
 
112
        messages.append(document.reporter.error(
 
113
            'Error importing directive module "%s" (directive "%s"):\n%s'
 
114
            % (modulename, directive_name, detail),
 
115
            line=document.current_line))
 
116
        return None, messages
 
117
    try:
 
118
        directive = getattr(module, classname)
 
119
        _directives[normname] = directive
202
120
    except AttributeError:
203
121
        messages.append(document.reporter.error(
204
 
            'No function "%s" in module "%s" (directive "%s").'
205
 
            % (functionname, modulename, directive_name),
 
122
            'No directive class "%s" in module "%s" (directive "%s").'
 
123
            % (classname, modulename, directive_name),
206
124
            line=document.current_line))
207
125
        return None, messages
208
 
    return function, messages
 
126
    return directive, messages
209
127
 
210
 
def register_directive(name, directive_function):
 
128
def register_directive(name, directive):
211
129
    """
212
130
    Register a nonstandard application-defined directive function.
213
131
    Language lookups are not needed for such functions.
214
132
    """
215
 
    _directives[name] = directive_function
 
133
    _directives[name] = directive
216
134
 
217
135
def flag(argument):
218
136
    """