Debian Codegraph @

docutils/writers/docutils_xml.py

raw symbols SCIP
1 # $Id: docutils_xml.py 10136 2025-05-20 15:48:27Z milde $
2 # Author: David Goodger, Paul Tremblay, Guenter Milde
3 # Maintainer: [email protected]
4 # Copyright: This module has been placed in the public domain.
5
6 """
7 Simple document tree Writer, writes Docutils XML according to
8 https://docutils.sourceforge.io/docs/ref/docutils.dtd.
9 """
10
11 from __future__ import annotations
12
13 __docformat__ = 'reStructuredText'
14
15 from io import StringIO
16 import xml.sax.saxutils
17
18 import docutils
19 from docutils import frontend, nodes, writers, utils
20
21
22 class RawXmlError(docutils.ApplicationError):
23 pass
24
25
26 class Writer(writers.Writer):
27
28 supported = ('xml',)
29 """Formats this writer supports."""
30
31 settings_spec = (
32 '"Docutils XML" Writer Options',
33 None,
34 (('Generate XML with newlines before and after tags.',
35 ['--newlines'],
36 {'action': 'store_true', 'validator': frontend.validate_boolean}),
37 ('Generate XML with indents and newlines.',
38 ['--indents'], # TODO use integer value for number of spaces?
39 {'action': 'store_true', 'validator': frontend.validate_boolean}),
40 ('Omit the XML declaration. Use with caution.',
41 ['--no-xml-declaration'],
42 {'dest': 'xml_declaration', 'default': 1, 'action': 'store_false',
43 'validator': frontend.validate_boolean}),
44 ('Omit the DOCTYPE declaration.',
45 ['--no-doctype'],
46 {'dest': 'doctype_declaration', 'default': 1,
47 'action': 'store_false', 'validator': frontend.validate_boolean}),))
48
49 settings_defaults = {'output_encoding_error_handler': 'xmlcharrefreplace'}
50
51 config_section = 'docutils_xml writer'
52 config_section_dependencies = ('writers',)
53
54 output = None
55 """Final translated form of `document`."""
56
57 def __init__(self) -> None:
58 writers.Writer.__init__(self)
59 self.translator_class = XMLTranslator
60
61 def translate(self) -> None:
62 self.visitor = visitor = self.translator_class(self.document)
63 self.document.walkabout(visitor)
64 self.output = ''.join(visitor.output)
65
66
67 class XMLTranslator(nodes.GenericNodeVisitor):
68
69 # TODO: add stylesheet options similar to HTML and LaTeX writers?
70 # xml_stylesheet = '<?xml-stylesheet type="text/xsl" href="%s"?>\n'
71 doctype = (
72 '<!DOCTYPE document PUBLIC'
73 ' "+//IDN docutils.sourceforge.net//DTD Docutils Generic//EN//XML"'
74 ' "http://docutils.sourceforge.net/docs/ref/docutils.dtd">\n')
75 generator = '<!-- Generated by Docutils %s -->\n'
76
77 xmlparser = xml.sax.make_parser()
78 """SAX parser instance to check/extract raw XML."""
79 xmlparser.setFeature(
80 "http://xml.org/sax/features/external-general-entities", True)
81
82 def __init__(self, document) -> None:
83 nodes.NodeVisitor.__init__(self, document)
84
85 # Reporter
86 self.warn = self.document.reporter.warning
87 self.error = self.document.reporter.error
88
89 # Settings
90 self.settings = settings = document.settings
91 self.indent = self.newline = ''
92 if settings.newlines:
93 self.newline = '\n'
94 if settings.indents:
95 self.newline = '\n'
96 self.indent = ' ' # TODO make this configurable?
97 self.level = 0 # indentation level
98 self.in_simple = 0 # level of nesting inside mixed-content elements
99 self.fixed_text = 0 # level of nesting inside FixedText elements
100
101 # Output
102 self.output = []
103 if settings.xml_declaration:
104 self.output.append(utils.xml_declaration(settings.output_encoding))
105 if settings.doctype_declaration:
106 self.output.append(self.doctype)
107 self.output.append(self.generator % docutils.__version__)
108
109 # initialize XML parser
110 self.the_handle = TestXml()
111 self.xmlparser.setContentHandler(self.the_handle)
112
113 # generic visit and depart methods
114 # --------------------------------
115
116 simple_nodes = (nodes.TextElement, nodes.meta,
117 nodes.image, nodes.colspec, nodes.transition)
118
119 def default_visit(self, node) -> None:
120 """Default node visit method."""
121 if not self.in_simple:
122 self.output.append(self.indent*self.level)
123 self.output.append(node.starttag(xml.sax.saxutils.quoteattr))
124 if not isinstance(node, nodes.Inline):
125 self.level += 1
126 # `nodes.literal` is not an instance of FixedTextElement by design,
127 # see docs/ref/rst/restructuredtext.html#inline-literals
128 if isinstance(node, (nodes.FixedTextElement, nodes.literal)):
129 self.fixed_text += 1
130 if isinstance(node, self.simple_nodes):
131 self.in_simple += 1
132 if not self.in_simple:
133 self.output.append(self.newline)
134
135 def default_departure(self, node) -> None:
136 """Default node depart method."""
137 if not isinstance(node, nodes.Inline):
138 self.level -= 1
139 if not self.in_simple:
140 self.output.append(self.indent*self.level)
141 self.output.append(node.endtag())
142 if isinstance(node, (nodes.FixedTextElement, nodes.literal)):
143 self.fixed_text -= 1
144 if isinstance(node, self.simple_nodes):
145 self.in_simple -= 1
146 if not self.in_simple:
147 self.output.append(self.newline)
148
149 # specific visit and depart methods
150 # ---------------------------------
151
152 def visit_Text(self, node) -> None:
153 text = xml.sax.saxutils.escape(node.astext())
154 # indent text if we are not in a FixedText element:
155 if not self.fixed_text:
156 text = text.replace('\n', '\n'+self.indent*self.level)
157 self.output.append(text)
158
159 def depart_Text(self, node) -> None:
160 pass
161
162 def visit_raw(self, node):
163 if 'xml' not in node.get('format', '').split():
164 # skip other raw content?
165 # raise nodes.SkipNode
166 self.default_visit(node)
167 return
168 # wrap in <raw> element
169 self.default_visit(node) # or not?
170 xml_string = node.astext()
171 self.output.append(xml_string)
172 self.default_departure(node) # or not?
173 # Check validity of raw XML:
174 try:
175 self.xmlparser.parse(StringIO(xml_string))
176 except xml.sax._exceptions.SAXParseException:
177 col_num = self.the_handle.locator.getColumnNumber()
178 line_num = self.the_handle.locator.getLineNumber()
179 srcline = node.line
180 if not isinstance(node.parent, nodes.TextElement):
181 srcline += 2 # directive content start line
182 msg = 'Invalid raw XML in column %d, line offset %d:\n%s' % (
183 col_num, line_num, node.astext())
184 self.warn(msg, source=node.source, line=srcline+line_num-1)
185 raise nodes.SkipNode # content already processed
186
187
188 class TestXml(xml.sax.handler.ContentHandler):
189
190 def setDocumentLocator(self, locator) -> None:
191 self.locator = locator