| 1 |
|
| 2 |
e. |
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
"""A Docutils-XML parser. |
| 16 |
|
| 17 |
Provisional: |
| 18 |
The API is not fixed yet. |
| 19 |
Defined objects may be renamed or changed |
| 20 |
in any Docutils release without prior notice. |
| 21 |
""" |
| 22 |
|
| 23 |
from __future__ import annotations |
| 24 |
|
| 25 |
__docformat__ = 'reStructuredText' |
| 26 |
|
| 27 |
import re |
| 28 |
import xml.etree.ElementTree as ET |
| 29 |
|
| 30 |
from docutils import frontend, nodes, parsers, utils |
| 31 |
|
| 32 |
|
| 33 |
class Parser(parsers.Parser): |
| 34 |
|
| 35 |
"""A Docutils-XML parser.""" |
| 36 |
|
| 37 |
supported = ('xml', 'docutils-xml') |
| 38 |
"""Aliases this parser supports.""" |
| 39 |
|
| 40 |
config_section = 'xml parser' |
| 41 |
config_section_dependencies = ('parsers',) |
| 42 |
settings_default_overrides = {'doctitle_xform': False, |
| 43 |
'validate': True, |
| 44 |
} |
| 45 |
|
| 46 |
def parse(self, inputstring, document) -> None: |
| 47 |
""" |
| 48 |
Parse `inputstring` and populate `document`, a "document tree". |
| 49 |
|
| 50 |
Provisional. |
| 51 |
""" |
| 52 |
self.setup_parse(inputstring, document) |
| 53 |
|
| 54 |
node = parse_element(inputstring, document) |
| 55 |
if not isinstance(node, nodes.document): |
| 56 |
document.append(node) |
| 57 |
|
| 58 |
self.finish_parse() |
| 59 |
|
| 60 |
|
| 61 |
class Unknown(nodes.Special, nodes.Inline, nodes.Element): |
| 62 |
"""An unknown element found by the XML parser.""" |
| 63 |
content_model = (((nodes.Element, nodes.Text), '*'),) |
| 64 |
|
| 65 |
|
| 66 |
def parse_element(inputstring, document=None): |
| 67 |
""" |
| 68 |
Parse `inputstring` as "Docutils XML", return `nodes.Element` instance. |
| 69 |
|
| 70 |
:inputstring: XML source. |
| 71 |
:document: `nodes.document` instance (default: a new dummy instance). |
| 72 |
Provides settings and reporter. |
| 73 |
Populated and returned, if the inputstring's root element |
| 74 |
is <document>. |
| 75 |
|
| 76 |
Caution: |
| 77 |
The function does not detect invalid XML. |
| 78 |
|
| 79 |
To check the validity of the returned node, |
| 80 |
you may use its `validate()` method:: |
| 81 |
|
| 82 |
node = parse_element('<tip><hint>text</hint></tip>') |
| 83 |
node.validate() |
| 84 |
|
| 85 |
Provisional. |
| 86 |
""" |
| 87 |
root = None |
| 88 |
parser = ET.XMLPullParser(events=('start',)) |
| 89 |
for i, line in enumerate(inputstring.splitlines(keepends=True)): |
| 90 |
try: |
| 91 |
parser.feed(line) |
| 92 |
for event, element in parser.read_events(): |
| 93 |
if root is None: |
| 94 |
root = element |
| 95 |
element.attrib['source line'] = str(i+1) |
| 96 |
except ET.ParseError as e: |
| 97 |
if document is None: |
| 98 |
raise |
| 99 |
document.reporter.error(f'XML parse error: {e}.', |
| 100 |
source=document.settings._source, |
| 101 |
line=e.position[0]) |
| 102 |
break |
| 103 |
return element2node(root, document) |
| 104 |
|
| 105 |
|
| 106 |
def element2node(element, document=None, unindent=True): |
| 107 |
""" |
| 108 |
Convert an `etree` element and its children to Docutils doctree nodes. |
| 109 |
|
| 110 |
:element: `xml.etree` element |
| 111 |
:document: see `parse_element()` |
| 112 |
:unindent: Remove formatting indentation of follow-up text lines? |
| 113 |
Cf. `append_text()`. |
| 114 |
TODO: do we need an "unindent" configuration setting? |
| 115 |
|
| 116 |
Return a `docutils.nodes.Element` instance. |
| 117 |
|
| 118 |
Internal. |
| 119 |
""" |
| 120 |
if document is None: |
| 121 |
document = utils.new_document('xml input', |
| 122 |
frontend.get_default_settings(Parser)) |
| 123 |
document.source == 'xml input' |
| 124 |
if element is None: |
| 125 |
problem = nodes.problematic('', 'No XML element found.') |
| 126 |
return nodes.paragraph('', '', problem) |
| 127 |
|
| 128 |
try: |
| 129 |
nodeclass = getattr(nodes, element.tag) |
| 130 |
if not issubclass(nodeclass, nodes.Element): |
| 131 |
nodeclass = Unknown |
| 132 |
except AttributeError: |
| 133 |
nodeclass = Unknown |
| 134 |
if nodeclass == nodes.document: |
| 135 |
node = document |
| 136 |
document.source = document.source or document.settings._source |
| 137 |
else: |
| 138 |
node = nodeclass() |
| 139 |
|
| 140 |
node.line = int(element.get('source line')) |
| 141 |
if isinstance(node, Unknown): |
| 142 |
node.tagname = element.tag |
| 143 |
document.reporter.warning( |
| 144 |
f'Unknown element type <{element.tag}>.', |
| 145 |
base_node=node) |
| 146 |
|
| 147 |
|
| 148 |
for key, value in element.items(): |
| 149 |
if key.startswith('{') or key == 'source line': |
| 150 |
continue |
| 151 |
try: |
| 152 |
node.attributes[key] = nodes.ATTRIBUTE_VALIDATORS[key](value) |
| 153 |
except (ValueError, KeyError): |
| 154 |
if key in node.list_attributes: |
| 155 |
value = value.split() |
| 156 |
node.attributes[key] = value |
| 157 |
|
| 158 |
|
| 159 |
if isinstance(node, nodes.decoration): |
| 160 |
document.decoration = node |
| 161 |
elif isinstance(node, nodes.substitution_definition): |
| 162 |
document.note_substitution_def(node, ' '.join(node['names']), document) |
| 163 |
if node['ids']: |
| 164 |
document.set_id(node) |
| 165 |
|
| 166 |
|
| 167 |
|
| 168 |
|
| 169 |
unindent = unindent and not isinstance( |
| 170 |
node, (nodes.FixedTextElement, nodes.literal, Unknown)) |
| 171 |
|
| 172 |
append_text(node, element.text, unindent) |
| 173 |
|
| 174 |
for child in element: |
| 175 |
node.append(element2node(child, document, unindent)) |
| 176 |
|
| 177 |
append_text(node, child.tail, unindent) |
| 178 |
|
| 179 |
return node |
| 180 |
|
| 181 |
|
| 182 |
def append_text(node, text, unindent) -> None: |
| 183 |
|
| 184 |
|
| 185 |
if not text: |
| 186 |
return |
| 187 |
if unindent: |
| 188 |
text = re.sub('\n +', '\n', text) |
| 189 |
if isinstance(node, nodes.TextElement): |
| 190 |
node.append(nodes.Text(text)) |
| 191 |
elif text.strip(): |
| 192 |
|
| 193 |
|
| 194 |
node.append(nodes.Text(text.strip())) |