Debian Codegraph @

docutils/parsers/rst/directives/tables.py

raw symbols SCIP
1 # $Id: tables.py 10282 2026-01-07 07:51:48Z milde $
2 # Authors: David Goodger <[email protected]>; David Priest
3 # Copyright: This module has been placed in the public domain.
4
5 """
6 Directives for table elements.
7 """
8
9 from __future__ import annotations
10
11 __docformat__ = 'reStructuredText'
12
13 import csv
14 from urllib.request import urlopen
15 from urllib.error import URLError
16 import warnings
17
18 from docutils import nodes, statemachine
19 from docutils.io import FileInput, StringInput
20 from docutils.parsers.rst import Directive
21 from docutils.parsers.rst import directives
22 from docutils.parsers.rst.directives.misc import adapt_path
23 from docutils.utils import SystemMessagePropagation
24
25
26 def align(argument):
27 return directives.choice(argument, ('left', 'center', 'right'))
28
29
30 class Table(Directive):
31
32 """
33 Generic table base class.
34 """
35
36 optional_arguments = 1
37 final_argument_whitespace = True
38 option_spec = {'class': directives.class_option,
39 'name': directives.unchanged,
40 'align': align,
41 'width': directives.length_or_percentage_or_unitless,
42 'widths': directives.value_or(('auto', 'grid'),
43 directives.positive_int_list)}
44 has_content = True
45
46 def make_title(self):
47 if self.arguments:
48 title_text = self.arguments[0]
49 text_nodes, messages = self.state.inline_text(title_text,
50 self.lineno)
51 title = nodes.title(title_text, '', *text_nodes)
52 (title.source,
53 title.line) = self.state_machine.get_source_and_line(self.lineno)
54 else:
55 title = None
56 messages = []
57 return title, messages
58
59 def check_table_dimensions(self, rows, header_rows, stub_columns):
60 if len(rows) < header_rows:
61 error = self.reporter.error('%s header row(s) specified but '
62 'only %s row(s) of data supplied ("%s" directive).'
63 % (header_rows, len(rows), self.name),
64 nodes.literal_block(self.block_text, self.block_text),
65 line=self.lineno)
66 raise SystemMessagePropagation(error)
67 if len(rows) == header_rows > 0:
68 error = self.reporter.error(
69 f'Insufficient data supplied ({len(rows)} row(s)); '
70 'no data remaining for table body, '
71 f'required by "{self.name}" directive.',
72 nodes.literal_block(self.block_text, self.block_text),
73 line=self.lineno)
74 raise SystemMessagePropagation(error)
75 for row in rows:
76 if len(row) < stub_columns:
77 error = self.reporter.error(
78 f'{stub_columns} stub column(s) specified '
79 f'but only {len(row)} columns(s) of data supplied '
80 f'("{self.name}" directive).',
81 nodes.literal_block(self.block_text, self.block_text),
82 line=self.lineno)
83 raise SystemMessagePropagation(error)
84 if len(row) == stub_columns > 0:
85 error = self.reporter.error(
86 'Insufficient data supplied (%s columns(s)); '
87 'no data remaining for table body, required '
88 'by "%s" directive.' % (len(row), self.name),
89 nodes.literal_block(self.block_text, self.block_text),
90 line=self.lineno)
91 raise SystemMessagePropagation(error)
92
93 def set_table_width(self, table_node) -> None:
94 if 'width' in self.options:
95 table_node['width'] = self.options.get('width')
96
97 @property
98 def widths(self):
99 return self.options.get('widths', '')
100
101 def get_column_widths(self, n_cols):
102 if isinstance(self.widths, list):
103 if len(self.widths) != n_cols:
104 # TODO: use last value for missing columns?
105 error = self.reporter.error('"%s" widths do not match the '
106 'number of columns in table (%s).' % (self.name, n_cols),
107 nodes.literal_block(self.block_text, self.block_text),
108 line=self.lineno)
109 raise SystemMessagePropagation(error)
110 col_widths = self.widths
111 elif n_cols:
112 col_widths = [100 // n_cols] * n_cols
113 else:
114 error = self.reporter.error('No table data detected in CSV file.',
115 nodes.literal_block(self.block_text, self.block_text),
116 line=self.lineno)
117 raise SystemMessagePropagation(error)
118 return col_widths
119
120 def extend_short_rows_with_empty_cells(self, columns, parts) -> None:
121 for part in parts:
122 for row in part:
123 if len(row) < columns:
124 row.extend([(0, 0, 0, [])] * (columns - len(row)))
125
126
127 class RSTTable(Table):
128 """
129 Class for the `"table" directive`__ for formal tables using rST syntax.
130
131 __ https://docutils.sourceforge.io/docs/ref/rst/directives.html
132 """
133
134 def run(self):
135 if not self.content:
136 warning = self.reporter.warning('Content block expected '
137 'for the "%s" directive; none found.' % self.name,
138 nodes.literal_block(self.block_text, self.block_text),
139 line=self.lineno)
140 return [warning]
141 title, messages = self.make_title()
142 node = nodes.Element() # anonymous container for parsing
143 self.state.nested_parse(self.content, self.content_offset, node)
144 if len(node) != 1 or not isinstance(node[0], nodes.table):
145 error = self.reporter.error('Error parsing content block for the '
146 '"%s" directive: exactly one table expected.' % self.name,
147 nodes.literal_block(self.block_text, self.block_text),
148 line=self.lineno)
149 return [error]
150 table_node = node[0]
151 table_node['classes'] += self.options.get('class', [])
152 self.set_table_width(table_node)
153 # update line-nr to point to the start of the directive
154 table_node.line = self.state_machine.get_source_and_line(
155 self.lineno)[1]
156 if 'align' in self.options:
157 table_node['align'] = self.options.get('align')
158 if isinstance(self.widths, list):
159 tgroup = table_node[0]
160 try:
161 col_widths = self.get_column_widths(tgroup["cols"])
162 except SystemMessagePropagation as detail:
163 return [detail.args[0]]
164 colspecs = [child for child in tgroup.children
165 if child.tagname == 'colspec']
166 for colspec, col_width in zip(colspecs, col_widths):
167 colspec['colwidth'] = col_width
168 if self.widths == 'auto':
169 table_node['classes'] += ['colwidths-auto']
170 elif self.widths: # "grid" or list of integers
171 table_node['classes'] += ['colwidths-given']
172 self.add_name(table_node)
173 if title:
174 table_node.insert(0, title)
175 return [table_node] + messages
176
177
178 class CSVTable(Table):
179
180 option_spec = {'header-rows': directives.nonnegative_int,
181 'stub-columns': directives.nonnegative_int,
182 'header': directives.unchanged,
183 'width': directives.length_or_percentage_or_unitless,
184 'widths': directives.value_or(('auto', ),
185 directives.positive_int_list),
186 'file': directives.path,
187 'url': directives.uri,
188 'encoding': directives.encoding,
189 'class': directives.class_option,
190 'name': directives.unchanged,
191 'align': align,
192 # field delimiter char
193 'delim': directives.single_char_or_whitespace_or_unicode,
194 # treat whitespace after delimiter as significant
195 'keepspace': directives.flag,
196 # text field quote/unquote char:
197 'quote': directives.single_char_or_unicode,
198 # char used to escape delim & quote as-needed:
199 'escape': directives.single_char_or_unicode}
200
201 class DocutilsDialect(csv.Dialect):
202
203 """CSV dialect for `csv_table` directive."""
204
205 delimiter = ','
206 quotechar = '"'
207 doublequote = True
208 skipinitialspace = True
209 strict = True
210 lineterminator = '\n'
211 quoting = csv.QUOTE_MINIMAL
212
213 def __init__(self, options) -> None:
214 if 'delim' in options:
215 self.delimiter = options['delim']
216 if 'keepspace' in options:
217 self.skipinitialspace = False
218 if 'quote' in options:
219 self.quotechar = options['quote']
220 if 'escape' in options:
221 self.doublequote = False
222 self.escapechar = options['escape']
223 super().__init__()
224
225 class HeaderDialect(csv.Dialect):
226 """
227 CSV dialect used for the "header" option data.
228
229 Deprecated. Will be removed in Docutils 1.0.
230 """
231 # The separate HeaderDialect was introduced in revision 2294
232 # (2004-06-17) in the sandbox before the "csv-table" directive moved
233 # to the trunk in r2309. Discussion in docutils-devel around this time
234 # did not mention a rationale (part of the discussion was in private
235 # mail).
236 # This is in conflict with the documentation, which always said:
237 # "Must use the same CSV format as the main CSV data."
238 # and did not change in this aspect.
239 #
240 # Maybe it was intended to have similar escape rules for rST and CSV,
241 # however with the current implementation this means we need
242 # `\\` for rST markup and ``\\\\`` for a literal backslash
243 # in the "option" header but ``\`` and ``\\`` in the header-lines and
244 # table cells of the main CSV data.
245 delimiter = ','
246 quotechar = '"'
247 escapechar = '\\'
248 doublequote = False
249 skipinitialspace = True
250 strict = True
251 lineterminator = '\n'
252 quoting = csv.QUOTE_MINIMAL
253
254 def __init__(self) -> None:
255 warnings.warn('CSVTable.HeaderDialect will be removed '
256 'in Docutils 1.0',
257 DeprecationWarning, stacklevel=2)
258 super().__init__()
259
260 def process_header_option(self):
261 source = self.state_machine.get_source(self.lineno - 1)
262 table_head = []
263 max_header_cols = 0
264 if 'header' in self.options: # separate table header in option
265 rows, max_header_cols = self.parse_csv_data_into_rows(
266 self.options['header'].split('\n'),
267 self.DocutilsDialect(self.options),
268 source)
269 table_head.extend(rows)
270 return table_head, max_header_cols
271
272 def run(self):
273 try:
274 if (not self.state.document.settings.file_insertion_enabled
275 and ('file' in self.options
276 or 'url' in self.options)):
277 warning = self.reporter.warning('File and URL access '
278 'deactivated; ignoring "%s" directive.' % self.name,
279 nodes.literal_block(self.block_text, self.block_text),
280 line=self.lineno)
281 return [warning]
282 title, messages = self.make_title()
283 csv_data, source = self.get_csv_data()
284 table_head, max_header_cols = self.process_header_option()
285 rows, max_cols = self.parse_csv_data_into_rows(
286 csv_data, self.DocutilsDialect(self.options), source)
287 max_cols = max(max_cols, max_header_cols)
288 header_rows = self.options.get('header-rows', 0)
289 stub_columns = self.options.get('stub-columns', 0)
290 self.check_table_dimensions(rows, header_rows, stub_columns)
291 table_head.extend(rows[:header_rows])
292 table_body = rows[header_rows:]
293 col_widths = self.get_column_widths(max_cols)
294 self.extend_short_rows_with_empty_cells(max_cols,
295 (table_head, table_body))
296 except SystemMessagePropagation as detail:
297 return [detail.args[0]]
298 except csv.Error as detail:
299 message = str(detail)
300 error = self.reporter.error('Error with CSV data'
301 ' in "%s" directive:\n%s' % (self.name, message),
302 nodes.literal_block(self.block_text, self.block_text),
303 line=self.lineno)
304 return [error]
305 table = (col_widths, table_head, table_body)
306 table_node = self.state.build_table(table, self.content_offset,
307 stub_columns, widths=self.widths)
308 table_node['classes'] += self.options.get('class', [])
309 if 'align' in self.options:
310 table_node['align'] = self.options.get('align')
311 self.set_table_width(table_node)
312 self.add_name(table_node)
313 if title:
314 table_node.insert(0, title)
315 (table_node.source,
316 table_node.line) = self.state_machine.get_source_and_line(self.lineno)
317 return [table_node] + messages
318
319 def get_csv_data(self):
320 """
321 Get CSV data from the directive content, from an external
322 file, or from a URL reference.
323 """
324 settings = self.state.document.settings
325 encoding = self.options.get('encoding', settings.input_encoding)
326 error_handler = settings.input_encoding_error_handler
327 if self.content:
328 # CSV data is from directive content.
329 if 'file' in self.options or 'url' in self.options:
330 error = self.reporter.error('"%s" directive may not both '
331 'specify an external file and have content.' % self.name,
332 nodes.literal_block(self.block_text, self.block_text),
333 line=self.lineno)
334 raise SystemMessagePropagation(error)
335 source = self.content.source(0)
336 csv_data = self.content
337 elif 'file' in self.options:
338 # CSV data is from an external file.
339 if 'url' in self.options:
340 error = self.reporter.error('The "file" and "url" options '
341 'may not be simultaneously specified '
342 'for the "%s" directive.' % self.name,
343 nodes.literal_block(self.block_text, self.block_text),
344 line=self.lineno)
345 raise SystemMessagePropagation(error)
346 source = adapt_path(self.options['file'],
347 self.state.document.current_source,
348 settings.root_prefix)
349 try:
350 csv_file = FileInput(source_path=source,
351 encoding=encoding,
352 error_handler=error_handler)
353 csv_data = csv_file.read().splitlines()
354 except OSError as error:
355 severe = self.reporter.severe(
356 'Problems with "%s" directive path:\n%s.'
357 % (self.name, error),
358 nodes.literal_block(self.block_text, self.block_text),
359 line=self.lineno)
360 raise SystemMessagePropagation(severe)
361 else:
362 settings.record_dependencies.add(source)
363 elif 'url' in self.options:
364 source = self.options['url']
365 try:
366 with urlopen(source) as response:
367 csv_text = response.read()
368 except (URLError, OSError, ValueError) as error:
369 severe = self.reporter.severe(
370 'Problems with "%s" directive URL "%s":\n%s.'
371 % (self.name, self.options['url'], error),
372 nodes.literal_block(self.block_text, self.block_text),
373 line=self.lineno)
374 raise SystemMessagePropagation(severe)
375 csv_file = StringInput(source=csv_text, source_path=source,
376 encoding=encoding,
377 error_handler=error_handler)
378 csv_data = csv_file.read().splitlines()
379 else:
380 error = self.reporter.warning(
381 'The "%s" directive requires content; none supplied.'
382 % self.name,
383 nodes.literal_block(self.block_text, self.block_text),
384 line=self.lineno)
385 raise SystemMessagePropagation(error)
386 return csv_data, source
387
388 def parse_csv_data_into_rows(self, csv_data, dialect, source):
389 csv_reader = csv.reader((line + '\n' for line in csv_data),
390 dialect=dialect)
391 rows = []
392 max_cols = 0
393 for row in csv_reader:
394 row_data = []
395 for cell in row:
396 cell_data = (0, 0, 0, statemachine.StringList(
397 cell.splitlines(), source=source))
398 row_data.append(cell_data)
399 rows.append(row_data)
400 max_cols = max(max_cols, len(row))
401 return rows, max_cols
402
403
404 class ListTable(Table):
405
406 """
407 Implement tables whose data is encoded as a uniform two-level bullet list.
408 For further ideas, see
409 https://docutils.sourceforge.io/docs/dev/rst/alternatives.html#list-driven-tables
410 """
411
412 option_spec = {'header-rows': directives.nonnegative_int,
413 'stub-columns': directives.nonnegative_int,
414 'width': directives.length_or_percentage_or_unitless,
415 'widths': directives.value_or(('auto', ),
416 directives.positive_int_list),
417 'class': directives.class_option,
418 'name': directives.unchanged,
419 'align': align}
420
421 def run(self):
422 if not self.content:
423 error = self.reporter.error('The "%s" directive is empty; '
424 'content required.' % self.name,
425 nodes.literal_block(self.block_text, self.block_text),
426 line=self.lineno)
427 return [error]
428 title, messages = self.make_title()
429 node = nodes.Element() # anonymous container for parsing
430 self.state.nested_parse(self.content, self.content_offset, node)
431 try:
432 _num_cols, col_widths = self.check_list_content(node)
433 table_data = [[item.children for item in row_list[0]]
434 for row_list in node[0]]
435 header_rows = self.options.get('header-rows', 0)
436 stub_columns = self.options.get('stub-columns', 0)
437 self.check_table_dimensions(table_data, header_rows, stub_columns)
438 except SystemMessagePropagation as detail:
439 return [detail.args[0]]
440 table_node = self.build_table_from_list(table_data, col_widths,
441 header_rows, stub_columns)
442 if 'align' in self.options:
443 table_node['align'] = self.options.get('align')
444 table_node['classes'] += self.options.get('class', [])
445 self.set_table_width(table_node)
446 self.add_name(table_node)
447 if title:
448 table_node.insert(0, title)
449 return [table_node] + messages
450
451 def check_list_content(self, node):
452 if len(node) != 1 or not isinstance(node[0], nodes.bullet_list):
453 error = self.reporter.error(
454 'Error parsing content block for the "%s" directive: '
455 'exactly one bullet list expected.' % self.name,
456 nodes.literal_block(self.block_text, self.block_text),
457 line=self.lineno)
458 raise SystemMessagePropagation(error)
459 list_node = node[0]
460 num_cols = 0
461 # Check for a uniform two-level bullet list:
462 for item_index in range(len(list_node)):
463 item = list_node[item_index]
464 if len(item) != 1 or not isinstance(item[0], nodes.bullet_list):
465 error = self.reporter.error(
466 'Error parsing content block for the "%s" directive: '
467 'two-level bullet list expected, but row %s does not '
468 'contain a second-level bullet list.'
469 % (self.name, item_index + 1),
470 nodes.literal_block(self.block_text, self.block_text),
471 line=self.lineno)
472 raise SystemMessagePropagation(error)
473 elif item_index:
474 if len(item[0]) != num_cols:
475 error = self.reporter.error(
476 'Error parsing content block for the "%s" directive: '
477 'uniform two-level bullet list expected, but row %s '
478 'does not contain the same number of items as row 1 '
479 '(%s vs %s).'
480 % (self.name, item_index + 1, len(item[0]), num_cols),
481 nodes.literal_block(self.block_text, self.block_text),
482 line=self.lineno)
483 raise SystemMessagePropagation(error)
484 else:
485 num_cols = len(item[0])
486 col_widths = self.get_column_widths(num_cols)
487 return num_cols, col_widths
488
489 def build_table_from_list(self, table_data,
490 col_widths, header_rows, stub_columns):
491 table = nodes.table()
492 (table.source,
493 table.line) = self.state_machine.get_source_and_line(self.lineno)
494 if self.widths == 'auto':
495 table['classes'] += ['colwidths-auto']
496 elif self.widths: # explicitly set column widths
497 table['classes'] += ['colwidths-given']
498 tgroup = nodes.tgroup(cols=len(col_widths))
499 table += tgroup
500 for col_width in col_widths:
501 colspec = nodes.colspec()
502 if col_width is not None:
503 colspec.attributes['colwidth'] = col_width
504 if stub_columns:
505 colspec.attributes['stub'] = True
506 stub_columns -= 1
507 tgroup += colspec
508 rows = []
509 for row in table_data:
510 row_node = nodes.row()
511 for cell in row:
512 entry = nodes.entry()
513 entry += cell
514 row_node += entry
515 rows.append(row_node)
516 if header_rows:
517 thead = nodes.thead()
518 thead.extend(rows[:header_rows])
519 tgroup += thead
520 tbody = nodes.tbody()
521 tbody.extend(rows[header_rows:])
522 tgroup += tbody
523 return table