rstFlatTable.py 13 KB

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