rstFlatTable.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8; mode: python -*-
  3. # SPDX-License-Identifier: GPL-2.0
  4. # pylint: disable=C0330, R0903, R0912
  5. """
  6. flat-table
  7. ~~~~~~~~~~
  8. Implementation of the ``flat-table`` reST-directive.
  9. :copyright: Copyright (C) 2016 Markus Heiser
  10. :license: GPL Version 2, June 1991 see linux/COPYING for details.
  11. The ``flat-table`` (:py:class:`FlatTable`) is a double-stage list similar to
  12. the ``list-table`` with some additional features:
  13. * *column-span*: with the role ``cspan`` a cell can be extended through
  14. additional columns
  15. * *row-span*: with the role ``rspan`` a cell can be extended through
  16. additional rows
  17. * *auto span* rightmost cell of a table row over the missing cells on the
  18. right side of that table-row. With Option ``:fill-cells:`` this behavior
  19. can be changed from *auto span* to *auto fill*, which automatically inserts
  20. (empty) cells instead of spanning the last cell.
  21. Options:
  22. * header-rows: [int] count of header rows
  23. * stub-columns: [int] count of stub columns
  24. * widths: [[int] [int] ... ] widths of columns
  25. * fill-cells: instead of autospann missing cells, insert missing cells
  26. roles:
  27. * cspan: [int] additionale columns (*morecols*)
  28. * rspan: [int] additionale rows (*morerows*)
  29. """
  30. # ==============================================================================
  31. # imports
  32. # ==============================================================================
  33. from docutils import nodes
  34. from docutils.parsers.rst import directives, roles
  35. from docutils.parsers.rst.directives.tables import Table
  36. from docutils.utils import SystemMessagePropagation
  37. # ==============================================================================
  38. # common globals
  39. # ==============================================================================
  40. __version__ = '1.0'
  41. # ==============================================================================
  42. def setup(app):
  43. # ==============================================================================
  44. app.add_directive("flat-table", FlatTable)
  45. roles.register_local_role('cspan', c_span)
  46. roles.register_local_role('rspan', r_span)
  47. return dict(
  48. version = __version__,
  49. parallel_read_safe = True,
  50. parallel_write_safe = True
  51. )
  52. # ==============================================================================
  53. def c_span(name, rawtext, text, lineno, inliner, options=None, content=None):
  54. # ==============================================================================
  55. # pylint: disable=W0613
  56. options = options if options is not None else {}
  57. content = content if content is not None else []
  58. nodelist = [colSpan(span=int(text))]
  59. msglist = []
  60. return nodelist, msglist
  61. # ==============================================================================
  62. def r_span(name, rawtext, text, lineno, inliner, options=None, content=None):
  63. # ==============================================================================
  64. # pylint: disable=W0613
  65. options = options if options is not None else {}
  66. content = content if content is not None else []
  67. nodelist = [rowSpan(span=int(text))]
  68. msglist = []
  69. return nodelist, msglist
  70. # ==============================================================================
  71. class rowSpan(nodes.General, nodes.Element): pass # pylint: disable=C0103,C0321
  72. class colSpan(nodes.General, nodes.Element): pass # pylint: disable=C0103,C0321
  73. # ==============================================================================
  74. # ==============================================================================
  75. class FlatTable(Table):
  76. # ==============================================================================
  77. """FlatTable (``flat-table``) directive"""
  78. option_spec = {
  79. 'name': directives.unchanged
  80. , 'class': directives.class_option
  81. , 'header-rows': directives.nonnegative_int
  82. , 'stub-columns': directives.nonnegative_int
  83. , 'widths': directives.positive_int_list
  84. , 'fill-cells' : directives.flag }
  85. def run(self):
  86. if not self.content:
  87. error = self.state_machine.reporter.error(
  88. 'The "%s" directive is empty; content required.' % self.name,
  89. nodes.literal_block(self.block_text, self.block_text),
  90. line=self.lineno)
  91. return [error]
  92. title, messages = self.make_title()
  93. node = nodes.Element() # anonymous container for parsing
  94. self.state.nested_parse(self.content, self.content_offset, node)
  95. tableBuilder = ListTableBuilder(self)
  96. tableBuilder.parseFlatTableNode(node)
  97. tableNode = tableBuilder.buildTableNode()
  98. # SDK.CONSOLE() # print --> tableNode.asdom().toprettyxml()
  99. if title:
  100. tableNode.insert(0, title)
  101. return [tableNode] + messages
  102. # ==============================================================================
  103. class ListTableBuilder(object):
  104. # ==============================================================================
  105. """Builds a table from a double-stage list"""
  106. def __init__(self, directive):
  107. self.directive = directive
  108. self.rows = []
  109. self.max_cols = 0
  110. def buildTableNode(self):
  111. colwidths = self.directive.get_column_widths(self.max_cols)
  112. if isinstance(colwidths, tuple):
  113. # Since docutils 0.13, get_column_widths returns a (widths,
  114. # colwidths) tuple, where widths is a string (i.e. 'auto').
  115. # See https://sourceforge.net/p/docutils/patches/120/.
  116. colwidths = colwidths[1]
  117. stub_columns = self.directive.options.get('stub-columns', 0)
  118. header_rows = self.directive.options.get('header-rows', 0)
  119. table = nodes.table()
  120. tgroup = nodes.tgroup(cols=len(colwidths))
  121. table += tgroup
  122. for colwidth in colwidths:
  123. colspec = nodes.colspec(colwidth=colwidth)
  124. # FIXME: It seems, that the stub method only works well in the
  125. # absence of rowspan (observed by the html builder, the docutils-xml
  126. # build seems OK). This is not extraordinary, because there exists
  127. # no table directive (except *this* flat-table) which allows to
  128. # define coexistent of rowspan and stubs (there was no use-case
  129. # before flat-table). This should be reviewed (later).
  130. if stub_columns:
  131. colspec.attributes['stub'] = 1
  132. stub_columns -= 1
  133. tgroup += colspec
  134. stub_columns = self.directive.options.get('stub-columns', 0)
  135. if header_rows:
  136. thead = nodes.thead()
  137. tgroup += thead
  138. for row in self.rows[:header_rows]:
  139. thead += self.buildTableRowNode(row)
  140. tbody = nodes.tbody()
  141. tgroup += tbody
  142. for row in self.rows[header_rows:]:
  143. tbody += self.buildTableRowNode(row)
  144. return table
  145. def buildTableRowNode(self, row_data, classes=None):
  146. classes = [] if classes is None else classes
  147. row = nodes.row()
  148. for cell in row_data:
  149. if cell is None:
  150. continue
  151. cspan, rspan, cellElements = cell
  152. attributes = {"classes" : classes}
  153. if rspan:
  154. attributes['morerows'] = rspan
  155. if cspan:
  156. attributes['morecols'] = cspan
  157. entry = nodes.entry(**attributes)
  158. entry.extend(cellElements)
  159. row += entry
  160. return row
  161. def raiseError(self, msg):
  162. error = self.directive.state_machine.reporter.error(
  163. msg
  164. , nodes.literal_block(self.directive.block_text
  165. , self.directive.block_text)
  166. , line = self.directive.lineno )
  167. raise SystemMessagePropagation(error)
  168. def parseFlatTableNode(self, node):
  169. """parses the node from a :py:class:`FlatTable` directive's body"""
  170. if len(node) != 1 or not isinstance(node[0], nodes.bullet_list):
  171. self.raiseError(
  172. 'Error parsing content block for the "%s" directive: '
  173. 'exactly one bullet list expected.' % self.directive.name )
  174. for rowNum, rowItem in enumerate(node[0]):
  175. row = self.parseRowItem(rowItem, rowNum)
  176. self.rows.append(row)
  177. self.roundOffTableDefinition()
  178. def roundOffTableDefinition(self):
  179. """Round off the table definition.
  180. This method rounds off the table definition in :py:member:`rows`.
  181. * This method inserts the needed ``None`` values for the missing cells
  182. arising from spanning cells over rows and/or columns.
  183. * recount the :py:member:`max_cols`
  184. * Autospan or fill (option ``fill-cells``) missing cells on the right
  185. side of the table-row
  186. """
  187. y = 0
  188. while y < len(self.rows):
  189. x = 0
  190. while x < len(self.rows[y]):
  191. cell = self.rows[y][x]
  192. if cell is None:
  193. x += 1
  194. continue
  195. cspan, rspan = cell[:2]
  196. # handle colspan in current row
  197. for c in range(cspan):
  198. try:
  199. self.rows[y].insert(x+c+1, None)
  200. except: # pylint: disable=W0702
  201. # the user sets ambiguous rowspans
  202. pass # SDK.CONSOLE()
  203. # handle colspan in spanned rows
  204. for r in range(rspan):
  205. for c in range(cspan + 1):
  206. try:
  207. self.rows[y+r+1].insert(x+c, None)
  208. except: # pylint: disable=W0702
  209. # the user sets ambiguous rowspans
  210. pass # SDK.CONSOLE()
  211. x += 1
  212. y += 1
  213. # Insert the missing cells on the right side. For this, first
  214. # re-calculate the max columns.
  215. for row in self.rows:
  216. if self.max_cols < len(row):
  217. self.max_cols = len(row)
  218. # fill with empty cells or cellspan?
  219. fill_cells = False
  220. if 'fill-cells' in self.directive.options:
  221. fill_cells = True
  222. for row in self.rows:
  223. x = self.max_cols - len(row)
  224. if x and not fill_cells:
  225. if row[-1] is None:
  226. row.append( ( x - 1, 0, []) )
  227. else:
  228. cspan, rspan, content = row[-1]
  229. row[-1] = (cspan + x, rspan, content)
  230. elif x and fill_cells:
  231. for i in range(x):
  232. row.append( (0, 0, nodes.comment()) )
  233. def pprint(self):
  234. # for debugging
  235. retVal = "[ "
  236. for row in self.rows:
  237. retVal += "[ "
  238. for col in row:
  239. if col is None:
  240. retVal += ('%r' % col)
  241. retVal += "\n , "
  242. else:
  243. content = col[2][0].astext()
  244. if len (content) > 30:
  245. content = content[:30] + "..."
  246. retVal += ('(cspan=%s, rspan=%s, %r)'
  247. % (col[0], col[1], content))
  248. retVal += "]\n , "
  249. retVal = retVal[:-2]
  250. retVal += "]\n , "
  251. retVal = retVal[:-2]
  252. return retVal + "]"
  253. def parseRowItem(self, rowItem, rowNum):
  254. row = []
  255. childNo = 0
  256. error = False
  257. cell = None
  258. target = None
  259. for child in rowItem:
  260. if (isinstance(child , nodes.comment)
  261. or isinstance(child, nodes.system_message)):
  262. pass
  263. elif isinstance(child , nodes.target):
  264. target = child
  265. elif isinstance(child, nodes.bullet_list):
  266. childNo += 1
  267. cell = child
  268. else:
  269. error = True
  270. break
  271. if childNo != 1 or error:
  272. self.raiseError(
  273. 'Error parsing content block for the "%s" directive: '
  274. 'two-level bullet list expected, but row %s does not '
  275. 'contain a second-level bullet list.'
  276. % (self.directive.name, rowNum + 1))
  277. for cellItem in cell:
  278. cspan, rspan, cellElements = self.parseCellItem(cellItem)
  279. if target is not None:
  280. cellElements.insert(0, target)
  281. row.append( (cspan, rspan, cellElements) )
  282. return row
  283. def parseCellItem(self, cellItem):
  284. # search and remove cspan, rspan colspec from the first element in
  285. # this listItem (field).
  286. cspan = rspan = 0
  287. if not len(cellItem):
  288. return cspan, rspan, []
  289. for elem in cellItem[0]:
  290. if isinstance(elem, colSpan):
  291. cspan = elem.get("span")
  292. elem.parent.remove(elem)
  293. continue
  294. if isinstance(elem, rowSpan):
  295. rspan = elem.get("span")
  296. elem.parent.remove(elem)
  297. continue
  298. return cspan, rspan, cellItem[:]