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
)
77 version
= __version__
,
78 parallel_read_safe
= True,
79 parallel_write_safe
= True
82 # ==============================================================================
83 def c_span(name
, rawtext
, text
, lineno
, inliner
, options
=None, content
=None):
84 # ==============================================================================
85 # pylint: disable=W0613
87 options
= options
if options
is not None else {}
88 content
= content
if content
is not None else []
89 nodelist
= [colSpan(span
=int(text
))]
91 return nodelist
, msglist
93 # ==============================================================================
94 def r_span(name
, rawtext
, text
, lineno
, inliner
, options
=None, content
=None):
95 # ==============================================================================
96 # pylint: disable=W0613
98 options
= options
if options
is not None else {}
99 content
= content
if content
is not None else []
100 nodelist
= [rowSpan(span
=int(text
))]
102 return nodelist
, msglist
105 # ==============================================================================
106 class rowSpan(nodes
.General
, nodes
.Element
): pass # pylint: disable=C0103,C0321
107 class colSpan(nodes
.General
, nodes
.Element
): pass # pylint: disable=C0103,C0321
108 # ==============================================================================
110 # ==============================================================================
111 class FlatTable(Table
):
112 # ==============================================================================
114 u
"""FlatTable (``flat-table``) directive"""
117 'name': directives
.unchanged
118 , 'class': directives
.class_option
119 , 'header-rows': directives
.nonnegative_int
120 , 'stub-columns': directives
.nonnegative_int
121 , 'widths': directives
.positive_int_list
122 , 'fill-cells' : directives
.flag
}
127 error
= self
.state_machine
.reporter
.error(
128 'The "%s" directive is empty; content required.' % self
.name
,
129 nodes
.literal_block(self
.block_text
, self
.block_text
),
133 title
, messages
= self
.make_title()
134 node
= nodes
.Element() # anonymous container for parsing
135 self
.state
.nested_parse(self
.content
, self
.content_offset
, node
)
137 tableBuilder
= ListTableBuilder(self
)
138 tableBuilder
.parseFlatTableNode(node
)
139 tableNode
= tableBuilder
.buildTableNode()
140 # SDK.CONSOLE() # print --> tableNode.asdom().toprettyxml()
142 tableNode
.insert(0, title
)
143 return [tableNode
] + messages
146 # ==============================================================================
147 class ListTableBuilder(object):
148 # ==============================================================================
150 u
"""Builds a table from a double-stage list"""
152 def __init__(self
, directive
):
153 self
.directive
= directive
157 def buildTableNode(self
):
159 colwidths
= self
.directive
.get_column_widths(self
.max_cols
)
160 if isinstance(colwidths
, tuple):
161 # Since docutils 0.13, get_column_widths returns a (widths,
162 # colwidths) tuple, where widths is a string (i.e. 'auto').
163 # See https://sourceforge.net/p/docutils/patches/120/.
164 colwidths
= colwidths
[1]
165 stub_columns
= self
.directive
.options
.get('stub-columns', 0)
166 header_rows
= self
.directive
.options
.get('header-rows', 0)
168 table
= nodes
.table()
169 tgroup
= nodes
.tgroup(cols
=len(colwidths
))
173 for colwidth
in colwidths
:
174 colspec
= nodes
.colspec(colwidth
=colwidth
)
175 # FIXME: It seems, that the stub method only works well in the
176 # absence of rowspan (observed by the html buidler, the docutils-xml
177 # build seems OK). This is not extraordinary, because there exists
178 # no table directive (except *this* flat-table) which allows to
179 # define coexistent of rowspan and stubs (there was no use-case
180 # before flat-table). This should be reviewed (later).
182 colspec
.attributes
['stub'] = 1
185 stub_columns
= self
.directive
.options
.get('stub-columns', 0)
188 thead
= nodes
.thead()
190 for row
in self
.rows
[:header_rows
]:
191 thead
+= self
.buildTableRowNode(row
)
193 tbody
= nodes
.tbody()
196 for row
in self
.rows
[header_rows
:]:
197 tbody
+= self
.buildTableRowNode(row
)
200 def buildTableRowNode(self
, row_data
, classes
=None):
201 classes
= [] if classes
is None else classes
203 for cell
in row_data
:
206 cspan
, rspan
, cellElements
= cell
208 attributes
= {"classes" : classes
}
210 attributes
['morerows'] = rspan
212 attributes
['morecols'] = cspan
213 entry
= nodes
.entry(**attributes
)
214 entry
.extend(cellElements
)
218 def raiseError(self
, msg
):
219 error
= self
.directive
.state_machine
.reporter
.error(
221 , nodes
.literal_block(self
.directive
.block_text
222 , self
.directive
.block_text
)
223 , line
= self
.directive
.lineno
)
224 raise SystemMessagePropagation(error
)
226 def parseFlatTableNode(self
, node
):
227 u
"""parses the node from a :py:class:`FlatTable` directive's body"""
229 if len(node
) != 1 or not isinstance(node
[0], nodes
.bullet_list
):
231 'Error parsing content block for the "%s" directive: '
232 'exactly one bullet list expected.' % self
.directive
.name
)
234 for rowNum
, rowItem
in enumerate(node
[0]):
235 row
= self
.parseRowItem(rowItem
, rowNum
)
236 self
.rows
.append(row
)
237 self
.roundOffTableDefinition()
239 def roundOffTableDefinition(self
):
240 u
"""Round off the table definition.
242 This method rounds off the table definition in :py:member:`rows`.
244 * This method inserts the needed ``None`` values for the missing cells
245 arising from spanning cells over rows and/or columns.
247 * recount the :py:member:`max_cols`
249 * Autospan or fill (option ``fill-cells``) missing cells on the right
250 side of the table-row
254 while y
< len(self
.rows
):
257 while x
< len(self
.rows
[y
]):
258 cell
= self
.rows
[y
][x
]
262 cspan
, rspan
= cell
[:2]
263 # handle colspan in current row
264 for c
in range(cspan
):
266 self
.rows
[y
].insert(x
+c
+1, None)
267 except: # pylint: disable=W0702
268 # the user sets ambiguous rowspans
270 # handle colspan in spanned rows
271 for r
in range(rspan
):
272 for c
in range(cspan
+ 1):
274 self
.rows
[y
+r
+1].insert(x
+c
, None)
275 except: # pylint: disable=W0702
276 # the user sets ambiguous rowspans
281 # Insert the missing cells on the right side. For this, first
282 # re-calculate the max columns.
284 for row
in self
.rows
:
285 if self
.max_cols
< len(row
):
286 self
.max_cols
= len(row
)
288 # fill with empty cells or cellspan?
291 if 'fill-cells' in self
.directive
.options
:
294 for row
in self
.rows
:
295 x
= self
.max_cols
- len(row
)
296 if x
and not fill_cells
:
298 row
.append( ( x
- 1, 0, []) )
300 cspan
, rspan
, content
= row
[-1]
301 row
[-1] = (cspan
+ x
, rspan
, content
)
302 elif x
and fill_cells
:
304 row
.append( (0, 0, nodes
.comment()) )
309 for row
in self
.rows
:
313 retVal
+= ('%r' % col
)
316 content
= col
[2][0].astext()
317 if len (content
) > 30:
318 content
= content
[:30] + "..."
319 retVal
+= ('(cspan=%s, rspan=%s, %r)'
320 % (col
[0], col
[1], content
))
327 def parseRowItem(self
, rowItem
, rowNum
):
334 for child
in rowItem
:
335 if (isinstance(child
, nodes
.comment
)
336 or isinstance(child
, nodes
.system_message
)):
338 elif isinstance(child
, nodes
.target
):
340 elif isinstance(child
, nodes
.bullet_list
):
347 if childNo
!= 1 or error
:
349 'Error parsing content block for the "%s" directive: '
350 'two-level bullet list expected, but row %s does not '
351 'contain a second-level bullet list.'
352 % (self
.directive
.name
, rowNum
+ 1))
354 for cellItem
in cell
:
355 cspan
, rspan
, cellElements
= self
.parseCellItem(cellItem
)
356 if target
is not None:
357 cellElements
.insert(0, target
)
358 row
.append( (cspan
, rspan
, cellElements
) )
361 def parseCellItem(self
, cellItem
):
362 # search and remove cspan, rspan colspec from the first element in
363 # this listItem (field).
365 if not len(cellItem
):
366 return cspan
, rspan
, []
367 for elem
in cellItem
[0]:
368 if isinstance(elem
, colSpan
):
369 cspan
= elem
.get("span")
370 elem
.parent
.remove(elem
)
372 if isinstance(elem
, rowSpan
):
373 rspan
= elem
.get("span")
374 elem
.parent
.remove(elem
)
376 return cspan
, rspan
, cellItem
[:]