rstFlatTable.py 13 KB

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