rstFlatTable.py 13 KB

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