PageRenderTime 184ms CodeModel.GetById 56ms RepoModel.GetById 16ms app.codeStats 0ms

/documentor/libraries/docutils-0.9.1-py3.2/docutils/writers/odf_odt/__init__.py

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