2 # -*- coding: utf-8; mode: python -*-
3 # pylint: disable=C0330, R0903, R0912
9 Implementation of the ``flat-table`` reST-directive.
11 :copyright: Copyright (C) 2016 Markus Heiser
12 :license: GPL Version 2, June 1991 see linux/COPYING for details.
14 The ``flat-table`` (:py:class:`FlatTable`) is a double-stage list similar to
15 the ``list-table`` with some additional features:
17 * *column-span*: with the role ``cspan`` a cell can be extended through
20 * *row-span*: with the role ``rspan`` a cell can be extended through
23 * *auto span* rightmost cell of a table row over the missing cells on the
24 right side of that table-row. With Option ``:fill-cells:`` this behavior
25 can changed from *auto span* to *auto fill*, which automaticly inserts
26 (empty) cells instead of spanning the last cell.
30 * header-rows: [int] count of header rows
31 * stub-columns: [int] count of stub columns
32 * widths: [[int] [int] ... ] widths of columns
33 * fill-cells: instead of autospann missing cells, insert missing cells
37 * cspan: [int] additionale columns (*morecols*)
38 * rspan: [int] additionale rows (*morerows*)
41 # ==============================================================================
43 # ==============================================================================
47 from docutils
import nodes
48 from docutils
.parsers
.rst
import directives
, roles
49 from docutils
.parsers
.rst
.directives
.tables
import Table
50 from docutils
.utils
import SystemMessagePropagation
52 # ==============================================================================
54 # ==============================================================================
56 # The version numbering follows numbering of the specification
57 # (Documentation/books/kernel-doc-HOWTO).
60 PY3
= sys
.version_info
[0] == 3
61 PY2
= sys
.version_info
[0] == 2
64 # pylint: disable=C0103, W0622
68 # ==============================================================================
70 # ==============================================================================
72 app
.add_directive("flat-table", FlatTable
)
73 roles
.register_local_role('cspan', c_span
)
74 roles
.register_local_role('rspan', r_span
)
76 # ==============================================================================
77 def c_span(name
, rawtext
, text
, lineno
, inliner
, options
=None, content
=None):
78 # ==============================================================================
79 # pylint: disable=W0613
81 options
= options
if options
is not None else {}
82 content
= content
if content
is not None else []
83 nodelist
= [colSpan(span
=int(text
))]
85 return nodelist
, msglist
87 # ==============================================================================
88 def r_span(name
, rawtext
, text
, lineno
, inliner
, options
=None, content
=None):
89 # ==============================================================================
90 # pylint: disable=W0613
92 options
= options
if options
is not None else {}
93 content
= content
if content
is not None else []
94 nodelist
= [rowSpan(span
=int(text
))]
96 return nodelist
, msglist
99 # ==============================================================================
100 class rowSpan(nodes
.General
, nodes
.Element
): pass # pylint: disable=C0103,C0321
101 class colSpan(nodes
.General
, nodes
.Element
): pass # pylint: disable=C0103,C0321
102 # ==============================================================================
104 # ==============================================================================
105 class FlatTable(Table
):
106 # ==============================================================================
108 u
"""FlatTable (``flat-table``) directive"""
111 'name': directives
.unchanged
112 , 'class': directives
.class_option
113 , 'header-rows': directives
.nonnegative_int
114 , 'stub-columns': directives
.nonnegative_int
115 , 'widths': directives
.positive_int_list
116 , 'fill-cells' : directives
.flag
}
121 error
= self
.state_machine
.reporter
.error(
122 'The "%s" directive is empty; content required.' % self
.name
,
123 nodes
.literal_block(self
.block_text
, self
.block_text
),
127 title
, messages
= self
.make_title()
128 node
= nodes
.Element() # anonymous container for parsing
129 self
.state
.nested_parse(self
.content
, self
.content_offset
, node
)
131 tableBuilder
= ListTableBuilder(self
)
132 tableBuilder
.parseFlatTableNode(node
)
133 tableNode
= tableBuilder
.buildTableNode()
134 # SDK.CONSOLE() # print --> tableNode.asdom().toprettyxml()
136 tableNode
.insert(0, title
)
137 return [tableNode
] + messages
140 # ==============================================================================
141 class ListTableBuilder(object):
142 # ==============================================================================
144 u
"""Builds a table from a double-stage list"""
146 def __init__(self
, directive
):
147 self
.directive
= directive
151 def buildTableNode(self
):
153 colwidths
= self
.directive
.get_column_widths(self
.max_cols
)
154 stub_columns
= self
.directive
.options
.get('stub-columns', 0)
155 header_rows
= self
.directive
.options
.get('header-rows', 0)
157 table
= nodes
.table()
158 tgroup
= nodes
.tgroup(cols
=len(colwidths
))
162 for colwidth
in colwidths
:
163 colspec
= nodes
.colspec(colwidth
=colwidth
)
164 # FIXME: It seems, that the stub method only works well in the
165 # absence of rowspan (observed by the html buidler, the docutils-xml
166 # build seems OK). This is not extraordinary, because there exists
167 # no table directive (except *this* flat-table) which allows to
168 # define coexistent of rowspan and stubs (there was no use-case
169 # before flat-table). This should be reviewed (later).
171 colspec
.attributes
['stub'] = 1
174 stub_columns
= self
.directive
.options
.get('stub-columns', 0)
177 thead
= nodes
.thead()
179 for row
in self
.rows
[:header_rows
]:
180 thead
+= self
.buildTableRowNode(row
)
182 tbody
= nodes
.tbody()
185 for row
in self
.rows
[header_rows
:]:
186 tbody
+= self
.buildTableRowNode(row
)
189 def buildTableRowNode(self
, row_data
, classes
=None):
190 classes
= [] if classes
is None else classes
192 for cell
in row_data
:
195 cspan
, rspan
, cellElements
= cell
197 attributes
= {"classes" : classes
}
199 attributes
['morerows'] = rspan
201 attributes
['morecols'] = cspan
202 entry
= nodes
.entry(**attributes
)
203 entry
.extend(cellElements
)
207 def raiseError(self
, msg
):
208 error
= self
.directive
.state_machine
.reporter
.error(
210 , nodes
.literal_block(self
.directive
.block_text
211 , self
.directive
.block_text
)
212 , line
= self
.directive
.lineno
)
213 raise SystemMessagePropagation(error
)
215 def parseFlatTableNode(self
, node
):
216 u
"""parses the node from a :py:class:`FlatTable` directive's body"""
218 if len(node
) != 1 or not isinstance(node
[0], nodes
.bullet_list
):
220 'Error parsing content block for the "%s" directive: '
221 'exactly one bullet list expected.' % self
.directive
.name
)
223 for rowNum
, rowItem
in enumerate(node
[0]):
224 row
= self
.parseRowItem(rowItem
, rowNum
)
225 self
.rows
.append(row
)
226 self
.roundOffTableDefinition()
228 def roundOffTableDefinition(self
):
229 u
"""Round off the table definition.
231 This method rounds off the table definition in :py:member:`rows`.
233 * This method inserts the needed ``None`` values for the missing cells
234 arising from spanning cells over rows and/or columns.
236 * recount the :py:member:`max_cols`
238 * Autospan or fill (option ``fill-cells``) missing cells on the right
239 side of the table-row
243 while y
< len(self
.rows
):
246 while x
< len(self
.rows
[y
]):
247 cell
= self
.rows
[y
][x
]
251 cspan
, rspan
= cell
[:2]
252 # handle colspan in current row
253 for c
in range(cspan
):
255 self
.rows
[y
].insert(x
+c
+1, None)
256 except: # pylint: disable=W0702
257 # the user sets ambiguous rowspans
259 # handle colspan in spanned rows
260 for r
in range(rspan
):
261 for c
in range(cspan
+ 1):
263 self
.rows
[y
+r
+1].insert(x
+c
, None)
264 except: # pylint: disable=W0702
265 # the user sets ambiguous rowspans
270 # Insert the missing cells on the right side. For this, first
271 # re-calculate the max columns.
273 for row
in self
.rows
:
274 if self
.max_cols
< len(row
):
275 self
.max_cols
= len(row
)
277 # fill with empty cells or cellspan?
280 if 'fill-cells' in self
.directive
.options
:
283 for row
in self
.rows
:
284 x
= self
.max_cols
- len(row
)
285 if x
and not fill_cells
:
287 row
.append( ( x
- 1, 0, []) )
289 cspan
, rspan
, content
= row
[-1]
290 row
[-1] = (cspan
+ x
, rspan
, content
)
291 elif x
and fill_cells
:
293 row
.append( (0, 0, nodes
.comment()) )
298 for row
in self
.rows
:
302 retVal
+= ('%r' % col
)
305 content
= col
[2][0].astext()
306 if len (content
) > 30:
307 content
= content
[:30] + "..."
308 retVal
+= ('(cspan=%s, rspan=%s, %r)'
309 % (col
[0], col
[1], content
))
316 def parseRowItem(self
, rowItem
, rowNum
):
323 for child
in rowItem
:
324 if (isinstance(child
, nodes
.comment
)
325 or isinstance(child
, nodes
.system_message
)):
327 elif isinstance(child
, nodes
.target
):
329 elif isinstance(child
, nodes
.bullet_list
):
336 if childNo
!= 1 or error
:
338 'Error parsing content block for the "%s" directive: '
339 'two-level bullet list expected, but row %s does not '
340 'contain a second-level bullet list.'
341 % (self
.directive
.name
, rowNum
+ 1))
343 for cellItem
in cell
:
344 cspan
, rspan
, cellElements
= self
.parseCellItem(cellItem
)
345 if target
is not None:
346 cellElements
.insert(0, target
)
347 row
.append( (cspan
, rspan
, cellElements
) )
350 def parseCellItem(self
, cellItem
):
351 # search and remove cspan, rspan colspec from the first element in
352 # this listItem (field).
354 if not len(cellItem
):
355 return cspan
, rspan
, []
356 for elem
in cellItem
[0]:
357 if isinstance(elem
, colSpan
):
358 cspan
= elem
.get("span")
359 elem
.parent
.remove(elem
)
361 if isinstance(elem
, rowSpan
):
362 rspan
= elem
.get("span")
363 elem
.parent
.remove(elem
)
365 return cspan
, rspan
, cellItem
[:]