Debian Codegraph @

docutils/writers/odf_odt/__init__.py

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 # $Id: __init__.py 10196 2025-08-07 06:35:37Z milde $
2 # Author: Dave Kuhlman <[email protected]>
3 # Copyright: This module has been placed in the public domain.
4
5 """
6 Open Document Format (ODF) Writer.
7
8 This module is provisional:
9 the API is not settled and may change with any minor Docutils version.
10 """
11
12 from __future__ import annotations
13
14 __docformat__ = 'reStructuredText'
15
16 from configparser import ConfigParser
17 import copy
18 from io import StringIO
19 import itertools
20 import locale
21 import os
22 import os.path
23 from pathlib import Path
24 import re
25 import subprocess
26 import tempfile
27 import time
28 import urllib
29 import weakref
30 from xml.etree import ElementTree as ET
31 from xml.dom import minidom
32 import zipfile
33
34 import docutils
35 from docutils import frontend, nodes, utils, writers, languages
36 from docutils.parsers.rst.directives.images import PIL # optional
37 from docutils.readers import standalone
38 from docutils.transforms import references
39
40 # Import pygments and odtwriter pygments formatters if possible.
41 try:
42 import pygments
43 import pygments.lexers
44 from .pygmentsformatter import (OdtPygmentsProgFormatter,
45 OdtPygmentsLaTeXFormatter)
46 except (ImportError, SyntaxError):
47 pygments = None
48
49 # import warnings
50 # warnings.warn('importing IPShellEmbed', UserWarning)
51 # from IPython.Shell import IPShellEmbed
52 # args = ['-pdb', '-pi1', 'In <\\#>: ', '-pi2', ' .\\D.: ',
53 # '-po', 'Out<\\#>: ', '-nosep']
54 # ipshell = IPShellEmbed(args,
55 # banner = 'Entering IPython. Press Ctrl-D to exit.',
56 # exit_msg = 'Leaving Interpreter, back to program.')
57
58 VERSION = '1.0a'
59
60 IMAGE_NAME_COUNTER = itertools.count()
61
62
63 #
64 # ElementTree does not support getparent method (lxml does).
65 # This wrapper class and the following support functions provide
66 # that support for the ability to get the parent of an element.
67 #
68 _parents = weakref.WeakKeyDictionary()
69 if isinstance(ET.Element, type):
70 _ElementInterface = ET.Element
71 else:
72 _ElementInterface = ET._ElementInterface
73
74
75 class _ElementInterfaceWrapper(_ElementInterface):
76 def __init__(self, tag, attrib=None) -> None:
77 _ElementInterface.__init__(self, tag, attrib)
78 _parents[self] = None
79
80 def setparent(self, parent) -> None:
81 _parents[self] = parent
82
83 def getparent(self):
84 return _parents[self]
85
86
87 #
88 # Constants and globals
89
90 SPACES_PATTERN = re.compile(r'( +)')
91 TABS_PATTERN = re.compile(r'(\t+)')
92 FILL_PAT1 = re.compile(r'^ +')
93 FILL_PAT2 = re.compile(r' {2,}')
94
95 TABLESTYLEPREFIX = 'rststyle-table-'
96 TABLENAMEDEFAULT = '%s0' % TABLESTYLEPREFIX
97 TABLEPROPERTYNAMES = (
98 'border', 'border-top', 'border-left',
99 'border-right', 'border-bottom', )
100
101 GENERATOR_DESC = 'Docutils.org/odf_odt'
102
103 NAME_SPACE_1 = 'urn:oasis:names:tc:opendocument:xmlns:office:1.0'
104
105 CONTENT_NAMESPACE_DICT = CNSD = {
106 # 'office:version': '1.0',
107 'chart': 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0',
108 'dc': 'http://purl.org/dc/elements/1.1/',
109 'dom': 'http://www.w3.org/2001/xml-events',
110 'dr3d': 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0',
111 'draw': 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0',
112 'fo': 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0',
113 'form': 'urn:oasis:names:tc:opendocument:xmlns:form:1.0',
114 'math': 'http://www.w3.org/1998/Math/MathML',
115 'meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
116 'number': 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0',
117 'office': NAME_SPACE_1,
118 'ooo': 'http://openoffice.org/2004/office',
119 'oooc': 'http://openoffice.org/2004/calc',
120 'ooow': 'http://openoffice.org/2004/writer',
121 'presentation': 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0',
122
123 'script': 'urn:oasis:names:tc:opendocument:xmlns:script:1.0',
124 'style': 'urn:oasis:names:tc:opendocument:xmlns:style:1.0',
125 'svg': 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0',
126 'table': 'urn:oasis:names:tc:opendocument:xmlns:table:1.0',
127 'text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
128 'xforms': 'http://www.w3.org/2002/xforms',
129 'xlink': 'http://www.w3.org/1999/xlink',
130 'xsd': 'http://www.w3.org/2001/XMLSchema',
131 'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
132 }
133
134 STYLES_NAMESPACE_DICT = SNSD = {
135 # 'office:version': '1.0',
136 'chart': 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0',
137 'dc': 'http://purl.org/dc/elements/1.1/',
138 'dom': 'http://www.w3.org/2001/xml-events',
139 'dr3d': 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0',
140 'draw': 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0',
141 'fo': 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0',
142 'form': 'urn:oasis:names:tc:opendocument:xmlns:form:1.0',
143 'math': 'http://www.w3.org/1998/Math/MathML',
144 'meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
145 'number': 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0',
146 'office': NAME_SPACE_1,
147 'presentation': 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0',
148 'ooo': 'http://openoffice.org/2004/office',
149 'oooc': 'http://openoffice.org/2004/calc',
150 'ooow': 'http://openoffice.org/2004/writer',
151 'script': 'urn:oasis:names:tc:opendocument:xmlns:script:1.0',
152 'style': 'urn:oasis:names:tc:opendocument:xmlns:style:1.0',
153 'svg': 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0',
154 'table': 'urn:oasis:names:tc:opendocument:xmlns:table:1.0',
155 'text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
156 'xlink': 'http://www.w3.org/1999/xlink',
157 }
158
159 MANIFEST_NAMESPACE_DICT = MANNSD = {
160 'manifest': 'urn:oasis:names:tc:opendocument:xmlns:manifest:1.0',
161 }
162
163 META_NAMESPACE_DICT = METNSD = {
164 # 'office:version': '1.0',
165 'dc': 'http://purl.org/dc/elements/1.1/',
166 'meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
167 'office': NAME_SPACE_1,
168 'ooo': 'http://openoffice.org/2004/office',
169 'xlink': 'http://www.w3.org/1999/xlink',
170 }
171
172 # Attribute dictionaries for use with ElementTree, which
173 # does not support use of nsmap parameter on Element() and SubElement().
174
175 CONTENT_NAMESPACE_ATTRIB = {
176 # 'office:version': '1.0',
177 'xmlns:chart': 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0',
178 'xmlns:dc': 'http://purl.org/dc/elements/1.1/',
179 'xmlns:dom': 'http://www.w3.org/2001/xml-events',
180 'xmlns:dr3d': 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0',
181 'xmlns:draw': 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0',
182 'xmlns:fo': 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0',
183 'xmlns:form': 'urn:oasis:names:tc:opendocument:xmlns:form:1.0',
184 'xmlns:math': 'http://www.w3.org/1998/Math/MathML',
185 'xmlns:meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
186 'xmlns:number': 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0',
187 'xmlns:office': NAME_SPACE_1,
188 'xmlns:presentation':
189 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0',
190 'xmlns:ooo': 'http://openoffice.org/2004/office',
191 'xmlns:oooc': 'http://openoffice.org/2004/calc',
192 'xmlns:ooow': 'http://openoffice.org/2004/writer',
193 'xmlns:script': 'urn:oasis:names:tc:opendocument:xmlns:script:1.0',
194 'xmlns:style': 'urn:oasis:names:tc:opendocument:xmlns:style:1.0',
195 'xmlns:svg': 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0',
196 'xmlns:table': 'urn:oasis:names:tc:opendocument:xmlns:table:1.0',
197 'xmlns:text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
198 'xmlns:xforms': 'http://www.w3.org/2002/xforms',
199 'xmlns:xlink': 'http://www.w3.org/1999/xlink',
200 'xmlns:xsd': 'http://www.w3.org/2001/XMLSchema',
201 'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
202 }
203
204 STYLES_NAMESPACE_ATTRIB = {
205 # 'office:version': '1.0',
206 'xmlns:chart': 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0',
207 'xmlns:dc': 'http://purl.org/dc/elements/1.1/',
208 'xmlns:dom': 'http://www.w3.org/2001/xml-events',
209 'xmlns:dr3d': 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0',
210 'xmlns:draw': 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0',
211 'xmlns:fo': 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0',
212 'xmlns:form': 'urn:oasis:names:tc:opendocument:xmlns:form:1.0',
213 'xmlns:math': 'http://www.w3.org/1998/Math/MathML',
214 'xmlns:meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
215 'xmlns:number': 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0',
216 'xmlns:office': NAME_SPACE_1,
217 'xmlns:presentation':
218 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0',
219 'xmlns:ooo': 'http://openoffice.org/2004/office',
220 'xmlns:oooc': 'http://openoffice.org/2004/calc',
221 'xmlns:ooow': 'http://openoffice.org/2004/writer',
222 'xmlns:script': 'urn:oasis:names:tc:opendocument:xmlns:script:1.0',
223 'xmlns:style': 'urn:oasis:names:tc:opendocument:xmlns:style:1.0',
224 'xmlns:svg': 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0',
225 'xmlns:table': 'urn:oasis:names:tc:opendocument:xmlns:table:1.0',
226 'xmlns:text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
227 'xmlns:xlink': 'http://www.w3.org/1999/xlink',
228 }
229
230 MANIFEST_NAMESPACE_ATTRIB = {
231 'xmlns:manifest': 'urn:oasis:names:tc:opendocument:xmlns:manifest:1.0',
232 }
233
234 META_NAMESPACE_ATTRIB = {
235 # 'office:version': '1.0',
236 'xmlns:dc': 'http://purl.org/dc/elements/1.1/',
237 'xmlns:meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
238 'xmlns:office': NAME_SPACE_1,
239 'xmlns:ooo': 'http://openoffice.org/2004/office',
240 'xmlns:xlink': 'http://www.w3.org/1999/xlink',
241 }
242
243
244 #
245 # Functions
246 #
247
248 #
249 # ElementTree support functions.
250 # In order to be able to get the parent of elements, must use these
251 # instead of the functions with same name provided by ElementTree.
252 #
253 def Element(tag, attrib=None, nsmap=None, nsdict=CNSD):
254 if attrib is None:
255 attrib = {}
256 tag, attrib = fix_ns(tag, attrib, nsdict)
257 return _ElementInterfaceWrapper(tag, attrib)
258
259
260 def SubElement(parent, tag, attrib=None, nsmap=None, nsdict=CNSD):
261 if attrib is None:
262 attrib = {}
263 tag, attrib = fix_ns(tag, attrib, nsdict)
264 el = _ElementInterfaceWrapper(tag, attrib)
265 parent.append(el)
266 el.setparent(parent)
267 return el
268
269
270 def fix_ns(tag, attrib, nsdict):
271 nstag = add_ns(tag, nsdict)
272 nsattrib = {}
273 for key, val in list(attrib.items()):
274 nskey = add_ns(key, nsdict)
275 nsattrib[nskey] = val
276 return nstag, nsattrib
277
278
279 def add_ns(tag, nsdict=CNSD):
280 return tag
281
282
283 def ToString(et):
284 outstream = StringIO()
285 et.write(outstream, encoding="unicode")
286 s1 = outstream.getvalue()
287 outstream.close()
288 return s1
289
290
291 def escape_cdata(text):
292 text = text.replace("&", "&amp;")
293 text = text.replace("<", "&lt;")
294 text = text.replace(">", "&gt;")
295 ascii_ = ''
296 for char in text:
297 if ord(char) >= ord("\x7f"):
298 ascii_ += "&#x%X;" % (ord(char), )
299 else:
300 ascii_ += char
301 return ascii_
302
303
304 #
305 # Classes
306 #
307
308
309 class TableStyle:
310 def __init__(self, border=None, backgroundcolor=None) -> None:
311 self.border = border
312 self.backgroundcolor = backgroundcolor
313
314 def get_border_(self):
315 return self.border_
316
317 def set_border_(self, border) -> None:
318 self.border_ = border
319
320 border = property(get_border_, set_border_)
321
322 def get_backgroundcolor_(self):
323 return self.backgroundcolor_
324
325 def set_backgroundcolor_(self, backgroundcolor) -> None:
326 self.backgroundcolor_ = backgroundcolor
327 backgroundcolor = property(get_backgroundcolor_, set_backgroundcolor_)
328
329
330 BUILTIN_DEFAULT_TABLE_STYLE = TableStyle(
331 border='0.0007in solid #000000')
332
333
334 #
335 # Information about the indentation level for lists nested inside
336 # other contexts, e.g. dictionary lists.
337 class ListLevel:
338 def __init__(self, level, sibling_level=True, nested_level=True) -> None:
339 self.level = level
340 self.sibling_level = sibling_level
341 self.nested_level = nested_level
342
343 def set_sibling(self, sibling_level) -> None:
344 self.sibling_level = sibling_level
345
346 def get_sibling(self):
347 return self.sibling_level
348
349 def set_nested(self, nested_level) -> None:
350 self.nested_level = nested_level
351
352 def get_nested(self):
353 return self.nested_level
354
355 def set_level(self, level) -> None:
356 self.level = level
357
358 def get_level(self):
359 return self.level
360
361
362 class Writer(writers.Writer):
363
364 MIME_TYPE = 'application/vnd.oasis.opendocument.text'
365 EXTENSION = '.odt'
366
367 supported = ('odt', )
368 """Formats this writer supports."""
369
370 default_stylesheet = 'styles' + EXTENSION
371
372 default_stylesheet_path = utils.relative_path(
373 os.path.join(os.getcwd(), 'dummy'),
374 os.path.join(os.path.dirname(__file__), default_stylesheet))
375
376 default_template = 'template.txt'
377
378 default_template_path = utils.relative_path(
379 os.path.join(os.getcwd(), 'dummy'),
380 os.path.join(os.path.dirname(__file__), default_template))
381
382 settings_spec = (
383 'ODF-Specific Options.',
384 None,
385 (
386 ('Specify a stylesheet. '
387 'Default: "%s"' % default_stylesheet_path,
388 ['--stylesheet'],
389 {'default': default_stylesheet_path,
390 'dest': 'stylesheet',
391 'metavar': '<filename>'}),
392 ('Specify an ODF-specific configuration/mapping file '
393 'relative to the current working directory.',
394 ['--odf-config-file'],
395 {'metavar': '<file>'}),
396 ('Obfuscate email addresses to confuse harvesters.',
397 ['--cloak-email-addresses'],
398 {'default': False,
399 'action': 'store_true',
400 'dest': 'cloak_email_addresses',
401 'validator': frontend.validate_boolean}),
402 ('Do not obfuscate email addresses.',
403 ['--no-cloak-email-addresses'],
404 {'default': False,
405 'action': 'store_false',
406 'dest': 'cloak_email_addresses',
407 'validator': frontend.validate_boolean}),
408 ('Specify the thickness of table borders in thousands of a cm. '
409 'Default is 35.',
410 ['--table-border-thickness'],
411 {'default': None,
412 'metavar': '<int>',
413 'validator': frontend.validate_nonnegative_int}),
414 ('Add syntax highlighting in literal code blocks.',
415 ['--add-syntax-highlighting'],
416 {'default': False,
417 'action': 'store_true',
418 'dest': 'add_syntax_highlighting',
419 'validator': frontend.validate_boolean}),
420 ('Do not add syntax highlighting in '
421 'literal code blocks. (default)',
422 ['--no-syntax-highlighting'],
423 {'default': False,
424 'action': 'store_false',
425 'dest': 'add_syntax_highlighting',
426 'validator': frontend.validate_boolean}),
427 ('Create sections for headers. (default)',
428 ['--create-sections'],
429 {'default': True,
430 'action': 'store_true',
431 'dest': 'create_sections',
432 'validator': frontend.validate_boolean}),
433 ('Do not create sections for headers.',
434 ['--no-sections'],
435 {'default': True,
436 'action': 'store_false',
437 'dest': 'create_sections',
438 'validator': frontend.validate_boolean}),
439 ('Create links.',
440 ['--create-links'],
441 {'default': False,
442 'action': 'store_true',
443 'dest': 'create_links',
444 'validator': frontend.validate_boolean}),
445 ('Do not create links. (default)',
446 ['--no-links'],
447 {'default': False,
448 'action': 'store_false',
449 'dest': 'create_links',
450 'validator': frontend.validate_boolean}),
451 ('Generate endnotes at end of document, not footnotes '
452 'at bottom of page.',
453 ['--endnotes-end-doc'],
454 {'default': False,
455 'action': 'store_true',
456 'dest': 'endnotes_end_doc',
457 'validator': frontend.validate_boolean}),
458 ('Generate footnotes at bottom of page, not endnotes '
459 'at end of document. (default)',
460 ['--no-endnotes-end-doc'],
461 {'default': False,
462 'action': 'store_false',
463 'dest': 'endnotes_end_doc',
464 'validator': frontend.validate_boolean}),
465 ('Generate a bullet list table of contents, '
466 'not a native ODF table of contents.',
467 ['--generate-list-toc'],
468 {'action': 'store_false',
469 'dest': 'generate_oowriter_toc',
470 'validator': frontend.validate_boolean}),
471 ('Generate a native ODF table of contents, '
472 'not a bullet list. (default)',
473 ['--generate-oowriter-toc'],
474 {'default': True,
475 'action': 'store_true',
476 'dest': 'generate_oowriter_toc',
477 'validator': frontend.validate_boolean}),
478 ('Specify the contents of an custom header line. '
479 'See ODF/ODT writer documentation for details '
480 'about special field character sequences.',
481 ['--custom-odt-header'],
482 {'default': '',
483 'dest': 'custom_header',
484 'metavar': '<custom header>'}),
485 ('Specify the contents of an custom footer line. '
486 'See ODF/ODT writer documentation for details.',
487 ['--custom-odt-footer'],
488 {'default': '',
489 'dest': 'custom_footer',
490 'metavar': '<custom footer>'}),
491 )
492 )
493
494 settings_defaults = {
495 'output_encoding_error_handler': 'xmlcharrefreplace',
496 }
497
498 relative_path_settings = ('odf_config_file', 'stylesheet',)
499
500 config_section = 'odf_odt writer'
501 config_section_dependencies = ('writers',)
502
503 def __init__(self) -> None:
504 writers.Writer.__init__(self)
505 self.translator_class = ODFTranslator
506
507 def translate(self) -> None:
508 self.settings = self.document.settings
509 self.visitor = self.translator_class(self.document)
510 self.visitor.retrieve_styles(self.EXTENSION)
511 self.document.walkabout(self.visitor)
512 self.visitor.add_doc_title()
513 self.assemble_my_parts()
514 self.output = self.parts['whole']
515
516 def assemble_my_parts(self) -> None:
517 """Assemble the `self.parts` dictionary. Extend in subclasses.
518 """
519 writers.Writer.assemble_parts(self)
520 f = tempfile.NamedTemporaryFile()
521 zfile = zipfile.ZipFile(f, 'w', zipfile.ZIP_DEFLATED)
522 self.write_zip_str(
523 zfile, 'mimetype', self.MIME_TYPE,
524 compress_type=zipfile.ZIP_STORED)
525 content = self.visitor.content_astext()
526 self.write_zip_str(zfile, 'content.xml', content)
527 s1 = self.create_manifest()
528 self.write_zip_str(zfile, 'META-INF/manifest.xml', s1)
529 s1 = self.create_meta()
530 self.write_zip_str(zfile, 'meta.xml', s1)
531 s1 = self.get_stylesheet()
532 # Set default language in document to be generated.
533 # Language is specified by the -l/--language command line option.
534 # The format is described in BCP 47. If region is omitted, we use
535 # local.normalize(ll) to obtain a region.
536 language_code = None
537 region_code = None
538 if self.visitor.language_code:
539 language_ids = self.visitor.language_code.replace('_', '-')
540 language_ids = language_ids.split('-')
541 # first tag is primary language tag
542 language_code = language_ids[0].lower()
543 # 2-letter region subtag may follow in 2nd or 3rd position
544 for subtag in language_ids[1:]:
545 if len(subtag) == 2 and subtag.isalpha():
546 region_code = subtag.upper()
547 break
548 elif len(subtag) == 1:
549 break # 1-letter tag is never before valid region tag
550 if region_code is None:
551 try:
552 rcode = locale.normalize(language_code)
553 except NameError:
554 rcode = language_code
555 rcode = rcode.split('_')
556 if len(rcode) > 1:
557 rcode = rcode[1].split('.')
558 region_code = rcode[0]
559 if region_code is None:
560 self.document.reporter.warning(
561 'invalid language-region.\n'
562 ' Could not find region with locale.normalize().\n'
563 ' Please specify both language and region (ll-RR).\n'
564 ' Examples: es-MX (Spanish, Mexico),\n'
565 ' en-AU (English, Australia).')
566 # Update the style ElementTree with the language and region.
567 # Note that we keep a reference to the modified node because
568 # it is possible that ElementTree will throw away the Python
569 # representation of the updated node if we do not.
570 updated, new_dom_styles, updated_node = self.update_stylesheet(
571 self.visitor.get_dom_stylesheet(), language_code, region_code)
572 if updated:
573 s1 = ET.tostring(new_dom_styles)
574 self.write_zip_str(zfile, 'styles.xml', s1)
575 self.store_embedded_files(zfile)
576 self.copy_from_stylesheet(zfile)
577 zfile.close()
578 f.seek(0)
579 whole = f.read()
580 f.close()
581 self.parts['whole'] = whole
582 self.parts['encoding'] = self.document.settings.output_encoding
583 self.parts['version'] = docutils.__version__
584
585 def update_stylesheet(self, stylesheet_root, language_code, region_code):
586 """Update xml style sheet element with language and region/country."""
587 updated = False
588 modified_nodes = set()
589 if language_code is not None or region_code is not None:
590 n1 = stylesheet_root.find(
591 '{urn:oasis:names:tc:opendocument:xmlns:office:1.0}'
592 'styles')
593 if n1 is None:
594 raise RuntimeError(
595 "Cannot find 'styles' element in styles.odt/styles.xml")
596 n2_nodes = n1.findall(
597 '{urn:oasis:names:tc:opendocument:xmlns:style:1.0}'
598 'default-style')
599 if not n2_nodes:
600 raise RuntimeError(
601 "Cannot find 'default-style' "
602 "element in styles.xml")
603 for node in n2_nodes:
604 family = node.attrib.get(
605 '{urn:oasis:names:tc:opendocument:xmlns:style:1.0}'
606 'family')
607 if family == 'paragraph' or family == 'graphic':
608 n3 = node.find(
609 '{urn:oasis:names:tc:opendocument:xmlns:style:1.0}'
610 'text-properties')
611 if n3 is None:
612 raise RuntimeError(
613 "Cannot find 'text-properties' "
614 "element in styles.xml")
615 if language_code is not None:
616 n3.attrib[
617 '{urn:oasis:names:tc:opendocument:xmlns:'
618 'xsl-fo-compatible:1.0}language'] = language_code
619 n3.attrib[
620 '{urn:oasis:names:tc:opendocument:xmlns:'
621 'style:1.0}language-complex'] = language_code
622 updated = True
623 modified_nodes.add(n3)
624 if region_code is not None:
625 n3.attrib[
626 '{urn:oasis:names:tc:opendocument:xmlns:'
627 'xsl-fo-compatible:1.0}country'] = region_code
628 n3.attrib[
629 '{urn:oasis:names:tc:opendocument:xmlns:'
630 'style:1.0}country-complex'] = region_code
631 updated = True
632 modified_nodes.add(n3)
633 return updated, stylesheet_root, modified_nodes
634
635 def write_zip_str(
636 self, zfile, name, bytes_, compress_type=zipfile.ZIP_DEFLATED,
637 ) -> None:
638 localtime = time.localtime(time.time())
639 zinfo = zipfile.ZipInfo(name, localtime)
640 # Add some standard UNIX file access permissions (-rw-r--r--).
641 zinfo.external_attr = (0x81a4 & 0xFFFF) << 16
642 zinfo.compress_type = compress_type
643 zfile.writestr(zinfo, bytes_)
644
645 def store_embedded_files(self, zfile) -> None:
646 embedded_files = self.visitor.get_embedded_file_list()
647 for source, destination in embedded_files:
648 if source is None:
649 continue
650 try:
651 zfile.write(source, destination)
652 except OSError:
653 self.document.reporter.warning(
654 "Can't open file %s." % (source, ))
655
656 def get_settings(self):
657 """
658 modeled after get_stylesheet
659 """
660 stylespath = self.settings.stylesheet
661 zfile = zipfile.ZipFile(stylespath, 'r')
662 s1 = zfile.read('settings.xml')
663 zfile.close()
664 return s1
665
666 def get_stylesheet(self):
667 """Get the stylesheet from the visitor.
668 Ask the visitor to setup the page.
669 """
670 return self.visitor.setup_page()
671
672 def copy_from_stylesheet(self, outzipfile) -> None:
673 """Copy images, settings, etc from the stylesheet doc into target doc.
674 """
675 stylespath = self.settings.stylesheet
676 if not stylespath.endswith('.odt'):
677 return # an '.xml' stylesheet does not have settings or images
678 inzipfile = zipfile.ZipFile(stylespath, 'r')
679 # Copy the settings.
680 s1 = inzipfile.read('settings.xml')
681 self.write_zip_str(outzipfile, 'settings.xml', s1)
682 # Copy the images.
683 namelist = inzipfile.namelist()
684 for name in namelist:
685 if name.startswith('Pictures/'):
686 imageobj = inzipfile.read(name)
687 outzipfile.writestr(name, imageobj)
688 inzipfile.close()
689
690 def assemble_parts(self) -> None:
691 pass
692
693 def create_manifest(self):
694 root = Element(
695 'manifest:manifest',
696 attrib=MANIFEST_NAMESPACE_ATTRIB,
697 nsdict=MANIFEST_NAMESPACE_DICT,
698 )
699 doc = ET.ElementTree(root)
700 SubElement(root, 'manifest:file-entry', attrib={
701 'manifest:media-type': self.MIME_TYPE,
702 'manifest:full-path': '/',
703 }, nsdict=MANNSD)
704 SubElement(root, 'manifest:file-entry', attrib={
705 'manifest:media-type': 'text/xml',
706 'manifest:full-path': 'content.xml',
707 }, nsdict=MANNSD)
708 SubElement(root, 'manifest:file-entry', attrib={
709 'manifest:media-type': 'text/xml',
710 'manifest:full-path': 'styles.xml',
711 }, nsdict=MANNSD)
712 SubElement(root, 'manifest:file-entry', attrib={
713 'manifest:media-type': 'text/xml',
714 'manifest:full-path': 'settings.xml',
715 }, nsdict=MANNSD)
716 SubElement(root, 'manifest:file-entry', attrib={
717 'manifest:media-type': 'text/xml',
718 'manifest:full-path': 'meta.xml',
719 }, nsdict=MANNSD)
720 s1 = ToString(doc)
721 doc = minidom.parseString(s1)
722 return doc.toprettyxml(' ')
723
724 def create_meta(self):
725 root = Element(
726 'office:document-meta',
727 attrib=META_NAMESPACE_ATTRIB,
728 nsdict=META_NAMESPACE_DICT,
729 )
730 doc = ET.ElementTree(root)
731 root = SubElement(root, 'office:meta', nsdict=METNSD)
732 el1 = SubElement(root, 'meta:generator', nsdict=METNSD)
733 el1.text = 'Docutils/rst2odf.py/%s' % (VERSION, )
734 s1 = os.environ.get('USER', '')
735 el1 = SubElement(root, 'meta:initial-creator', nsdict=METNSD)
736 el1.text = s1
737 s2 = time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime())
738 el1 = SubElement(root, 'meta:creation-date', nsdict=METNSD)
739 el1.text = s2
740 el1 = SubElement(root, 'dc:creator', nsdict=METNSD)
741 el1.text = s1
742 el1 = SubElement(root, 'dc:date', nsdict=METNSD)
743 el1.text = s2
744 el1 = SubElement(root, 'dc:language', nsdict=METNSD)
745 el1.text = 'en-US'
746 el1 = SubElement(root, 'meta:editing-cycles', nsdict=METNSD)
747 el1.text = '1'
748 el1 = SubElement(root, 'meta:editing-duration', nsdict=METNSD)
749 el1.text = 'PT00M01S'
750 el1 = SubElement(root, 'dc:title', nsdict=METNSD)
751 el1.text = self.document.get('title', '[no title]')
752 for prop, value in self.visitor.get_meta_dict().items():
753 # 'keywords', 'description', and 'subject' have their own fields:
754 if prop == 'keywords':
755 keywords = re.split(', *', value)
756 for keyword in keywords:
757 el1 = SubElement(root, 'meta:keyword', nsdict=METNSD)
758 el1.text = keyword
759 elif prop == 'description':
760 el1 = SubElement(root, 'dc:description', nsdict=METNSD)
761 el1.text = value
762 elif prop == 'subject':
763 el1 = SubElement(root, 'dc:subject', nsdict=METNSD)
764 el1.text = value
765 else: # Store remaining properties as custom/user-defined
766 el1 = SubElement(root, 'meta:user-defined',
767 attrib={'meta:name': prop}, nsdict=METNSD)
768 el1.text = value
769 s1 = ToString(doc)
770 # doc = minidom.parseString(s1)
771 # s1 = doc.toprettyxml(' ')
772 return s1
773
774
775 # class ODFTranslator(nodes.SparseNodeVisitor):
776 class ODFTranslator(nodes.GenericNodeVisitor):
777
778 used_styles = (
779 'attribution', 'blockindent', 'blockquote', 'blockquote-bulletitem',
780 'blockquote-bulletlist', 'blockquote-enumitem', 'blockquote-enumlist',
781 'bulletitem', 'bulletlist',
782 'caption', 'legend',
783 'centeredtextbody', 'codeblock', 'codeblock-indented',
784 'codeblock-classname', 'codeblock-comment', 'codeblock-functionname',
785 'codeblock-keyword', 'codeblock-name', 'codeblock-number',
786 'codeblock-operator', 'codeblock-string', 'emphasis', 'enumitem',
787 'enumlist', 'epigraph', 'epigraph-bulletitem', 'epigraph-bulletlist',
788 'epigraph-enumitem', 'epigraph-enumlist', 'footer',
789 'footnote', 'citation',
790 'header', 'highlights', 'highlights-bulletitem',
791 'highlights-bulletlist', 'highlights-enumitem', 'highlights-enumlist',
792 'horizontalline', 'inlineliteral', 'quotation', 'rubric',
793 'strong', 'table-title', 'textbody', 'tocbulletlist', 'tocenumlist',
794 'title',
795 'subtitle',
796 'heading1',
797 'heading2',
798 'heading3',
799 'heading4',
800 'heading5',
801 'heading6',
802 'heading7',
803 'admon-attention-hdr',
804 'admon-attention-body',
805 'admon-caution-hdr',
806 'admon-caution-body',
807 'admon-danger-hdr',
808 'admon-danger-body',
809 'admon-error-hdr',
810 'admon-error-body',
811 'admon-generic-hdr',
812 'admon-generic-body',
813 'admon-hint-hdr',
814 'admon-hint-body',
815 'admon-important-hdr',
816 'admon-important-body',
817 'admon-note-hdr',
818 'admon-note-body',
819 'admon-tip-hdr',
820 'admon-tip-body',
821 'admon-warning-hdr',
822 'admon-warning-body',
823 'tableoption',
824 'tableoption.%c', 'tableoption.%c%d', 'Table%d', 'Table%d.%c',
825 'Table%d.%c%d',
826 'lineblock1',
827 'lineblock2',
828 'lineblock3',
829 'lineblock4',
830 'lineblock5',
831 'lineblock6',
832 'image', 'figureframe',
833 )
834
835 def __init__(self, document) -> None:
836 # nodes.SparseNodeVisitor.__init__(self, document)
837 nodes.GenericNodeVisitor.__init__(self, document)
838 self.settings = document.settings
839 if self.settings.output_encoding == 'unicode':
840 self.document.reporter.severe('The ODT writer returns `bytes` '
841 'that cannot be decoded to `str`')
842 # TODO: return document as "flat" XML?
843 self.language_code = self.settings.language_code
844 self.language = languages.get_language(
845 self.language_code,
846 document.reporter)
847 self.format_map = {}
848 if self.settings.odf_config_file:
849 parser = ConfigParser()
850 parser.read(self.settings.odf_config_file)
851 for rststyle, format in parser.items("Formats"):
852 if rststyle not in self.used_styles:
853 self.document.reporter.warning(
854 'Style "%s" is not a style used by odtwriter.' % (
855 rststyle, ))
856 self.format_map[rststyle] = format
857 self.section_level = 0
858 self.section_count = 0
859 # Create ElementTree content and styles documents.
860 root = Element(
861 'office:document-content',
862 attrib=CONTENT_NAMESPACE_ATTRIB,
863 )
864 self.content_tree = ET.ElementTree(element=root)
865 self.current_element = root
866 SubElement(root, 'office:scripts')
867 SubElement(root, 'office:font-face-decls')
868 el = SubElement(root, 'office:automatic-styles')
869 self.automatic_styles = el
870 el = SubElement(root, 'office:body')
871 el = self.generate_content_element(el)
872 self.current_element = el
873 self.body_text_element = el
874 self.paragraph_style_stack = [self.rststyle('textbody'), ]
875 self.list_style_stack = []
876 self.table_count = 0
877 self.column_count = ord('A') - 1
878 self.trace_level = -1
879 self.optiontablestyles_generated = False
880 self.field_name = None
881 self.field_element = None
882 self.title = None
883 self.image_count = 0
884 self.image_style_count = 0
885 self.image_dict = {}
886 self.embedded_file_list = []
887 self.syntaxhighlighting = 1
888 self.syntaxhighlight_lexer = 'python'
889 self.header_content = []
890 self.footer_content = []
891 self.in_header = False
892 self.in_footer = False
893 self.blockstyle = ''
894 self.in_table_of_contents = False
895 self.table_of_content_index_body = None
896 self.list_level = 0
897 self.def_list_level = 0
898 self.footnote_ref_dict = {}
899 self.footnote_list = []
900 self.footnote_chars_idx = 0
901 self.footnote_level = 0
902 self.pending_ids = []
903 self.in_paragraph = False
904 self.found_doc_title = False
905 self.bumped_list_level_stack = []
906 self.meta_dict = {}
907 self.line_block_level = 0
908 self.line_indent_level = 0
909 self.citation_id = None
910 self.style_index = 0 # use to form unique style names
911 self.str_stylesheet = ''
912 self.str_stylesheetcontent = ''
913 self.dom_stylesheet = None
914 self.table_styles = None
915 self.in_citation = False
916
917 # Keep track of nested styling classes
918 self.inline_style_count_stack = []
919
920 def get_str_stylesheet(self):
921 return self.str_stylesheet
922
923 def retrieve_styles(self, extension):
924 """Retrieve the stylesheet from a .xml or .odt (zip) file.
925
926 Store in `self.*_styles*` attributes.
927 """
928 stylespath = self.settings.stylesheet
929 ext = os.path.splitext(stylespath)[1]
930 if ext == '.xml':
931 s1 = Path(stylespath).read_text(encoding='utf-8')
932 s2 = ''
933 elif ext == extension:
934 zfile = zipfile.ZipFile(stylespath, 'r')
935 s1 = zfile.read('styles.xml')
936 s2 = zfile.read('content.xml')
937 zfile.close()
938 else:
939 raise RuntimeError('stylesheet path (%s) must be %s or '
940 '.xml file' % (stylespath, extension))
941 self.str_stylesheet = s1
942 self.str_stylesheetcontent = s2
943 self.dom_stylesheet = ET.fromstring(self.str_stylesheet)
944 if not s2:
945 return
946 # TODO: dom_stylesheetcontent is never used. Remove?
947 self.dom_stylesheetcontent = ET.fromstring(
948 self.str_stylesheetcontent)
949 self.table_styles = self.extract_table_styles(s2)
950
951 def extract_table_styles(self, styles_str):
952 root = ET.fromstring(styles_str)
953 table_styles = {}
954 auto_styles = root.find(
955 '{%s}automatic-styles' % (CNSD['office'], ))
956 for stylenode in auto_styles:
957 name = stylenode.get('{%s}name' % (CNSD['style'], ))
958 tablename = name.split('.')[0]
959 family = stylenode.get('{%s}family' % (CNSD['style'], ))
960 if name.startswith(TABLESTYLEPREFIX):
961 tablestyle = table_styles.get(tablename)
962 if tablestyle is None:
963 tablestyle = TableStyle()
964 table_styles[tablename] = tablestyle
965 if family == 'table':
966 properties = stylenode.find(
967 '{%s}table-properties' % (CNSD['style'], ))
968 property_ = properties.get(
969 '{%s}%s' % (CNSD['fo'], 'background-color', ))
970 if property_ is not None and property_ != 'none':
971 tablestyle.backgroundcolor = property_
972 elif family == 'table-cell':
973 properties = stylenode.find(
974 '{%s}table-cell-properties' % (CNSD['style'], ))
975 if properties is not None:
976 border = self.get_property(properties)
977 if border is not None:
978 tablestyle.border = border
979 return table_styles
980
981 def get_property(self, stylenode):
982 border = None
983 for propertyname in TABLEPROPERTYNAMES:
984 border = stylenode.get('{%s}%s' % (CNSD['fo'], propertyname, ))
985 if border is not None and border != 'none':
986 return border
987 return border
988
989 def add_doc_title(self) -> None:
990 text = self.settings.title
991 if text:
992 self.title = text
993 if not self.found_doc_title:
994 el = Element('text:p', attrib={
995 'text:style-name': self.rststyle('title'),
996 })
997 el.text = text
998 self.body_text_element.insert(0, el)
999 el = self.find_first_text_p(self.body_text_element)
1000 if el is not None:
1001 self.attach_page_style(el)
1002
1003 def find_first_text_p(self, el):
1004 """Search the generated doc and return the first <text:p> element.
1005 """
1006 if el.tag == 'text:p' or el.tag == 'text:h':
1007 return el
1008 else:
1009 for child in el:
1010 el1 = self.find_first_text_p(child)
1011 if el1 is not None:
1012 return el1
1013 return None
1014
1015 def attach_page_style(self, el) -> None:
1016 """Attach the default page style.
1017
1018 Create an automatic-style that refers to the current style
1019 of this element and that refers to the default page style.
1020 """
1021 current_style = el.get('text:style-name')
1022 style_name = 'P1003'
1023 el1 = SubElement(
1024 self.automatic_styles, 'style:style', attrib={
1025 'style:name': style_name,
1026 'style:master-page-name': "rststyle-pagedefault",
1027 'style:family': "paragraph",
1028 }, nsdict=SNSD)
1029 if current_style:
1030 el1.set('style:parent-style-name', current_style)
1031 el.set('text:style-name', style_name)
1032
1033 def rststyle(self, name, parameters=()):
1034 """
1035 Returns the style name to use for the given style.
1036
1037 If `parameters` is given `name` must contain a matching number of
1038 ``%`` and is used as a format expression with `parameters` as
1039 the value.
1040 """
1041 name1 = name % parameters
1042 return self.format_map.get(name1, 'rststyle-%s' % name1)
1043
1044 def generate_content_element(self, root):
1045 return SubElement(root, 'office:text')
1046
1047 def setup_page(self):
1048 self.setup_paper(self.dom_stylesheet)
1049 if (len(self.header_content) > 0
1050 or len(self.footer_content) > 0
1051 or self.settings.custom_header
1052 or self.settings.custom_footer):
1053 self.add_header_footer(self.dom_stylesheet)
1054 return ET.tostring(self.dom_stylesheet)
1055
1056 def get_dom_stylesheet(self):
1057 return self.dom_stylesheet
1058
1059 def setup_paper(self, root_el) -> None:
1060 # TODO: only call paperconf, if it is actually used
1061 # (i.e. page size removed from "styles.odt" with rst2odt_prepstyles.py
1062 # cf. conditional in walk() below)?
1063 try:
1064 dimensions = subprocess.check_output(('paperconf', '-s'),
1065 stderr=subprocess.STDOUT)
1066 w, h = (float(s) for s in dimensions.split())
1067 except (subprocess.CalledProcessError, FileNotFoundError, ValueError):
1068 self.document.reporter.info(
1069 'Cannot use `paperconf`, defaulting to Letter.')
1070 w, h = 612, 792 # default to Letter
1071
1072 def walk(el) -> None:
1073 if el.tag == "{%s}page-layout-properties" % SNSD["style"] and \
1074 "{%s}page-width" % SNSD["fo"] not in el.attrib:
1075 el.attrib["{%s}page-width" % SNSD["fo"]] = "%.3fpt" % w
1076 el.attrib["{%s}page-height" % SNSD["fo"]] = "%.3fpt" % h
1077 el.attrib["{%s}margin-left" % SNSD["fo"]] = \
1078 el.attrib["{%s}margin-right" % SNSD["fo"]] = \
1079 "%.3fpt" % (.1 * w)
1080 el.attrib["{%s}margin-top" % SNSD["fo"]] = \
1081 el.attrib["{%s}margin-bottom" % SNSD["fo"]] = \
1082 "%.3fpt" % (.1 * h)
1083 else:
1084 for subel in el:
1085 walk(subel)
1086 walk(root_el)
1087
1088 def add_header_footer(self, root_el) -> None:
1089 automatic_styles = root_el.find(
1090 '{%s}automatic-styles' % SNSD['office'])
1091 path = '{%s}master-styles' % (NAME_SPACE_1, )
1092 master_el = root_el.find(path)
1093 if master_el is None:
1094 return
1095 path = '{%s}master-page' % (SNSD['style'], )
1096 master_el_container = master_el.findall(path)
1097 master_el = None
1098 target_attrib = '{%s}name' % (SNSD['style'], )
1099 target_name = self.rststyle('pagedefault')
1100 for el in master_el_container:
1101 if el.get(target_attrib) == target_name:
1102 master_el = el
1103 break
1104 if master_el is None:
1105 return
1106 el1 = master_el
1107 if self.header_content or self.settings.custom_header:
1108 el2 = SubElement(
1109 el1, 'style:header',
1110 attrib=STYLES_NAMESPACE_ATTRIB,
1111 nsdict=STYLES_NAMESPACE_DICT,
1112 )
1113 for el in self.header_content:
1114 attrkey = add_ns('text:style-name', nsdict=SNSD)
1115 el.attrib[attrkey] = self.rststyle('header')
1116 el2.append(el)
1117 if self.settings.custom_header:
1118 self.create_custom_headfoot(
1119 el2,
1120 self.settings.custom_header, 'header', automatic_styles)
1121 if self.footer_content or self.settings.custom_footer:
1122 el2 = SubElement(
1123 el1, 'style:footer',
1124 attrib=STYLES_NAMESPACE_ATTRIB,
1125 nsdict=STYLES_NAMESPACE_DICT,
1126 )
1127 for el in self.footer_content:
1128 attrkey = add_ns('text:style-name', nsdict=SNSD)
1129 el.attrib[attrkey] = self.rststyle('footer')
1130 el2.append(el)
1131 if self.settings.custom_footer:
1132 self.create_custom_headfoot(
1133 el2,
1134 self.settings.custom_footer, 'footer', automatic_styles)
1135
1136 code_none, code_field, code_text = list(range(3))
1137 field_pat = re.compile(r'%(..?)%')
1138
1139 def create_custom_headfoot(
1140 self, parent, text, style_name, automatic_styles):
1141 parent = SubElement(parent, 'text:p', attrib={
1142 'text:style-name': self.rststyle(style_name),
1143 })
1144 current_element = None
1145 field_iter = self.split_field_specifiers_iter(text)
1146 for item in field_iter:
1147 if item[0] == ODFTranslator.code_field:
1148 if item[1] not in (
1149 'p', 'P',
1150 't1', 't2', 't3', 't4',
1151 'd1', 'd2', 'd3', 'd4', 'd5',
1152 's', 't', 'a'):
1153 msg = 'bad field spec: %%%s%%' % (item[1], )
1154 raise RuntimeError(msg)
1155 el1 = self.make_field_element(
1156 parent,
1157 item[1], style_name, automatic_styles)
1158 if el1 is None:
1159 msg = 'bad field spec: %%%s%%' % (item[1], )
1160 raise RuntimeError(msg)
1161 else:
1162 current_element = el1
1163 else:
1164 if current_element is None:
1165 parent.text = item[1]
1166 else:
1167 current_element.tail = item[1]
1168
1169 def make_field_element(self, parent, text, style_name, automatic_styles):
1170 if text == 'p':
1171 el1 = SubElement(parent, 'text:page-number', attrib={
1172 # 'text:style-name': self.rststyle(style_name),
1173 'text:select-page': 'current',
1174 })
1175 elif text == 'P':
1176 el1 = SubElement(parent, 'text:page-count', attrib={
1177 # 'text:style-name': self.rststyle(style_name),
1178 })
1179 elif text == 't1':
1180 self.style_index += 1
1181 el1 = SubElement(parent, 'text:time', attrib={
1182 'text:style-name': self.rststyle(style_name),
1183 'text:fixed': 'true',
1184 'style:data-style-name':
1185 'rst-time-style-%d' % self.style_index,
1186 })
1187 el2 = SubElement(automatic_styles, 'number:time-style', attrib={
1188 'style:name': 'rst-time-style-%d' % self.style_index,
1189 'xmlns:number': SNSD['number'],
1190 'xmlns:style': SNSD['style'],
1191 })
1192 el3 = SubElement(el2, 'number:hours', attrib={
1193 'number:style': 'long',
1194 })
1195 el3 = SubElement(el2, 'number:text')
1196 el3.text = ':'
1197 el3 = SubElement(el2, 'number:minutes', attrib={
1198 'number:style': 'long',
1199 })
1200 elif text == 't2':
1201 self.style_index += 1
1202 el1 = SubElement(parent, 'text:time', attrib={
1203 'text:style-name': self.rststyle(style_name),
1204 'text:fixed': 'true',
1205 'style:data-style-name':
1206 'rst-time-style-%d' % self.style_index,
1207 })
1208 el2 = SubElement(automatic_styles, 'number:time-style', attrib={
1209 'style:name': 'rst-time-style-%d' % self.style_index,
1210 'xmlns:number': SNSD['number'],
1211 'xmlns:style': SNSD['style'],
1212 })
1213 el3 = SubElement(el2, 'number:hours', attrib={
1214 'number:style': 'long',
1215 })
1216 el3 = SubElement(el2, 'number:text')
1217 el3.text = ':'
1218 el3 = SubElement(el2, 'number:minutes', attrib={
1219 'number:style': 'long',
1220 })
1221 el3 = SubElement(el2, 'number:text')
1222 el3.text = ':'
1223 el3 = SubElement(el2, 'number:seconds', attrib={
1224 'number:style': 'long',
1225 })
1226 elif text == 't3':
1227 self.style_index += 1
1228 el1 = SubElement(parent, 'text:time', attrib={
1229 'text:style-name': self.rststyle(style_name),
1230 'text:fixed': 'true',
1231 'style:data-style-name':
1232 'rst-time-style-%d' % self.style_index,
1233 })
1234 el2 = SubElement(automatic_styles, 'number:time-style', attrib={
1235 'style:name': 'rst-time-style-%d' % self.style_index,
1236 'xmlns:number': SNSD['number'],
1237 'xmlns:style': SNSD['style'],
1238 })
1239 el3 = SubElement(el2, 'number:hours', attrib={
1240 'number:style': 'long',
1241 })
1242 el3 = SubElement(el2, 'number:text')
1243 el3.text = ':'
1244 el3 = SubElement(el2, 'number:minutes', attrib={
1245 'number:style': 'long',
1246 })
1247 el3 = SubElement(el2, 'number:text')
1248 el3.text = ' '
1249 el3 = SubElement(el2, 'number:am-pm')
1250 elif text == 't4':
1251 self.style_index += 1
1252 el1 = SubElement(parent, 'text:time', attrib={
1253 'text:style-name': self.rststyle(style_name),
1254 'text:fixed': 'true',
1255 'style:data-style-name':
1256 'rst-time-style-%d' % self.style_index,
1257 })
1258 el2 = SubElement(automatic_styles, 'number:time-style', attrib={
1259 'style:name': 'rst-time-style-%d' % self.style_index,
1260 'xmlns:number': SNSD['number'],
1261 'xmlns:style': SNSD['style'],
1262 })
1263 el3 = SubElement(el2, 'number:hours', attrib={
1264 'number:style': 'long',
1265 })
1266 el3 = SubElement(el2, 'number:text')
1267 el3.text = ':'
1268 el3 = SubElement(el2, 'number:minutes', attrib={
1269 'number:style': 'long',
1270 })
1271 el3 = SubElement(el2, 'number:text')
1272 el3.text = ':'
1273 el3 = SubElement(el2, 'number:seconds', attrib={
1274 'number:style': 'long',
1275 })
1276 el3 = SubElement(el2, 'number:text')
1277 el3.text = ' '
1278 el3 = SubElement(el2, 'number:am-pm')
1279 elif text == 'd1':
1280 self.style_index += 1
1281 el1 = SubElement(parent, 'text:date', attrib={
1282 'text:style-name': self.rststyle(style_name),
1283 'style:data-style-name':
1284 'rst-date-style-%d' % self.style_index,
1285 })
1286 el2 = SubElement(automatic_styles, 'number:date-style', attrib={
1287 'style:name': 'rst-date-style-%d' % self.style_index,
1288 'number:automatic-order': 'true',
1289 'xmlns:number': SNSD['number'],
1290 'xmlns:style': SNSD['style'],
1291 })
1292 el3 = SubElement(el2, 'number:month', attrib={
1293 'number:style': 'long',
1294 })
1295 el3 = SubElement(el2, 'number:text')
1296 el3.text = '/'
1297 el3 = SubElement(el2, 'number:day', attrib={
1298 'number:style': 'long',
1299 })
1300 el3 = SubElement(el2, 'number:text')
1301 el3.text = '/'
1302 el3 = SubElement(el2, 'number:year')
1303 elif text == 'd2':
1304 self.style_index += 1
1305 el1 = SubElement(parent, 'text:date', attrib={
1306 'text:style-name': self.rststyle(style_name),
1307 'style:data-style-name':
1308 'rst-date-style-%d' % self.style_index,
1309 })
1310 el2 = SubElement(automatic_styles, 'number:date-style', attrib={
1311 'style:name': 'rst-date-style-%d' % self.style_index,
1312 'number:automatic-order': 'true',
1313 'xmlns:number': SNSD['number'],
1314 'xmlns:style': SNSD['style'],
1315 })
1316 el3 = SubElement(el2, 'number:month', attrib={
1317 'number:style': 'long',
1318 })
1319 el3 = SubElement(el2, 'number:text')
1320 el3.text = '/'
1321 el3 = SubElement(el2, 'number:day', attrib={
1322 'number:style': 'long',
1323 })
1324 el3 = SubElement(el2, 'number:text')
1325 el3.text = '/'
1326 el3 = SubElement(el2, 'number:year', attrib={
1327 'number:style': 'long',
1328 })
1329 elif text == 'd3':
1330 self.style_index += 1
1331 el1 = SubElement(parent, 'text:date', attrib={
1332 'text:style-name': self.rststyle(style_name),
1333 'style:data-style-name':
1334 'rst-date-style-%d' % self.style_index,
1335 })
1336 el2 = SubElement(automatic_styles, 'number:date-style', attrib={
1337 'style:name': 'rst-date-style-%d' % self.style_index,
1338 'number:automatic-order': 'true',
1339 'xmlns:number': SNSD['number'],
1340 'xmlns:style': SNSD['style'],
1341 })
1342 el3 = SubElement(el2, 'number:month', attrib={
1343 'number:textual': 'true',
1344 })
1345 el3 = SubElement(el2, 'number:text')
1346 el3.text = ' '
1347 el3 = SubElement(el2, 'number:day', attrib={})
1348 el3 = SubElement(el2, 'number:text')
1349 el3.text = ', '
1350 el3 = SubElement(el2, 'number:year', attrib={
1351 'number:style': 'long',
1352 })
1353 elif text == 'd4':
1354 self.style_index += 1
1355 el1 = SubElement(parent, 'text:date', attrib={
1356 'text:style-name': self.rststyle(style_name),
1357 'style:data-style-name':
1358 'rst-date-style-%d' % self.style_index,
1359 })
1360 el2 = SubElement(automatic_styles, 'number:date-style', attrib={
1361 'style:name': 'rst-date-style-%d' % self.style_index,
1362 'number:automatic-order': 'true',
1363 'xmlns:number': SNSD['number'],
1364 'xmlns:style': SNSD['style'],
1365 })
1366 el3 = SubElement(el2, 'number:month', attrib={
1367 'number:textual': 'true',
1368 'number:style': 'long',
1369 })
1370 el3 = SubElement(el2, 'number:text')
1371 el3.text = ' '
1372 el3 = SubElement(el2, 'number:day', attrib={})
1373 el3 = SubElement(el2, 'number:text')
1374 el3.text = ', '
1375 el3 = SubElement(el2, 'number:year', attrib={
1376 'number:style': 'long',
1377 })
1378 elif text == 'd5':
1379 self.style_index += 1
1380 el1 = SubElement(parent, 'text:date', attrib={
1381 'text:style-name': self.rststyle(style_name),
1382 'style:data-style-name':
1383 'rst-date-style-%d' % self.style_index,
1384 })
1385 el2 = SubElement(automatic_styles, 'number:date-style', attrib={
1386 'style:name': 'rst-date-style-%d' % self.style_index,
1387 'xmlns:number': SNSD['number'],
1388 'xmlns:style': SNSD['style'],
1389 })
1390 el3 = SubElement(el2, 'number:year', attrib={
1391 'number:style': 'long',
1392 })
1393 el3 = SubElement(el2, 'number:text')
1394 el3.text = '-'
1395 el3 = SubElement(el2, 'number:month', attrib={
1396 'number:style': 'long',
1397 })
1398 el3 = SubElement(el2, 'number:text')
1399 el3.text = '-'
1400 el3 = SubElement(el2, 'number:day', attrib={
1401 'number:style': 'long',
1402 })
1403 elif text == 's':
1404 el1 = SubElement(parent, 'text:subject', attrib={
1405 'text:style-name': self.rststyle(style_name),
1406 })
1407 elif text == 't':
1408 el1 = SubElement(parent, 'text:title', attrib={
1409 'text:style-name': self.rststyle(style_name),
1410 })
1411 elif text == 'a':
1412 el1 = SubElement(parent, 'text:author-name', attrib={
1413 'text:fixed': 'false',
1414 })
1415 else:
1416 el1 = None
1417 return el1
1418
1419 def split_field_specifiers_iter(self, text):
1420 pos1 = 0
1421 while True:
1422 mo = ODFTranslator.field_pat.search(text, pos1)
1423 if mo:
1424 pos2 = mo.start()
1425 if pos2 > pos1:
1426 yield ODFTranslator.code_text, text[pos1:pos2]
1427 yield ODFTranslator.code_field, mo.group(1)
1428 pos1 = mo.end()
1429 else:
1430 break
1431 trailing = text[pos1:]
1432 if trailing:
1433 yield ODFTranslator.code_text, trailing
1434
1435 def astext(self):
1436 root = self.content_tree.getroot()
1437 et = ET.ElementTree(root)
1438 return ToString(et)
1439
1440 def content_astext(self):
1441 return self.astext()
1442
1443 def set_title(self, title) -> None:
1444 self.title = title
1445
1446 def get_title(self):
1447 return self.title
1448
1449 def set_embedded_file_list(self, embedded_file_list) -> None:
1450 self.embedded_file_list = embedded_file_list
1451
1452 def get_embedded_file_list(self):
1453 return self.embedded_file_list
1454
1455 def get_meta_dict(self):
1456 return self.meta_dict
1457
1458 def process_footnotes(self) -> None:
1459 for node, el1 in self.footnote_list:
1460 backrefs = node.attributes.get('backrefs', [])
1461 first = True
1462 for ref in backrefs:
1463 el2 = self.footnote_ref_dict.get(ref)
1464 if el2 is not None:
1465 if first:
1466 first = False
1467 el3 = copy.deepcopy(el1)
1468 el2.append(el3)
1469 else:
1470 if len(el2) > 0: # and 'id' in el2.attrib:
1471 child = el2[0]
1472 ref1 = child.text
1473 attribkey = add_ns('text:id', nsdict=SNSD)
1474 id1 = el2.get(attribkey, 'footnote-error')
1475 if id1 is None:
1476 id1 = ''
1477 tag = add_ns('text:note-ref', nsdict=SNSD)
1478 el2.tag = tag
1479 if self.settings.endnotes_end_doc:
1480 note_class = 'endnote'
1481 else:
1482 note_class = 'footnote'
1483 el2.attrib.clear()
1484 attribkey = add_ns('text:note-class', nsdict=SNSD)
1485 el2.attrib[attribkey] = note_class
1486 attribkey = add_ns('text:ref-name', nsdict=SNSD)
1487 el2.attrib[attribkey] = id1
1488 attribkey = add_ns(
1489 'text:reference-format', nsdict=SNSD)
1490 el2.attrib[attribkey] = 'page'
1491 el2.text = ref1
1492
1493 #
1494 # Utility methods
1495
1496 def append_child(self, tag, attrib=None, parent=None):
1497 if parent is None:
1498 parent = self.current_element
1499 return SubElement(parent, tag, attrib)
1500
1501 def append_p(self, style, text=None):
1502 result = self.append_child('text:p', attrib={
1503 'text:style-name': self.rststyle(style)})
1504 self.append_pending_ids(result)
1505 if text is not None:
1506 result.text = text
1507 return result
1508
1509 def append_pending_ids(self, el) -> None:
1510 if self.settings.create_links:
1511 for id in self.pending_ids:
1512 SubElement(el, 'text:reference-mark', attrib={
1513 'text:name': id})
1514 self.pending_ids = []
1515
1516 def set_current_element(self, el) -> None:
1517 self.current_element = el
1518
1519 def set_to_parent(self) -> None:
1520 self.current_element = self.current_element.getparent()
1521
1522 def generate_labeled_block(self, node, label):
1523 label = '%s:' % (self.language.labels[label], )
1524 el = self.append_p('textbody')
1525 el1 = SubElement(
1526 el, 'text:span',
1527 attrib={'text:style-name': self.rststyle('strong')})
1528 el1.text = label
1529 return self.append_p('blockindent')
1530
1531 def generate_labeled_line(self, node, label):
1532 label = '%s:' % (self.language.labels[label], )
1533 el = self.append_p('textbody')
1534 el1 = SubElement(
1535 el, 'text:span',
1536 attrib={'text:style-name': self.rststyle('strong')})
1537 el1.text = label
1538 el1.tail = node.astext()
1539 return el
1540
1541 def encode(self, text):
1542 return text.replace('\n', " ")
1543
1544 #
1545 # Visitor functions
1546 #
1547 # In alphabetic order, more or less.
1548 # See docutils.docutils.nodes.node_class_names.
1549 #
1550
1551 def dispatch_visit(self, node) -> None:
1552 """Override to catch basic attributes which many nodes have."""
1553 self.handle_basic_atts(node)
1554 nodes.GenericNodeVisitor.dispatch_visit(self, node)
1555
1556 def handle_basic_atts(self, node) -> None:
1557 if isinstance(node, nodes.Element) and node['ids']:
1558 self.pending_ids += node['ids']
1559
1560 def default_visit(self, node) -> None:
1561 self.document.reporter.warning(f'missing visit_{node.tagname}',
1562 base_node=node)
1563
1564 def default_departure(self, node) -> None:
1565 self.document.reporter.warning(f'missing depart_{node.tagname}',
1566 base_node=node)
1567
1568 def visit_Text(self, node) -> None:
1569 # Skip nodes whose text has been processed in parent nodes.
1570 if isinstance(node.parent, docutils.nodes.literal_block):
1571 return
1572 text = node.astext()
1573 # Are we in mixed content? If so, add the text to the
1574 # etree tail of the previous sibling element.
1575 if len(self.current_element) > 0:
1576 if self.current_element[-1].tail:
1577 self.current_element[-1].tail += text
1578 else:
1579 self.current_element[-1].tail = text
1580 else:
1581 if self.current_element.text:
1582 self.current_element.text += text
1583 else:
1584 self.current_element.text = text
1585
1586 def depart_Text(self, node) -> None:
1587 pass
1588
1589 #
1590 # Pre-defined fields
1591 #
1592
1593 def visit_address(self, node) -> None:
1594 el = self.generate_labeled_block(node, 'address')
1595 self.set_current_element(el)
1596
1597 def depart_address(self, node) -> None:
1598 self.set_to_parent()
1599
1600 def visit_author(self, node) -> None:
1601 if isinstance(node.parent, nodes.authors):
1602 el = self.append_p('blockindent')
1603 else:
1604 el = self.generate_labeled_block(node, 'author')
1605 self.set_current_element(el)
1606
1607 def depart_author(self, node) -> None:
1608 self.set_to_parent()
1609
1610 def visit_authors(self, node) -> None:
1611 label = '%s:' % (self.language.labels['authors'], )
1612 el = self.append_p('textbody')
1613 el1 = SubElement(
1614 el, 'text:span',
1615 attrib={'text:style-name': self.rststyle('strong')})
1616 el1.text = label
1617
1618 def depart_authors(self, node) -> None:
1619 pass
1620
1621 def visit_contact(self, node) -> None:
1622 el = self.generate_labeled_block(node, 'contact')
1623 self.set_current_element(el)
1624
1625 def depart_contact(self, node) -> None:
1626 self.set_to_parent()
1627
1628 def visit_copyright(self, node) -> None:
1629 el = self.generate_labeled_block(node, 'copyright')
1630 self.set_current_element(el)
1631
1632 def depart_copyright(self, node) -> None:
1633 self.set_to_parent()
1634
1635 def visit_date(self, node) -> None:
1636 self.generate_labeled_line(node, 'date')
1637
1638 def depart_date(self, node) -> None:
1639 pass
1640
1641 def visit_organization(self, node) -> None:
1642 el = self.generate_labeled_block(node, 'organization')
1643 self.set_current_element(el)
1644
1645 def depart_organization(self, node) -> None:
1646 self.set_to_parent()
1647
1648 def visit_status(self, node) -> None:
1649 el = self.generate_labeled_block(node, 'status')
1650 self.set_current_element(el)
1651
1652 def depart_status(self, node) -> None:
1653 self.set_to_parent()
1654
1655 def visit_revision(self, node) -> None:
1656 self.generate_labeled_line(node, 'revision')
1657
1658 def depart_revision(self, node) -> None:
1659 pass
1660
1661 def visit_version(self, node) -> None:
1662 self.generate_labeled_line(node, 'version')
1663 # self.set_current_element(el)
1664
1665 def depart_version(self, node) -> None:
1666 # self.set_to_parent()
1667 pass
1668
1669 def visit_attribution(self, node) -> None:
1670 self.append_p('attribution', node.astext())
1671
1672 def depart_attribution(self, node) -> None:
1673 pass
1674
1675 def visit_block_quote(self, node) -> None:
1676 if 'epigraph' in node.attributes['classes']:
1677 self.paragraph_style_stack.append(self.rststyle('epigraph'))
1678 self.blockstyle = self.rststyle('epigraph')
1679 elif 'highlights' in node.attributes['classes']:
1680 self.paragraph_style_stack.append(self.rststyle('highlights'))
1681 self.blockstyle = self.rststyle('highlights')
1682 else:
1683 self.paragraph_style_stack.append(self.rststyle('blockquote'))
1684 self.blockstyle = self.rststyle('blockquote')
1685 self.line_indent_level += 1
1686
1687 def depart_block_quote(self, node) -> None:
1688 self.paragraph_style_stack.pop()
1689 self.blockstyle = ''
1690 self.line_indent_level -= 1
1691
1692 def visit_bullet_list(self, node) -> None:
1693 self.list_level += 1
1694 if self.in_table_of_contents:
1695 if self.settings.generate_oowriter_toc:
1696 pass
1697 else:
1698 if 'classes' in node and \
1699 'auto-toc' in node.attributes['classes']:
1700 el = SubElement(self.current_element, 'text:list', attrib={
1701 'text:style-name': self.rststyle('tocenumlist'),
1702 })
1703 self.list_style_stack.append(self.rststyle('enumitem'))
1704 else:
1705 el = SubElement(self.current_element, 'text:list', attrib={
1706 'text:style-name': self.rststyle('tocbulletlist'),
1707 })
1708 self.list_style_stack.append(self.rststyle('bulletitem'))
1709 self.set_current_element(el)
1710 else:
1711 if self.blockstyle == self.rststyle('blockquote'):
1712 el = SubElement(self.current_element, 'text:list', attrib={
1713 'text:style-name': self.rststyle('blockquote-bulletlist'),
1714 })
1715 self.list_style_stack.append(
1716 self.rststyle('blockquote-bulletitem'))
1717 elif self.blockstyle == self.rststyle('highlights'):
1718 el = SubElement(self.current_element, 'text:list', attrib={
1719 'text:style-name': self.rststyle('highlights-bulletlist'),
1720 })
1721 self.list_style_stack.append(
1722 self.rststyle('highlights-bulletitem'))
1723 elif self.blockstyle == self.rststyle('epigraph'):
1724 el = SubElement(self.current_element, 'text:list', attrib={
1725 'text:style-name': self.rststyle('epigraph-bulletlist'),
1726 })
1727 self.list_style_stack.append(
1728 self.rststyle('epigraph-bulletitem'))
1729 else:
1730 el = SubElement(self.current_element, 'text:list', attrib={
1731 'text:style-name': self.rststyle('bulletlist'),
1732 })
1733 self.list_style_stack.append(self.rststyle('bulletitem'))
1734 self.set_current_element(el)
1735
1736 def depart_bullet_list(self, node) -> None:
1737 if self.in_table_of_contents:
1738 if self.settings.generate_oowriter_toc:
1739 pass
1740 else:
1741 self.set_to_parent()
1742 self.list_style_stack.pop()
1743 else:
1744 self.set_to_parent()
1745 self.list_style_stack.pop()
1746 self.list_level -= 1
1747
1748 def visit_caption(self, node):
1749 raise nodes.SkipChildren
1750
1751 def depart_caption(self, node) -> None:
1752 pass
1753
1754 def visit_comment(self, node) -> None:
1755 el = self.append_p('textbody')
1756 el1 = SubElement(el, 'office:annotation', attrib={})
1757 el2 = SubElement(el1, 'dc:creator', attrib={})
1758 s1 = os.environ.get('USER', '')
1759 el2.text = s1
1760 el2 = SubElement(el1, 'text:p', attrib={})
1761 el2.text = node.astext()
1762
1763 def depart_comment(self, node) -> None:
1764 pass
1765
1766 def visit_compound(self, node) -> None:
1767 # The compound directive currently receives no special treatment.
1768 pass
1769
1770 def depart_compound(self, node) -> None:
1771 pass
1772
1773 def visit_container(self, node) -> None:
1774 styles = node.attributes.get('classes', ())
1775 if len(styles) > 0:
1776 self.paragraph_style_stack.append(self.rststyle(styles[0]))
1777
1778 def depart_container(self, node) -> None:
1779 styles = node.attributes.get('classes', ())
1780 if len(styles) > 0:
1781 self.paragraph_style_stack.pop()
1782
1783 def visit_decoration(self, node) -> None:
1784 pass
1785
1786 def depart_decoration(self, node) -> None:
1787 pass
1788
1789 def visit_definition_list(self, node):
1790 self.def_list_level += 1
1791 if self.list_level > 5:
1792 raise RuntimeError(
1793 'max definition list nesting level exceeded')
1794
1795 def depart_definition_list(self, node) -> None:
1796 self.def_list_level -= 1
1797
1798 def visit_definition_list_item(self, node) -> None:
1799 pass
1800
1801 def depart_definition_list_item(self, node) -> None:
1802 pass
1803
1804 def visit_term(self, node):
1805 el = self.append_p('deflist-term-%d' % self.def_list_level)
1806 el.text = node.astext()
1807 self.set_current_element(el)
1808 raise nodes.SkipChildren
1809
1810 def depart_term(self, node) -> None:
1811 self.set_to_parent()
1812
1813 def visit_definition(self, node) -> None:
1814 self.paragraph_style_stack.append(
1815 self.rststyle('deflist-def-%d' % self.def_list_level))
1816 self.bumped_list_level_stack.append(ListLevel(1))
1817
1818 def depart_definition(self, node) -> None:
1819 self.paragraph_style_stack.pop()
1820 self.bumped_list_level_stack.pop()
1821
1822 def visit_classifier(self, node) -> None:
1823 if len(self.current_element) > 0:
1824 el = self.current_element[-1]
1825 el1 = SubElement(
1826 el, 'text:span',
1827 attrib={'text:style-name': self.rststyle('emphasis')})
1828 el1.text = ' (%s)' % (node.astext(), )
1829
1830 def depart_classifier(self, node) -> None:
1831 pass
1832
1833 def visit_document(self, node) -> None:
1834 pass
1835
1836 def depart_document(self, node) -> None:
1837 self.process_footnotes()
1838
1839 def visit_docinfo(self, node) -> None:
1840 self.section_level += 1
1841 self.section_count += 1
1842 if self.settings.create_sections:
1843 el = self.append_child(
1844 'text:section', attrib={
1845 'text:name': 'Section%d' % self.section_count,
1846 'text:style-name': 'Sect%d' % self.section_level,
1847 }
1848 )
1849 self.set_current_element(el)
1850
1851 def depart_docinfo(self, node) -> None:
1852 self.section_level -= 1
1853 if self.settings.create_sections:
1854 self.set_to_parent()
1855
1856 def visit_emphasis(self, node) -> None:
1857 el = SubElement(
1858 self.current_element, 'text:span',
1859 attrib={'text:style-name': self.rststyle('emphasis')})
1860 self.set_current_element(el)
1861
1862 def depart_emphasis(self, node) -> None:
1863 self.set_to_parent()
1864
1865 def visit_enumerated_list(self, node) -> None:
1866 el1 = self.current_element
1867 if self.blockstyle == self.rststyle('blockquote'):
1868 el2 = SubElement(el1, 'text:list', attrib={
1869 'text:style-name': self.rststyle('blockquote-enumlist'),
1870 })
1871 self.list_style_stack.append(self.rststyle('blockquote-enumitem'))
1872 elif self.blockstyle == self.rststyle('highlights'):
1873 el2 = SubElement(el1, 'text:list', attrib={
1874 'text:style-name': self.rststyle('highlights-enumlist'),
1875 })
1876 self.list_style_stack.append(self.rststyle('highlights-enumitem'))
1877 elif self.blockstyle == self.rststyle('epigraph'):
1878 el2 = SubElement(el1, 'text:list', attrib={
1879 'text:style-name': self.rststyle('epigraph-enumlist'),
1880 })
1881 self.list_style_stack.append(self.rststyle('epigraph-enumitem'))
1882 else:
1883 liststylename = 'enumlist-%s' % (node.get('enumtype', 'arabic'), )
1884 el2 = SubElement(el1, 'text:list', attrib={
1885 'text:style-name': self.rststyle(liststylename),
1886 })
1887 self.list_style_stack.append(self.rststyle('enumitem'))
1888 self.set_current_element(el2)
1889
1890 def depart_enumerated_list(self, node) -> None:
1891 self.set_to_parent()
1892 self.list_style_stack.pop()
1893
1894 def visit_list_item(self, node) -> None:
1895 # If we are in a "bumped" list level, then wrap this
1896 # list in an outer lists in order to increase the
1897 # indentation level.
1898 if self.in_table_of_contents:
1899 if self.settings.generate_oowriter_toc:
1900 self.paragraph_style_stack.append(
1901 self.rststyle('contents-%d' % (self.list_level, )))
1902 else:
1903 el1 = self.append_child('text:list-item')
1904 self.set_current_element(el1)
1905 else:
1906 el1 = self.append_child('text:list-item')
1907 el3 = el1
1908 if len(self.bumped_list_level_stack) > 0:
1909 level_obj = self.bumped_list_level_stack[-1]
1910 if level_obj.get_sibling():
1911 level_obj.set_nested(False)
1912 for level_obj1 in self.bumped_list_level_stack:
1913 for idx in range(level_obj1.get_level()):
1914 el2 = self.append_child('text:list', parent=el3)
1915 el3 = self.append_child(
1916 'text:list-item', parent=el2)
1917 self.paragraph_style_stack.append(self.list_style_stack[-1])
1918 self.set_current_element(el3)
1919
1920 def depart_list_item(self, node) -> None:
1921 if self.in_table_of_contents:
1922 if self.settings.generate_oowriter_toc:
1923 self.paragraph_style_stack.pop()
1924 else:
1925 self.set_to_parent()
1926 else:
1927 if len(self.bumped_list_level_stack) > 0:
1928 level_obj = self.bumped_list_level_stack[-1]
1929 if level_obj.get_sibling():
1930 level_obj.set_nested(True)
1931 for level_obj1 in self.bumped_list_level_stack:
1932 for idx in range(level_obj1.get_level()):
1933 self.set_to_parent()
1934 self.set_to_parent()
1935 self.paragraph_style_stack.pop()
1936 self.set_to_parent()
1937
1938 def visit_header(self, node) -> None:
1939 self.in_header = True
1940
1941 def depart_header(self, node) -> None:
1942 self.in_header = False
1943
1944 def visit_footer(self, node) -> None:
1945 self.in_footer = True
1946
1947 def depart_footer(self, node) -> None:
1948 self.in_footer = False
1949
1950 def visit_field(self, node) -> None:
1951 pass
1952
1953 def depart_field(self, node) -> None:
1954 pass
1955
1956 def visit_field_list(self, node) -> None:
1957 pass
1958
1959 def depart_field_list(self, node) -> None:
1960 pass
1961
1962 def visit_field_name(self, node) -> None:
1963 el = self.append_p('textbody')
1964 el1 = SubElement(
1965 el, 'text:span',
1966 attrib={'text:style-name': self.rststyle('strong')})
1967 el1.text = node.astext()
1968
1969 def depart_field_name(self, node) -> None:
1970 pass
1971
1972 def visit_field_body(self, node) -> None:
1973 self.paragraph_style_stack.append(self.rststyle('blockindent'))
1974
1975 def depart_field_body(self, node) -> None:
1976 self.paragraph_style_stack.pop()
1977
1978 def visit_figure(self, node) -> None:
1979 pass
1980
1981 def depart_figure(self, node) -> None:
1982 pass
1983
1984 def visit_footnote(self, node) -> None:
1985 self.footnote_level += 1
1986 self.save_footnote_current = self.current_element
1987 el1 = Element('text:note-body')
1988 self.current_element = el1
1989 self.footnote_list.append((node, el1))
1990 if isinstance(node, docutils.nodes.citation):
1991 self.paragraph_style_stack.append(self.rststyle('citation'))
1992 else:
1993 self.paragraph_style_stack.append(self.rststyle('footnote'))
1994
1995 def depart_footnote(self, node) -> None:
1996 self.paragraph_style_stack.pop()
1997 self.current_element = self.save_footnote_current
1998 self.footnote_level -= 1
1999
2000 footnote_chars = [
2001 '*', '**', '***',
2002 '++', '+++',
2003 '##', '###',
2004 '@@', '@@@',
2005 ]
2006
2007 def visit_footnote_reference(self, node):
2008 if self.footnote_level <= 0:
2009 id = node.attributes['ids'][0]
2010 refid = node.attributes.get('refid')
2011 if refid is None:
2012 refid = ''
2013 if self.settings.endnotes_end_doc:
2014 note_class = 'endnote'
2015 else:
2016 note_class = 'footnote'
2017 el1 = self.append_child('text:note', attrib={
2018 'text:id': '%s' % (refid, ),
2019 'text:note-class': note_class,
2020 })
2021 note_auto = str(node.attributes.get('auto', 1))
2022 if isinstance(node, docutils.nodes.citation_reference):
2023 citation = '[%s]' % node.astext()
2024 el2 = SubElement(el1, 'text:note-citation', attrib={
2025 'text:label': citation,
2026 })
2027 el2.text = citation
2028 elif note_auto == '1':
2029 el2 = SubElement(el1, 'text:note-citation', attrib={
2030 'text:label': node.astext(),
2031 })
2032 el2.text = node.astext()
2033 elif note_auto == '*':
2034 if self.footnote_chars_idx >= len(
2035 ODFTranslator.footnote_chars):
2036 self.footnote_chars_idx = 0
2037 footnote_char = ODFTranslator.footnote_chars[
2038 self.footnote_chars_idx]
2039 self.footnote_chars_idx += 1
2040 el2 = SubElement(el1, 'text:note-citation', attrib={
2041 'text:label': footnote_char,
2042 })
2043 el2.text = footnote_char
2044 self.footnote_ref_dict[id] = el1
2045 raise nodes.SkipChildren
2046
2047 def depart_footnote_reference(self, node) -> None:
2048 pass
2049
2050 def visit_citation(self, node) -> None:
2051 self.in_citation = True
2052 for id in node.attributes['ids']:
2053 self.citation_id = id
2054 break
2055 self.paragraph_style_stack.append(self.rststyle('blockindent'))
2056 self.bumped_list_level_stack.append(ListLevel(1))
2057
2058 def depart_citation(self, node) -> None:
2059 self.citation_id = None
2060 self.paragraph_style_stack.pop()
2061 self.bumped_list_level_stack.pop()
2062 self.in_citation = False
2063
2064 def visit_citation_reference(self, node) -> None:
2065 if self.settings.create_links:
2066 id = node.attributes['refid']
2067 el = self.append_child('text:reference-ref', attrib={
2068 'text:ref-name': '%s' % (id, ),
2069 'text:reference-format': 'text',
2070 })
2071 el.text = '['
2072 self.set_current_element(el)
2073 elif self.current_element.text is None:
2074 self.current_element.text = '['
2075 else:
2076 self.current_element.text += '['
2077
2078 def depart_citation_reference(self, node) -> None:
2079 self.current_element.text += ']'
2080 if self.settings.create_links:
2081 self.set_to_parent()
2082
2083 def visit_label(self, node):
2084 if isinstance(node.parent, docutils.nodes.footnote):
2085 raise nodes.SkipChildren
2086 elif self.citation_id is not None:
2087 el = self.append_p('textbody')
2088 self.set_current_element(el)
2089 if self.settings.create_links:
2090 el0 = SubElement(el, 'text:span')
2091 el0.text = '['
2092 self.append_child('text:reference-mark-start', attrib={
2093 'text:name': '%s' % (self.citation_id, ),
2094 })
2095 else:
2096 el.text = '['
2097
2098 def depart_label(self, node) -> None:
2099 if isinstance(node.parent, docutils.nodes.footnote):
2100 pass
2101 elif self.citation_id is not None:
2102 if self.settings.create_links:
2103 self.append_child('text:reference-mark-end', attrib={
2104 'text:name': '%s' % (self.citation_id, ),
2105 })
2106 el0 = SubElement(self.current_element, 'text:span')
2107 el0.text = ']'
2108 else:
2109 self.current_element.text += ']'
2110 self.set_to_parent()
2111
2112 def visit_generated(self, node) -> None:
2113 pass
2114
2115 def depart_generated(self, node) -> None:
2116 pass
2117
2118 def check_file_exists(self, path) -> int:
2119 if os.path.exists(path):
2120 return 1
2121 else:
2122 return 0
2123
2124 def visit_image(self, node) -> None:
2125 # Capture the image file.
2126 source = node['uri']
2127 uri_parts = urllib.parse.urlparse(source)
2128 if uri_parts.scheme in ('', 'file'):
2129 source = urllib.parse.unquote(uri_parts.path)
2130 if self.settings.root_prefix and source.startswith('/'):
2131 root_prefix = Path(self.settings.root_prefix)
2132 source = (root_prefix/source[1:]).as_posix()
2133 else:
2134 # adapt relative paths
2135 docsource, line = utils.get_source_line(node)
2136 if docsource:
2137 dirname = os.path.dirname(docsource)
2138 if dirname:
2139 source = os.path.join(dirname, source)
2140 if not self.check_file_exists(source):
2141 self.document.reporter.warning(
2142 f'Cannot find image file "{source}".', base_node=node)
2143 return
2144 if source in self.image_dict:
2145 filename, destination = self.image_dict[source]
2146 else:
2147 self.image_count += 1
2148 filename = os.path.split(source)[1]
2149 destination = 'Pictures/1%08x%s' % (self.image_count, filename)
2150 if uri_parts.scheme in ('', 'file'):
2151 spec = (os.path.abspath(source), destination,)
2152 else:
2153 try:
2154 with urllib.request.urlopen(source) as imgfile:
2155 content = imgfile.read()
2156 except urllib.error.URLError as err:
2157 self.document.reporter.warning(
2158 f'Cannot open image URL "{source}". {err}',
2159 base_node=node)
2160 return
2161 with tempfile.NamedTemporaryFile('wb',
2162 delete=False) as imgfile2:
2163 imgfile2.write(content)
2164 source = imgfile2.name
2165 spec = (source, destination,)
2166 self.embedded_file_list.append(spec)
2167 self.image_dict[source] = (source, destination,)
2168 # Is this a figure (containing an image) or just a plain image?
2169 if self.in_paragraph:
2170 el1 = self.current_element
2171 else:
2172 el1 = SubElement(
2173 self.current_element, 'text:p',
2174 attrib={'text:style-name': self.rststyle('textbody')})
2175 el2 = el1
2176 if isinstance(node.parent, docutils.nodes.figure):
2177 el3, el4, el5, caption = self.generate_figure(
2178 node, source,
2179 destination, el2)
2180 attrib = {}
2181 el6, width = self.generate_image(
2182 node, source, destination,
2183 el5, attrib)
2184 if caption is not None:
2185 el6.tail = caption
2186 else: # if isinstance(node.parent, docutils.nodes.image):
2187 self.generate_image(node, source, destination, el2)
2188
2189 def depart_image(self, node) -> None:
2190 pass
2191
2192 def get_image_width_height(self, node, attr):
2193 size = None
2194 unit = None
2195 if attr in node.attributes:
2196 size = node.attributes[attr]
2197 size = size.strip()
2198 # For conversion factors, see:
2199 # http://www.unitconversion.org/unit_converter/typography-ex.html
2200 try:
2201 if size.endswith('%'):
2202 if attr == 'height':
2203 # Percentage allowed for width but not height.
2204 raise ValueError('percentage not allowed for height')
2205 size = size.rstrip(' %')
2206 size = float(size) / 100.0
2207 unit = '%'
2208 else:
2209 size, unit = self.convert_to_cm(size)
2210 except ValueError as exp:
2211 self.document.reporter.warning(
2212 f'Invalid {attr} for image: "{node.attributes[attr]}". '
2213 f'Error: "{exp}".', base_node=node)
2214 size, unit = 0.5, 'cm' # fallback to avoid consequential error
2215 return size, unit
2216
2217 def convert_to_cm(self, size):
2218 """Convert various units to centimeters.
2219
2220 Note that a call to this method should be wrapped in:
2221 try: except ValueError:
2222 """
2223 size = size.strip()
2224 if size.endswith('px'):
2225 size = float(size[:-2]) * 0.026 # convert px to cm
2226 elif size.endswith('in'):
2227 size = float(size[:-2]) * 2.54 # convert in to cm
2228 elif size.endswith('pt'):
2229 size = float(size[:-2]) * 0.035 # convert pt to cm
2230 elif size.endswith('pc'):
2231 size = float(size[:-2]) * 0.423 # convert pc to cm
2232 elif size.endswith('mm'):
2233 size = float(size[:-2]) * 0.1 # convert mm to cm
2234 elif size.endswith('Q'):
2235 size = float(size[:-1]) * 0.25 # convert Q to cm
2236 elif size.endswith('cm'):
2237 size = float(size[:-2])
2238 elif size[-1:] in '0123456789.': # no unit, use px
2239 size = float(size) * 0.026 # convert px to cm
2240 else:
2241 raise ValueError('unit not supported with ODT')
2242 unit = 'cm'
2243 return size, unit
2244
2245 def get_image_scale(self, node):
2246 if 'scale' in node.attributes:
2247 scale = node.attributes['scale']
2248 if scale < 1:
2249 self.document.reporter.warning(
2250 f'scale out of range ({scale}), using 1.', base_node=node)
2251 scale = 1
2252 scale = scale * 0.01
2253 else:
2254 scale = 1.0
2255 return scale
2256
2257 def get_image_scaled_width_height(self, node, source):
2258 """Return the image size in centimeters adjusted by image attrs."""
2259 scale = self.get_image_scale(node)
2260 width, width_unit = self.get_image_width_height(node, 'width')
2261 height, _ = self.get_image_width_height(node, 'height')
2262 dpi = (96, 96) # image resolution in pixel per inch
2263 if width is None or height is None:
2264 if PIL is None:
2265 self.document.reporter.warning(
2266 'image size not fully specified and PIL not installed',
2267 base_node=node)
2268 return '0.5cm', '0.5cm' # prevent consequential error
2269 filename, destination = self.image_dict[source]
2270 with PIL.Image.open(filename, 'r') as img:
2271 img_size = img.size
2272 dpi = img.info.get('dpi', dpi)
2273 # dpi information can be (xdpi, ydpi) or xydpi
2274 try:
2275 iter(dpi)
2276 except TypeError:
2277 dpi = (dpi, dpi)
2278 # TODO: use dpi when converting px to cm
2279 if width is None:
2280 width = img_size[0] * 0.026 # convert px to cm
2281 if height is None and width_unit != '%':
2282 height = img_size[1] * 0.026 # convert px to cm
2283 if width_unit == '%':
2284 factor = width
2285 line_width = self.get_page_width()
2286 width = factor * line_width
2287 if height is None:
2288 # scale proportionally
2289 image_width = img_size[0] * 0.026 # convert px to cm
2290 image_height = img_size[1] * 0.026 # convert px to cm
2291 factor = (factor * line_width) / image_width
2292 height = factor * image_height
2293 width *= scale
2294 height *= scale
2295 width = '%.2fcm' % width
2296 height = '%.2fcm' % height
2297 return width, height
2298
2299 def get_page_width(self):
2300 """Return the document's page width in centimeters."""
2301 root = self.get_dom_stylesheet()
2302 nodes = root.iterfind(
2303 './/{urn:oasis:names:tc:opendocument:xmlns:style:1.0}'
2304 'page-layout/'
2305 '{urn:oasis:names:tc:opendocument:xmlns:style:1.0}'
2306 'page-layout-properties')
2307 width = None
2308 for node in nodes:
2309 page_width = node.get(
2310 '{urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0}'
2311 'page-width')
2312 margin_left = node.get(
2313 '{urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0}'
2314 'margin-left')
2315 margin_right = node.get(
2316 '{urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0}'
2317 'margin-right')
2318 if (page_width is None
2319 or margin_left is None
2320 or margin_right is None):
2321 continue
2322 try:
2323 page_width, _ = self.convert_to_cm(page_width)
2324 margin_left, _ = self.convert_to_cm(margin_left)
2325 margin_right, _ = self.convert_to_cm(margin_right)
2326 except ValueError:
2327 self.document.reporter.warning(
2328 'Stylesheet file contains invalid page width '
2329 'or margin size.')
2330 width = page_width - margin_left - margin_right
2331 if width is None:
2332 # We can't find the width in styles, so we make a guess.
2333 # Use a width of 6 in = 15.24 cm.
2334 width = 15.24
2335 return width
2336
2337 def generate_figure(self, node, source, destination, current_element):
2338 caption = None
2339 width, height = self.get_image_scaled_width_height(node, source)
2340 for node1 in node.parent.children:
2341 if node1.tagname == 'caption':
2342 caption = node1.astext()
2343 self.image_style_count += 1
2344 #
2345 # Add the style for the caption.
2346 if caption is not None:
2347 attrib = {
2348 'style:class': 'extra',
2349 'style:family': 'paragraph',
2350 'style:name': 'Caption',
2351 'style:parent-style-name': 'Standard',
2352 }
2353 el1 = SubElement(self.automatic_styles, 'style:style',
2354 attrib=attrib, nsdict=SNSD)
2355 attrib = {
2356 'fo:margin-bottom': '0.0835in',
2357 'fo:margin-top': '0.0835in',
2358 'text:line-number': '0',
2359 'text:number-lines': 'false',
2360 }
2361 SubElement(el1, 'style:paragraph-properties',
2362 attrib=attrib, nsdict=SNSD)
2363 attrib = {
2364 'fo:font-size': '12pt',
2365 'fo:font-style': 'italic',
2366 'style:font-name': 'Times',
2367 'style:font-name-complex': 'Lucidasans1',
2368 'style:font-size-asian': '12pt',
2369 'style:font-size-complex': '12pt',
2370 'style:font-style-asian': 'italic',
2371 'style:font-style-complex': 'italic',
2372 }
2373 SubElement(el1, 'style:text-properties',
2374 attrib=attrib, nsdict=SNSD)
2375 style_name = 'rstframestyle%d' % self.image_style_count
2376 draw_name = 'graphics%d' % next(IMAGE_NAME_COUNTER)
2377 # Add the styles
2378 attrib = {
2379 'style:name': style_name,
2380 'style:family': 'graphic',
2381 'style:parent-style-name': self.rststyle('figureframe'),
2382 }
2383 el1 = SubElement(self.automatic_styles,
2384 'style:style', attrib=attrib, nsdict=SNSD)
2385 attrib = {}
2386 wrap = False
2387 classes = node.parent.attributes.get('classes')
2388 if classes and 'wrap' in classes:
2389 wrap = True
2390 if wrap:
2391 attrib['style:wrap'] = 'dynamic'
2392 else:
2393 attrib['style:wrap'] = 'none'
2394 SubElement(el1, 'style:graphic-properties',
2395 attrib=attrib, nsdict=SNSD)
2396 attrib = {
2397 'draw:style-name': style_name,
2398 'draw:name': draw_name,
2399 'text:anchor-type': 'paragraph',
2400 'draw:z-index': '0',
2401 }
2402 attrib['svg:width'] = width
2403 el3 = SubElement(current_element, 'draw:frame', attrib=attrib)
2404 attrib = {}
2405 el4 = SubElement(el3, 'draw:text-box', attrib=attrib)
2406 attrib = {
2407 'text:style-name': self.rststyle('caption'),
2408 }
2409 el5 = SubElement(el4, 'text:p', attrib=attrib)
2410 return el3, el4, el5, caption
2411
2412 def generate_image(self, node, source, destination, current_element,
2413 frame_attrs=None):
2414 width, height = self.get_image_scaled_width_height(node, source)
2415 self.image_style_count += 1
2416 style_name = 'rstframestyle%d' % self.image_style_count
2417 # Add the style.
2418 attrib = {
2419 'style:name': style_name,
2420 'style:family': 'graphic',
2421 'style:parent-style-name': self.rststyle('image'),
2422 }
2423 el1 = SubElement(self.automatic_styles,
2424 'style:style', attrib=attrib, nsdict=SNSD)
2425 halign = None
2426 valign = None
2427 if 'align' in node.attributes:
2428 align = node.attributes['align'].split()
2429 for val in align:
2430 if val in ('left', 'center', 'right'):
2431 halign = val
2432 elif val in ('top', 'middle', 'bottom'):
2433 valign = val
2434 if frame_attrs is None:
2435 attrib = {
2436 'style:vertical-pos': 'top',
2437 'style:vertical-rel': 'paragraph',
2438 'style:horizontal-rel': 'paragraph',
2439 'style:mirror': 'none',
2440 'fo:clip': 'rect(0cm 0cm 0cm 0cm)',
2441 'draw:luminance': '0%',
2442 'draw:contrast': '0%',
2443 'draw:red': '0%',
2444 'draw:green': '0%',
2445 'draw:blue': '0%',
2446 'draw:gamma': '100%',
2447 'draw:color-inversion': 'false',
2448 'draw:image-opacity': '100%',
2449 'draw:color-mode': 'standard',
2450 }
2451 else:
2452 attrib = frame_attrs
2453 if halign is not None:
2454 attrib['style:horizontal-pos'] = halign
2455 if valign is not None:
2456 attrib['style:vertical-pos'] = valign
2457 # If there is a classes/wrap directive or we are
2458 # inside a table, add a no-wrap style.
2459 wrap = False
2460 classes = node.attributes.get('classes')
2461 if classes and 'wrap' in classes:
2462 wrap = True
2463 if wrap:
2464 attrib['style:wrap'] = 'dynamic'
2465 else:
2466 attrib['style:wrap'] = 'none'
2467 # If we are inside a table, add a no-wrap style.
2468 if self.is_in_table(node):
2469 attrib['style:wrap'] = 'none'
2470 SubElement(el1, 'style:graphic-properties',
2471 attrib=attrib, nsdict=SNSD)
2472 draw_name = 'graphics%d' % next(IMAGE_NAME_COUNTER)
2473 # Add the content.
2474 # el = SubElement(current_element, 'text:p',
2475 # attrib={'text:style-name': self.rststyle('textbody')})
2476 attrib = {
2477 'draw:style-name': style_name,
2478 'draw:name': draw_name,
2479 'draw:z-index': '1',
2480 }
2481 if isinstance(node.parent, nodes.TextElement):
2482 attrib['text:anchor-type'] = 'as-char' # vds
2483 else:
2484 attrib['text:anchor-type'] = 'paragraph'
2485 attrib['svg:width'] = width
2486 attrib['svg:height'] = height
2487 el1 = SubElement(current_element, 'draw:frame', attrib=attrib)
2488 SubElement(el1, 'draw:image', attrib={
2489 'xlink:href': '%s' % (destination, ),
2490 'xlink:type': 'simple',
2491 'xlink:show': 'embed',
2492 'xlink:actuate': 'onLoad',
2493 })
2494 return el1, width
2495
2496 def is_in_table(self, node) -> bool:
2497 node1 = node.parent
2498 while node1:
2499 if isinstance(node1, docutils.nodes.entry):
2500 return True
2501 node1 = node1.parent
2502 return False
2503
2504 def visit_legend(self, node) -> None:
2505 if isinstance(node.parent, docutils.nodes.figure):
2506 el1 = self.current_element[-1]
2507 el1 = el1[0][0]
2508 self.current_element = el1
2509 self.paragraph_style_stack.append(self.rststyle('legend'))
2510
2511 def depart_legend(self, node) -> None:
2512 if isinstance(node.parent, docutils.nodes.figure):
2513 self.paragraph_style_stack.pop()
2514 self.set_to_parent()
2515 self.set_to_parent()
2516 self.set_to_parent()
2517
2518 def visit_line_block(self, node) -> None:
2519 self.line_indent_level += 1
2520 self.line_block_level += 1
2521
2522 def depart_line_block(self, node) -> None:
2523 self.line_indent_level -= 1
2524 self.line_block_level -= 1
2525
2526 def visit_line(self, node) -> None:
2527 style = 'lineblock%d' % self.line_indent_level
2528 el1 = SubElement(self.current_element, 'text:p',
2529 attrib={'text:style-name': self.rststyle(style), })
2530 self.current_element = el1
2531
2532 def depart_line(self, node) -> None:
2533 self.set_to_parent()
2534
2535 def visit_literal(self, node) -> None:
2536 el = SubElement(
2537 self.current_element, 'text:span',
2538 attrib={'text:style-name': self.rststyle('inlineliteral')})
2539 self.set_current_element(el)
2540
2541 def depart_literal(self, node) -> None:
2542 self.set_to_parent()
2543
2544 def visit_inline(self, node) -> None:
2545 styles = node.attributes.get('classes', ())
2546 if styles:
2547 el = self.current_element
2548 for inline_style in styles:
2549 el = SubElement(el, 'text:span',
2550 attrib={'text:style-name':
2551 self.rststyle(inline_style)})
2552 count = len(styles)
2553 else:
2554 # No style was specified so use a default style (old code
2555 # crashed if no style was given)
2556 el = SubElement(self.current_element, 'text:span')
2557 count = 1
2558
2559 self.set_current_element(el)
2560 self.inline_style_count_stack.append(count)
2561
2562 def depart_inline(self, node) -> None:
2563 count = self.inline_style_count_stack.pop()
2564 for x in range(count):
2565 self.set_to_parent()
2566
2567 def _calculate_code_block_padding(self, line):
2568 count = 0
2569 matchobj = SPACES_PATTERN.match(line)
2570 if matchobj:
2571 pad = matchobj.group()
2572 count = len(pad)
2573 else:
2574 matchobj = TABS_PATTERN.match(line)
2575 if matchobj:
2576 pad = matchobj.group()
2577 count = len(pad) * 8
2578 return count
2579
2580 def _add_syntax_highlighting(self, insource, language):
2581 lexer = pygments.lexers.get_lexer_by_name(language, stripall=True)
2582 if language in ('latex', 'tex'):
2583 fmtr = OdtPygmentsLaTeXFormatter(
2584 self.rststyle, escape_function=escape_cdata
2585 )
2586 else:
2587 fmtr = OdtPygmentsProgFormatter(
2588 self.rststyle, escape_function=escape_cdata
2589 )
2590 return pygments.highlight(insource, lexer, fmtr)
2591
2592 def fill_line(self, line):
2593 line = FILL_PAT1.sub(self.fill_func1, line)
2594 return FILL_PAT2.sub(self.fill_func2, line)
2595
2596 def fill_func1(self, matchobj) -> str:
2597 spaces = matchobj.group(0)
2598 return '<text:s text:c="%d"/>' % (len(spaces), )
2599
2600 def fill_func2(self, matchobj) -> str:
2601 spaces = matchobj.group(0)
2602 return ' <text:s text:c="%d"/>' % (len(spaces) - 1, )
2603
2604 def visit_literal_block(self, node) -> None:
2605 if len(self.paragraph_style_stack) > 1:
2606 wrapper1 = '<text:p text:style-name="%s">%%s</text:p>' % (
2607 self.rststyle('codeblock-indented'), )
2608 else:
2609 wrapper1 = '<text:p text:style-name="%s">%%s</text:p>' % (
2610 self.rststyle('codeblock'), )
2611 source = node.astext()
2612 if (pygments and self.settings.add_syntax_highlighting):
2613 language = node.get('language', 'python')
2614 source = self._add_syntax_highlighting(source, language)
2615 else:
2616 source = escape_cdata(source)
2617 lines = source.split('\n')
2618 # If there is an empty last line, remove it.
2619 if lines[-1] == '':
2620 del lines[-1]
2621 lines1 = ['<wrappertag1 xmlns:text="urn:oasis:names:tc:'
2622 'opendocument:xmlns:text:1.0">']
2623 my_lines = []
2624 for my_line in lines:
2625 my_line = self.fill_line(my_line)
2626 my_line = my_line.replace("&#10;", "\n")
2627 my_lines.append(my_line)
2628 my_lines_str = '<text:line-break/>'.join(my_lines)
2629 my_lines_str2 = wrapper1 % (my_lines_str, )
2630 lines1.extend((my_lines_str2, '</wrappertag1>'))
2631 s1 = ''.join(lines1)
2632 s1 = s1.encode("utf-8")
2633 el1 = ET.fromstring(s1)
2634 for child in el1:
2635 self.current_element.append(child)
2636
2637 def depart_literal_block(self, node) -> None:
2638 pass
2639
2640 visit_doctest_block = visit_literal_block
2641 depart_doctest_block = depart_literal_block
2642
2643 # placeholder for math (see docs/dev/todo.rst)
2644 def visit_math(self, node) -> None:
2645 self.document.reporter.warning('"math" role not supported',
2646 base_node=node)
2647 self.visit_literal(node)
2648
2649 def depart_math(self, node) -> None:
2650 self.depart_literal(node)
2651
2652 def visit_math_block(self, node) -> None:
2653 self.document.reporter.warning('"math" directive not supported',
2654 base_node=node)
2655 self.visit_literal_block(node)
2656
2657 def depart_math_block(self, node) -> None:
2658 self.depart_literal_block(node)
2659
2660 def visit_meta(self, node) -> None:
2661 name = node.attributes.get('name')
2662 content = node.attributes.get('content')
2663 if name is not None and content is not None:
2664 self.meta_dict[name] = content
2665
2666 def depart_meta(self, node) -> None:
2667 pass
2668
2669 def visit_option_list(self, node) -> None:
2670 table_name = 'tableoption'
2671 #
2672 # Generate automatic styles
2673 if not self.optiontablestyles_generated:
2674 self.optiontablestyles_generated = True
2675 el = SubElement(self.automatic_styles, 'style:style', attrib={
2676 'style:name': self.rststyle(table_name),
2677 'style:family': 'table'}, nsdict=SNSD)
2678 el1 = SubElement(el, 'style:table-properties', attrib={
2679 'style:width': '17.59cm',
2680 'table:align': 'left',
2681 'style:shadow': 'none'}, nsdict=SNSD)
2682 el = SubElement(self.automatic_styles, 'style:style', attrib={
2683 'style:name': self.rststyle('%s.%%c' % table_name, ('A', )),
2684 'style:family': 'table-column'}, nsdict=SNSD)
2685 el1 = SubElement(el, 'style:table-column-properties', attrib={
2686 'style:column-width': '4.999cm'}, nsdict=SNSD)
2687 el = SubElement(self.automatic_styles, 'style:style', attrib={
2688 'style:name': self.rststyle('%s.%%c' % table_name, ('B', )),
2689 'style:family': 'table-column'}, nsdict=SNSD)
2690 el1 = SubElement(el, 'style:table-column-properties', attrib={
2691 'style:column-width': '12.587cm'}, nsdict=SNSD)
2692 el = SubElement(self.automatic_styles, 'style:style', attrib={
2693 'style:name': self.rststyle(
2694 '%s.%%c%%d' % table_name, ('A', 1, )),
2695 'style:family': 'table-cell'}, nsdict=SNSD)
2696 el1 = SubElement(el, 'style:table-cell-properties', attrib={
2697 'fo:background-color': 'transparent',
2698 'fo:padding': '0.097cm',
2699 'fo:border-left': '0.035cm solid #000000',
2700 'fo:border-right': 'none',
2701 'fo:border-top': '0.035cm solid #000000',
2702 'fo:border-bottom': '0.035cm solid #000000'}, nsdict=SNSD)
2703 el2 = SubElement(el1, 'style:background-image', nsdict=SNSD)
2704 el = SubElement(self.automatic_styles, 'style:style', attrib={
2705 'style:name': self.rststyle(
2706 '%s.%%c%%d' % table_name, ('B', 1, )),
2707 'style:family': 'table-cell'}, nsdict=SNSD)
2708 el1 = SubElement(el, 'style:table-cell-properties', attrib={
2709 'fo:padding': '0.097cm',
2710 'fo:border': '0.035cm solid #000000'}, nsdict=SNSD)
2711 el = SubElement(self.automatic_styles, 'style:style', attrib={
2712 'style:name': self.rststyle(
2713 '%s.%%c%%d' % table_name, ('A', 2, )),
2714 'style:family': 'table-cell'}, nsdict=SNSD)
2715 el1 = SubElement(el, 'style:table-cell-properties', attrib={
2716 'fo:padding': '0.097cm',
2717 'fo:border-left': '0.035cm solid #000000',
2718 'fo:border-right': 'none',
2719 'fo:border-top': 'none',
2720 'fo:border-bottom': '0.035cm solid #000000'}, nsdict=SNSD)
2721 el = SubElement(self.automatic_styles, 'style:style', attrib={
2722 'style:name': self.rststyle(
2723 '%s.%%c%%d' % table_name, ('B', 2, )),
2724 'style:family': 'table-cell'}, nsdict=SNSD)
2725 el1 = SubElement(el, 'style:table-cell-properties', attrib={
2726 'fo:padding': '0.097cm',
2727 'fo:border-left': '0.035cm solid #000000',
2728 'fo:border-right': '0.035cm solid #000000',
2729 'fo:border-top': 'none',
2730 'fo:border-bottom': '0.035cm solid #000000'}, nsdict=SNSD)
2731 #
2732 # Generate table data
2733 el = self.append_child('table:table', attrib={
2734 'table:name': self.rststyle(table_name),
2735 'table:style-name': self.rststyle(table_name),
2736 })
2737 el1 = SubElement(el, 'table:table-column', attrib={
2738 'table:style-name': self.rststyle(
2739 '%s.%%c' % table_name, ('A', ))})
2740 el1 = SubElement(el, 'table:table-column', attrib={
2741 'table:style-name': self.rststyle(
2742 '%s.%%c' % table_name, ('B', ))})
2743 el1 = SubElement(el, 'table:table-header-rows')
2744 el2 = SubElement(el1, 'table:table-row')
2745 el3 = SubElement(el2, 'table:table-cell', attrib={
2746 'table:style-name': self.rststyle(
2747 '%s.%%c%%d' % table_name, ('A', 1, )),
2748 'office:value-type': 'string'})
2749 el4 = SubElement(el3, 'text:p', attrib={
2750 'text:style-name': 'Table_20_Heading'})
2751 el4.text = 'Option'
2752 el3 = SubElement(el2, 'table:table-cell', attrib={
2753 'table:style-name': self.rststyle(
2754 '%s.%%c%%d' % table_name, ('B', 1, )),
2755 'office:value-type': 'string'})
2756 el4 = SubElement(el3, 'text:p', attrib={
2757 'text:style-name': 'Table_20_Heading'})
2758 el4.text = 'Description'
2759 self.set_current_element(el)
2760
2761 def depart_option_list(self, node) -> None:
2762 self.set_to_parent()
2763
2764 def visit_option_list_item(self, node) -> None:
2765 el = self.append_child('table:table-row')
2766 self.set_current_element(el)
2767
2768 def depart_option_list_item(self, node) -> None:
2769 self.set_to_parent()
2770
2771 def visit_option_group(self, node) -> None:
2772 el = self.append_child('table:table-cell', attrib={
2773 'table:style-name': 'Table%d.A2' % self.table_count,
2774 'office:value-type': 'string',
2775 })
2776 self.set_current_element(el)
2777
2778 def depart_option_group(self, node) -> None:
2779 self.set_to_parent()
2780
2781 def visit_option(self, node) -> None:
2782 el = self.append_child('text:p', attrib={
2783 'text:style-name': 'Table_20_Contents'})
2784 el.text = node.astext()
2785
2786 def depart_option(self, node) -> None:
2787 pass
2788
2789 def visit_option_string(self, node) -> None:
2790 pass
2791
2792 def depart_option_string(self, node) -> None:
2793 pass
2794
2795 def visit_option_argument(self, node) -> None:
2796 pass
2797
2798 def depart_option_argument(self, node) -> None:
2799 pass
2800
2801 def visit_description(self, node):
2802 el = self.append_child('table:table-cell', attrib={
2803 'table:style-name': 'Table%d.B2' % self.table_count,
2804 'office:value-type': 'string',
2805 })
2806 el1 = SubElement(el, 'text:p', attrib={
2807 'text:style-name': 'Table_20_Contents'})
2808 el1.text = node.astext()
2809 raise nodes.SkipChildren
2810
2811 def depart_description(self, node) -> None:
2812 pass
2813
2814 def visit_paragraph(self, node) -> None:
2815 self.in_paragraph = True
2816 if self.in_header:
2817 el = self.append_p('header')
2818 elif self.in_footer:
2819 el = self.append_p('footer')
2820 else:
2821 style_name = self.paragraph_style_stack[-1]
2822 el = self.append_child(
2823 'text:p',
2824 attrib={'text:style-name': style_name})
2825 self.append_pending_ids(el)
2826 self.set_current_element(el)
2827
2828 def depart_paragraph(self, node) -> None:
2829 self.in_paragraph = False
2830 self.set_to_parent()
2831 if self.in_header:
2832 self.header_content.append(self.current_element[-1])
2833 self.current_element.remove(self.current_element[-1])
2834 elif self.in_footer:
2835 self.footer_content.append(self.current_element[-1])
2836 self.current_element.remove(self.current_element[-1])
2837
2838 def visit_problematic(self, node) -> None:
2839 pass
2840
2841 def depart_problematic(self, node) -> None:
2842 pass
2843
2844 def visit_raw(self, node):
2845 if 'format' in node.attributes:
2846 formats = node.attributes['format']
2847 formatlist = formats.split()
2848 if 'odt' in formatlist:
2849 rawstr = node.astext()
2850 attrstr = ' '.join(
2851 '%s="%s"' % (k, v, )
2852 for k, v in list(CONTENT_NAMESPACE_ATTRIB.items()))
2853 contentstr = '<stuff %s>%s</stuff>' % (attrstr, rawstr, )
2854 contentstr = contentstr.encode("utf-8")
2855 content = ET.fromstring(contentstr)
2856 if len(content) > 0:
2857 el1 = content[0]
2858 if self.in_header:
2859 pass
2860 elif self.in_footer:
2861 pass
2862 else:
2863 self.current_element.append(el1)
2864 raise nodes.SkipChildren
2865
2866 def depart_raw(self, node) -> None:
2867 if self.in_header:
2868 pass
2869 elif self.in_footer:
2870 pass
2871 else:
2872 pass
2873
2874 def visit_reference(self, node) -> None:
2875 # text = node.astext()
2876 if self.settings.create_links:
2877 if 'refuri' in node:
2878 href = node['refuri']
2879 if (self.settings.cloak_email_addresses
2880 and href.startswith('mailto:')):
2881 href = self.cloak_mailto(href)
2882 el = self.append_child('text:a', attrib={
2883 'xlink:href': '%s' % href,
2884 'xlink:type': 'simple',
2885 })
2886 self.set_current_element(el)
2887 elif 'refid' in node:
2888 if self.settings.create_links:
2889 href = node['refid']
2890 el = self.append_child('text:reference-ref', attrib={
2891 'text:ref-name': '%s' % href,
2892 'text:reference-format': 'text',
2893 })
2894 else:
2895 self.document.reporter.warning(
2896 'References must have "refuri" or "refid" attribute.',
2897 base_node=node)
2898 if (self.in_table_of_contents
2899 and len(node.children) >= 1
2900 and isinstance(node.children[0], docutils.nodes.generated)):
2901 node.remove(node.children[0])
2902
2903 def depart_reference(self, node) -> None:
2904 if self.settings.create_links:
2905 if 'refuri' in node:
2906 self.set_to_parent()
2907
2908 def visit_rubric(self, node) -> None:
2909 style_name = self.rststyle('rubric')
2910 classes = node.get('classes')
2911 if classes:
2912 class1 = classes[0]
2913 if class1:
2914 style_name = class1
2915 el = SubElement(self.current_element, 'text:h', attrib={
2916 # 'text:outline-level': '%d' % section_level,
2917 # 'text:style-name': 'Heading_20_%d' % section_level,
2918 'text:style-name': style_name,
2919 })
2920 text = node.astext()
2921 el.text = self.encode(text)
2922
2923 def depart_rubric(self, node) -> None:
2924 pass
2925
2926 def visit_section(self, node, move_ids=1) -> None:
2927 self.section_level += 1
2928 self.section_count += 1
2929 if self.settings.create_sections:
2930 el = self.append_child('text:section', attrib={
2931 'text:name': 'Section%d' % self.section_count,
2932 'text:style-name': 'Sect%d' % self.section_level,
2933 })
2934 self.set_current_element(el)
2935
2936 def depart_section(self, node) -> None:
2937 self.section_level -= 1
2938 if self.settings.create_sections:
2939 self.set_to_parent()
2940
2941 def visit_strong(self, node) -> None:
2942 el = SubElement(self.current_element, 'text:span',
2943 attrib={'text:style-name': self.rststyle('strong')})
2944 self.set_current_element(el)
2945
2946 def depart_strong(self, node) -> None:
2947 self.set_to_parent()
2948
2949 def visit_substitution_definition(self, node):
2950 raise nodes.SkipChildren
2951
2952 def depart_substitution_definition(self, node) -> None:
2953 pass
2954
2955 def visit_system_message(self, node) -> None:
2956 pass
2957
2958 def depart_system_message(self, node) -> None:
2959 pass
2960
2961 def get_table_style(self, node):
2962 table_style = None
2963 table_name = None
2964 str_classes = node.get('classes')
2965 if str_classes is not None:
2966 for str_class in str_classes:
2967 if str_class.startswith(TABLESTYLEPREFIX):
2968 table_name = str_class
2969 break
2970 if table_name is not None:
2971 table_style = self.table_styles.get(table_name)
2972 if table_style is None:
2973 # If we can't find the table style, issue warning
2974 # and use the default table style.
2975 self.document.reporter.warning(
2976 f'Can\'t find table style "{table_name}". Using default.',
2977 base_node=node)
2978 table_name = TABLENAMEDEFAULT
2979 table_style = self.table_styles.get(table_name)
2980 if table_style is None:
2981 # If we can't find the default table style, issue a warning
2982 # and use a built-in default style.
2983 self.document.reporter.warning(
2984 f'Can\'t find default table style "{table_name}". '
2985 'Using built-in default.', base_node=node)
2986 table_style = BUILTIN_DEFAULT_TABLE_STYLE
2987 else:
2988 table_name = TABLENAMEDEFAULT
2989 table_style = self.table_styles.get(table_name)
2990 if table_style is None:
2991 # If we can't find the default table style, issue a warning
2992 # and use a built-in default style.
2993 self.document.reporter.warning(
2994 'Can\'t find default table style "{table_name}". '
2995 'Using built-in default.', base_node=node)
2996 table_style = BUILTIN_DEFAULT_TABLE_STYLE
2997 return table_style
2998
2999 def visit_table(self, node) -> None:
3000 self.table_count += 1
3001 table_style = self.get_table_style(node)
3002 table_name = '%s%%d' % TABLESTYLEPREFIX
3003 el1 = SubElement(self.automatic_styles, 'style:style', attrib={
3004 'style:name': self.rststyle(
3005 '%s' % table_name, (self.table_count, )),
3006 'style:family': 'table',
3007 }, nsdict=SNSD)
3008 if table_style.backgroundcolor is None:
3009 SubElement(el1, 'style:table-properties', attrib={
3010 # 'style:width': '17.59cm',
3011 # 'table:align': 'margins',
3012 'table:align': 'left',
3013 'fo:margin-top': '0in',
3014 'fo:margin-bottom': '0.10in',
3015 }, nsdict=SNSD)
3016 else:
3017 SubElement(el1, 'style:table-properties', attrib={
3018 # 'style:width': '17.59cm',
3019 'table:align': 'margins',
3020 'fo:margin-top': '0in',
3021 'fo:margin-bottom': '0.10in',
3022 'fo:background-color': table_style.backgroundcolor,
3023 }, nsdict=SNSD)
3024 # We use a single cell style for all cells in this table.
3025 # That's probably not correct, but seems to work.
3026 el2 = SubElement(self.automatic_styles, 'style:style', attrib={
3027 'style:name': self.rststyle(
3028 '%s.%%c%%d' % table_name, (self.table_count, 'A', 1, )),
3029 'style:family': 'table-cell',
3030 }, nsdict=SNSD)
3031 thickness = self.settings.table_border_thickness
3032 if thickness is None:
3033 line_style1 = table_style.border
3034 else:
3035 line_style1 = '0.%03dcm solid #000000' % (thickness, )
3036 SubElement(el2, 'style:table-cell-properties', attrib={
3037 'fo:padding': '0.049cm',
3038 'fo:border-left': line_style1,
3039 'fo:border-right': line_style1,
3040 'fo:border-top': line_style1,
3041 'fo:border-bottom': line_style1,
3042 }, nsdict=SNSD)
3043 title = None
3044 for child in node.children:
3045 if child.tagname == 'title':
3046 title = child.astext()
3047 break
3048 if title is not None:
3049 self.append_p('table-title', title)
3050 else:
3051 pass
3052 el4 = SubElement(self.current_element, 'table:table', attrib={
3053 'table:name': self.rststyle(
3054 '%s' % table_name, (self.table_count, )),
3055 'table:style-name': self.rststyle(
3056 '%s' % table_name, (self.table_count, )),
3057 })
3058 self.set_current_element(el4)
3059 self.current_table_style = el1
3060 self.table_width = 0.0
3061
3062 def depart_table(self, node) -> None:
3063 attribkey = add_ns('style:width', nsdict=SNSD)
3064 attribval = '%.4fin' % (self.table_width, )
3065 el1 = self.current_table_style
3066 el2 = el1[0]
3067 el2.attrib[attribkey] = attribval
3068 self.set_to_parent()
3069
3070 def visit_tgroup(self, node) -> None:
3071 self.column_count = ord('A') - 1
3072
3073 def depart_tgroup(self, node) -> None:
3074 pass
3075
3076 def visit_colspec(self, node) -> None:
3077 self.column_count += 1
3078 colspec_name = self.rststyle(
3079 '%s%%d.%%s' % TABLESTYLEPREFIX,
3080 (self.table_count, chr(self.column_count), )
3081 )
3082 colwidth = node.propwidth() / 12.0
3083 el1 = SubElement(self.automatic_styles, 'style:style', attrib={
3084 'style:name': colspec_name,
3085 'style:family': 'table-column',
3086 }, nsdict=SNSD)
3087 SubElement(el1, 'style:table-column-properties',
3088 attrib={'style:column-width': '%.4fin' % colwidth},
3089 nsdict=SNSD)
3090 self.append_child('table:table-column',
3091 attrib={'table:style-name': colspec_name, })
3092 self.table_width += colwidth
3093
3094 def depart_colspec(self, node) -> None:
3095 pass
3096
3097 def visit_thead(self, node) -> None:
3098 el = self.append_child('table:table-header-rows')
3099 self.set_current_element(el)
3100 self.in_thead = True
3101 self.paragraph_style_stack.append('Table_20_Heading')
3102
3103 def depart_thead(self, node) -> None:
3104 self.set_to_parent()
3105 self.in_thead = False
3106 self.paragraph_style_stack.pop()
3107
3108 def visit_row(self, node) -> None:
3109 self.column_count = ord('A') - 1
3110 el = self.append_child('table:table-row')
3111 self.set_current_element(el)
3112
3113 def depart_row(self, node) -> None:
3114 self.set_to_parent()
3115
3116 def visit_entry(self, node) -> None:
3117 self.column_count += 1
3118 cellspec_name = self.rststyle(
3119 '%s%%d.%%c%%d' % TABLESTYLEPREFIX,
3120 (self.table_count, 'A', 1, )
3121 )
3122 attrib = {
3123 'table:style-name': cellspec_name,
3124 'office:value-type': 'string',
3125 }
3126 morecols = node.get('morecols', 0)
3127 if morecols > 0:
3128 attrib['table:number-columns-spanned'] = '%d' % (morecols + 1,)
3129 self.column_count += morecols
3130 morerows = node.get('morerows', 0)
3131 if morerows > 0:
3132 attrib['table:number-rows-spanned'] = '%d' % (morerows + 1,)
3133 el1 = self.append_child('table:table-cell', attrib=attrib)
3134 self.set_current_element(el1)
3135
3136 def depart_entry(self, node) -> None:
3137 self.set_to_parent()
3138
3139 def visit_tbody(self, node) -> None:
3140 pass
3141
3142 def depart_tbody(self, node) -> None:
3143 pass
3144
3145 def visit_target(self, node) -> None:
3146 #
3147 # I don't know how to implement targets in ODF.
3148 # How do we create a target in oowriter? A cross-reference?
3149 if ('refuri' not in node
3150 and 'refid' not in node
3151 and 'refname' not in node):
3152 pass
3153 else:
3154 pass
3155
3156 def depart_target(self, node) -> None:
3157 pass
3158
3159 def visit_title(self, node, move_ids=1, title_type='title') -> None:
3160 if isinstance(node.parent, docutils.nodes.section):
3161 section_level = self.section_level
3162 if section_level > 7:
3163 self.document.reporter.warning(
3164 'Heading/section levels greater than 7 not supported.'
3165 ' Reducing to heading level 7 for heading: "%s"' % (
3166 node.astext(), ), base_node=node)
3167 section_level = 7
3168 el1 = self.append_child(
3169 'text:h', attrib={
3170 'text:outline-level': '%d' % section_level,
3171 # 'text:style-name': 'Heading_20_%d' % section_level,
3172 'text:style-name': self.rststyle(
3173 'heading%d', (section_level, )),
3174 })
3175 self.append_pending_ids(el1)
3176 self.set_current_element(el1)
3177 elif isinstance(node.parent, docutils.nodes.document):
3178 # text = self.settings.title
3179 # else:
3180 # text = node.astext()
3181 el1 = SubElement(self.current_element, 'text:p', attrib={
3182 'text:style-name': self.rststyle(title_type),
3183 })
3184 self.append_pending_ids(el1)
3185 text = node.astext()
3186 self.title = text
3187 self.found_doc_title = True
3188 self.set_current_element(el1)
3189
3190 def depart_title(self, node) -> None:
3191 if (isinstance(node.parent, docutils.nodes.section)
3192 or isinstance(node.parent, docutils.nodes.document)):
3193 self.set_to_parent()
3194
3195 def visit_subtitle(self, node, move_ids=1) -> None:
3196 self.visit_title(node, move_ids, title_type='subtitle')
3197
3198 def depart_subtitle(self, node) -> None:
3199 self.depart_title(node)
3200
3201 def visit_title_reference(self, node):
3202 el = self.append_child('text:span', attrib={
3203 'text:style-name': self.rststyle('quotation')})
3204 el.text = self.encode(node.astext())
3205 raise nodes.SkipChildren
3206
3207 def depart_title_reference(self, node) -> None:
3208 pass
3209
3210 def generate_table_of_content_entry_template(self, el1) -> None:
3211 for idx in range(1, 11):
3212 el2 = SubElement(
3213 el1,
3214 'text:table-of-content-entry-template',
3215 attrib={
3216 'text:outline-level': "%d" % (idx, ),
3217 'text:style-name': self.rststyle('contents-%d' % (idx, )),
3218 })
3219 SubElement(el2, 'text:index-entry-chapter')
3220 SubElement(el2, 'text:index-entry-text')
3221 SubElement(el2, 'text:index-entry-tab-stop', attrib={
3222 'style:leader-char': ".",
3223 'style:type': "right",
3224 })
3225 SubElement(el2, 'text:index-entry-page-number')
3226
3227 def find_title_label(self, node, class_type, label_key):
3228 label = ''
3229 title_node = None
3230 for child in node.children:
3231 if isinstance(child, class_type):
3232 title_node = child
3233 break
3234 if title_node is not None:
3235 label = title_node.astext()
3236 else:
3237 label = self.language.labels[label_key]
3238 return label
3239
3240 def visit_topic(self, node) -> None:
3241 if 'classes' in node.attributes:
3242 if 'contents' in node.attributes['classes']:
3243 label = self.find_title_label(
3244 node, docutils.nodes.title, 'contents')
3245 if self.settings.generate_oowriter_toc:
3246 el1 = self.append_child('text:table-of-content', attrib={
3247 'text:name': 'Table of Contents1',
3248 'text:protected': 'true',
3249 'text:style-name': 'Sect1',
3250 })
3251 el2 = SubElement(
3252 el1,
3253 'text:table-of-content-source',
3254 attrib={
3255 'text:outline-level': '10',
3256 })
3257 el3 = SubElement(el2, 'text:index-title-template', attrib={
3258 'text:style-name': 'Contents_20_Heading',
3259 })
3260 el3.text = label
3261 self.generate_table_of_content_entry_template(el2)
3262 el4 = SubElement(el1, 'text:index-body')
3263 el5 = SubElement(el4, 'text:index-title')
3264 el6 = SubElement(el5, 'text:p', attrib={
3265 'text:style-name': self.rststyle('contents-heading'),
3266 })
3267 el6.text = label
3268 self.save_current_element = self.current_element
3269 self.table_of_content_index_body = el4
3270 self.set_current_element(el4)
3271 else:
3272 el = self.append_p('horizontalline')
3273 el = self.append_p('centeredtextbody')
3274 el1 = SubElement(
3275 el, 'text:span',
3276 attrib={'text:style-name': self.rststyle('strong')})
3277 el1.text = label
3278 self.in_table_of_contents = True
3279 elif 'abstract' in node.attributes['classes']:
3280 el = self.append_p('horizontalline')
3281 el = self.append_p('centeredtextbody')
3282 el1 = SubElement(
3283 el, 'text:span',
3284 attrib={'text:style-name': self.rststyle('strong')})
3285 label = self.find_title_label(
3286 node, docutils.nodes.title,
3287 'abstract')
3288 el1.text = label
3289 elif 'dedication' in node.attributes['classes']:
3290 el = self.append_p('horizontalline')
3291 el = self.append_p('centeredtextbody')
3292 el1 = SubElement(
3293 el, 'text:span',
3294 attrib={'text:style-name': self.rststyle('strong')})
3295 label = self.find_title_label(
3296 node, docutils.nodes.title,
3297 'dedication')
3298 el1.text = label
3299
3300 def depart_topic(self, node) -> None:
3301 if 'classes' in node.attributes:
3302 if 'contents' in node.attributes['classes']:
3303 if self.settings.generate_oowriter_toc:
3304 self.update_toc_page_numbers(
3305 self.table_of_content_index_body)
3306 self.set_current_element(self.save_current_element)
3307 else:
3308 self.append_p('horizontalline')
3309 self.in_table_of_contents = False
3310
3311 def update_toc_page_numbers(self, el) -> None:
3312 collection = []
3313 self.update_toc_collect(el, 0, collection)
3314 self.update_toc_add_numbers(collection)
3315
3316 def update_toc_collect(self, el, level, collection) -> None:
3317 collection.append((level, el))
3318 level += 1
3319 for child_el in el:
3320 if child_el.tag != 'text:index-body':
3321 self.update_toc_collect(child_el, level, collection)
3322
3323 def update_toc_add_numbers(self, collection) -> None:
3324 for level, el1 in collection:
3325 if (el1.tag == 'text:p'
3326 and el1.text != 'Table of Contents'):
3327 el2 = SubElement(el1, 'text:tab')
3328 el2.tail = '9999'
3329
3330 def visit_transition(self, node) -> None:
3331 self.append_p('horizontalline')
3332
3333 def depart_transition(self, node) -> None:
3334 pass
3335
3336 #
3337 # Admonitions
3338 #
3339 def visit_warning(self, node) -> None:
3340 self.generate_admonition(node, 'warning')
3341
3342 def depart_warning(self, node) -> None:
3343 self.paragraph_style_stack.pop()
3344
3345 def visit_attention(self, node) -> None:
3346 self.generate_admonition(node, 'attention')
3347
3348 depart_attention = depart_warning
3349
3350 def visit_caution(self, node) -> None:
3351 self.generate_admonition(node, 'caution')
3352
3353 depart_caution = depart_warning
3354
3355 def visit_danger(self, node) -> None:
3356 self.generate_admonition(node, 'danger')
3357
3358 depart_danger = depart_warning
3359
3360 def visit_error(self, node) -> None:
3361 self.generate_admonition(node, 'error')
3362
3363 depart_error = depart_warning
3364
3365 def visit_hint(self, node) -> None:
3366 self.generate_admonition(node, 'hint')
3367
3368 depart_hint = depart_warning
3369
3370 def visit_important(self, node) -> None:
3371 self.generate_admonition(node, 'important')
3372
3373 depart_important = depart_warning
3374
3375 def visit_note(self, node) -> None:
3376 self.generate_admonition(node, 'note')
3377
3378 depart_note = depart_warning
3379
3380 def visit_tip(self, node) -> None:
3381 self.generate_admonition(node, 'tip')
3382
3383 depart_tip = depart_warning
3384
3385 def visit_admonition(self, node) -> None:
3386 title = None
3387 for child in node.children:
3388 if child.tagname == 'title':
3389 title = child.astext()
3390 if title is None:
3391 classes1 = node.get('classes')
3392 if classes1:
3393 title = classes1[0]
3394 self.generate_admonition(node, 'generic', title)
3395
3396 depart_admonition = depart_warning
3397
3398 def generate_admonition(self, node, label, title=None) -> None:
3399 if hasattr(self.language, 'labels'):
3400 translated_label = self.language.labels.get(label, label)
3401 else:
3402 translated_label = label
3403 el1 = SubElement(self.current_element, 'text:p', attrib={
3404 'text:style-name': self.rststyle(
3405 'admon-%s-hdr', (label, )),
3406 })
3407 if title:
3408 el1.text = title
3409 else:
3410 el1.text = '%s!' % (translated_label.capitalize(), )
3411 s1 = self.rststyle('admon-%s-body', (label, ))
3412 self.paragraph_style_stack.append(s1)
3413
3414 #
3415 # Roles (e.g. subscript, superscript, strong, ...
3416 #
3417 def visit_subscript(self, node) -> None:
3418 el = self.append_child('text:span', attrib={
3419 'text:style-name': 'rststyle-subscript',
3420 })
3421 self.set_current_element(el)
3422
3423 def depart_subscript(self, node) -> None:
3424 self.set_to_parent()
3425
3426 def visit_superscript(self, node) -> None:
3427 el = self.append_child('text:span', attrib={
3428 'text:style-name': 'rststyle-superscript',
3429 })
3430 self.set_current_element(el)
3431
3432 def depart_superscript(self, node) -> None:
3433 self.set_to_parent()
3434
3435 def visit_abbreviation(self, node) -> None:
3436 pass
3437
3438 def depart_abbreviation(self, node) -> None:
3439 pass
3440
3441 def visit_acronym(self, node) -> None:
3442 pass
3443
3444 def depart_acronym(self, node) -> None:
3445 pass
3446
3447 def visit_sidebar(self, node) -> None:
3448 pass
3449
3450 def depart_sidebar(self, node) -> None:
3451 pass
3452
3453
3454 # Use an own reader to modify transformations done.
3455 class Reader(standalone.Reader):
3456
3457 def get_transforms(self):
3458 transforms = super().get_transforms()
3459 if not self.settings.create_links:
3460 transforms.remove(references.DanglingReferences)
3461 return transforms