PageRenderTime 64ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/documentor/libraries/docutils-0.9.1-py3.2/docutils/parsers/rst/tableparser.py

https://github.com/tictactatic/Superdesk
Python | 544 lines | 439 code | 25 blank | 80 comment | 43 complexity | 77ff26acbbcf441c05a51aba446bd95f MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-3.0, GPL-2.0
  1. # $Id: tableparser.py 7320 2012-01-19 22:33:02Z milde $
  2. # Author: David Goodger <goodger@python.org>
  3. # Copyright: This module has been placed in the public domain.
  4. """
  5. This module defines table parser classes,which parse plaintext-graphic tables
  6. and produce a well-formed data structure suitable for building a CALS table.
  7. :Classes:
  8. - `GridTableParser`: Parse fully-formed tables represented with a grid.
  9. - `SimpleTableParser`: Parse simple tables, delimited by top & bottom
  10. borders.
  11. :Exception class: `TableMarkupError`
  12. :Function:
  13. `update_dict_of_lists()`: Merge two dictionaries containing list values.
  14. """
  15. __docformat__ = 'reStructuredText'
  16. import re
  17. import sys
  18. from docutils import DataError
  19. from docutils.utils import strip_combining_chars
  20. class TableMarkupError(DataError):
  21. """
  22. Raise if there is any problem with table markup.
  23. The keyword argument `offset` denotes the offset of the problem
  24. from the table's start line.
  25. """
  26. def __init__(self, *args, **kwargs):
  27. self.offset = kwargs.pop('offset', 0)
  28. DataError.__init__(self, *args)
  29. class TableParser:
  30. """
  31. Abstract superclass for the common parts of the syntax-specific parsers.
  32. """
  33. head_body_separator_pat = None
  34. """Matches the row separator between head rows and body rows."""
  35. double_width_pad_char = '\x00'
  36. """Padding character for East Asian double-width text."""
  37. def parse(self, block):
  38. """
  39. Analyze the text `block` and return a table data structure.
  40. Given a plaintext-graphic table in `block` (list of lines of text; no
  41. whitespace padding), parse the table, construct and return the data
  42. necessary to construct a CALS table or equivalent.
  43. Raise `TableMarkupError` if there is any problem with the markup.
  44. """
  45. self.setup(block)
  46. self.find_head_body_sep()
  47. self.parse_table()
  48. structure = self.structure_from_cells()
  49. return structure
  50. def find_head_body_sep(self):
  51. """Look for a head/body row separator line; store the line index."""
  52. for i in range(len(self.block)):
  53. line = self.block[i]
  54. if self.head_body_separator_pat.match(line):
  55. if self.head_body_sep:
  56. raise TableMarkupError(
  57. 'Multiple head/body row separators '
  58. '(table lines %s and %s); only one allowed.'
  59. % (self.head_body_sep+1, i+1), offset=i)
  60. else:
  61. self.head_body_sep = i
  62. self.block[i] = line.replace('=', '-')
  63. if self.head_body_sep == 0 or self.head_body_sep == (len(self.block)
  64. - 1):
  65. raise TableMarkupError('The head/body row separator may not be '
  66. 'the first or last line of the table.',
  67. offset=i)
  68. class GridTableParser(TableParser):
  69. """
  70. Parse a grid table using `parse()`.
  71. Here's an example of a grid table::
  72. +------------------------+------------+----------+----------+
  73. | Header row, column 1 | Header 2 | Header 3 | Header 4 |
  74. +========================+============+==========+==========+
  75. | body row 1, column 1 | column 2 | column 3 | column 4 |
  76. +------------------------+------------+----------+----------+
  77. | body row 2 | Cells may span columns. |
  78. +------------------------+------------+---------------------+
  79. | body row 3 | Cells may | - Table cells |
  80. +------------------------+ span rows. | - contain |
  81. | body row 4 | | - body elements. |
  82. +------------------------+------------+---------------------+
  83. Intersections use '+', row separators use '-' (except for one optional
  84. head/body row separator, which uses '='), and column separators use '|'.
  85. Passing the above table to the `parse()` method will result in the
  86. following data structure::
  87. ([24, 12, 10, 10],
  88. [[(0, 0, 1, ['Header row, column 1']),
  89. (0, 0, 1, ['Header 2']),
  90. (0, 0, 1, ['Header 3']),
  91. (0, 0, 1, ['Header 4'])]],
  92. [[(0, 0, 3, ['body row 1, column 1']),
  93. (0, 0, 3, ['column 2']),
  94. (0, 0, 3, ['column 3']),
  95. (0, 0, 3, ['column 4'])],
  96. [(0, 0, 5, ['body row 2']),
  97. (0, 2, 5, ['Cells may span columns.']),
  98. None,
  99. None],
  100. [(0, 0, 7, ['body row 3']),
  101. (1, 0, 7, ['Cells may', 'span rows.', '']),
  102. (1, 1, 7, ['- Table cells', '- contain', '- body elements.']),
  103. None],
  104. [(0, 0, 9, ['body row 4']), None, None, None]])
  105. The first item is a list containing column widths (colspecs). The second
  106. item is a list of head rows, and the third is a list of body rows. Each
  107. row contains a list of cells. Each cell is either None (for a cell unused
  108. because of another cell's span), or a tuple. A cell tuple contains four
  109. items: the number of extra rows used by the cell in a vertical span
  110. (morerows); the number of extra columns used by the cell in a horizontal
  111. span (morecols); the line offset of the first line of the cell contents;
  112. and the cell contents, a list of lines of text.
  113. """
  114. head_body_separator_pat = re.compile(r'\+=[=+]+=\+ *$')
  115. def setup(self, block):
  116. self.block = block[:] # make a copy; it may be modified
  117. self.block.disconnect() # don't propagate changes to parent
  118. self.bottom = len(block) - 1
  119. self.right = len(block[0]) - 1
  120. self.head_body_sep = None
  121. self.done = [-1] * len(block[0])
  122. self.cells = []
  123. self.rowseps = {0: [0]}
  124. self.colseps = {0: [0]}
  125. def parse_table(self):
  126. """
  127. Start with a queue of upper-left corners, containing the upper-left
  128. corner of the table itself. Trace out one rectangular cell, remember
  129. it, and add its upper-right and lower-left corners to the queue of
  130. potential upper-left corners of further cells. Process the queue in
  131. top-to-bottom order, keeping track of how much of each text column has
  132. been seen.
  133. We'll end up knowing all the row and column boundaries, cell positions
  134. and their dimensions.
  135. """
  136. corners = [(0, 0)]
  137. while corners:
  138. top, left = corners.pop(0)
  139. if top == self.bottom or left == self.right \
  140. or top <= self.done[left]:
  141. continue
  142. result = self.scan_cell(top, left)
  143. if not result:
  144. continue
  145. bottom, right, rowseps, colseps = result
  146. update_dict_of_lists(self.rowseps, rowseps)
  147. update_dict_of_lists(self.colseps, colseps)
  148. self.mark_done(top, left, bottom, right)
  149. cellblock = self.block.get_2D_block(top + 1, left + 1,
  150. bottom, right)
  151. cellblock.disconnect() # lines in cell can't sync with parent
  152. cellblock.replace(self.double_width_pad_char, '')
  153. self.cells.append((top, left, bottom, right, cellblock))
  154. corners.extend([(top, right), (bottom, left)])
  155. corners.sort()
  156. if not self.check_parse_complete():
  157. raise TableMarkupError('Malformed table; parse incomplete.')
  158. def mark_done(self, top, left, bottom, right):
  159. """For keeping track of how much of each text column has been seen."""
  160. before = top - 1
  161. after = bottom - 1
  162. for col in range(left, right):
  163. assert self.done[col] == before
  164. self.done[col] = after
  165. def check_parse_complete(self):
  166. """Each text column should have been completely seen."""
  167. last = self.bottom - 1
  168. for col in range(self.right):
  169. if self.done[col] != last:
  170. return False
  171. return True
  172. def scan_cell(self, top, left):
  173. """Starting at the top-left corner, start tracing out a cell."""
  174. assert self.block[top][left] == '+'
  175. result = self.scan_right(top, left)
  176. return result
  177. def scan_right(self, top, left):
  178. """
  179. Look for the top-right corner of the cell, and make note of all column
  180. boundaries ('+').
  181. """
  182. colseps = {}
  183. line = self.block[top]
  184. for i in range(left + 1, self.right + 1):
  185. if line[i] == '+':
  186. colseps[i] = [top]
  187. result = self.scan_down(top, left, i)
  188. if result:
  189. bottom, rowseps, newcolseps = result
  190. update_dict_of_lists(colseps, newcolseps)
  191. return bottom, i, rowseps, colseps
  192. elif line[i] != '-':
  193. return None
  194. return None
  195. def scan_down(self, top, left, right):
  196. """
  197. Look for the bottom-right corner of the cell, making note of all row
  198. boundaries.
  199. """
  200. rowseps = {}
  201. for i in range(top + 1, self.bottom + 1):
  202. if self.block[i][right] == '+':
  203. rowseps[i] = [right]
  204. result = self.scan_left(top, left, i, right)
  205. if result:
  206. newrowseps, colseps = result
  207. update_dict_of_lists(rowseps, newrowseps)
  208. return i, rowseps, colseps
  209. elif self.block[i][right] != '|':
  210. return None
  211. return None
  212. def scan_left(self, top, left, bottom, right):
  213. """
  214. Noting column boundaries, look for the bottom-left corner of the cell.
  215. It must line up with the starting point.
  216. """
  217. colseps = {}
  218. line = self.block[bottom]
  219. for i in range(right - 1, left, -1):
  220. if line[i] == '+':
  221. colseps[i] = [bottom]
  222. elif line[i] != '-':
  223. return None
  224. if line[left] != '+':
  225. return None
  226. result = self.scan_up(top, left, bottom, right)
  227. if result is not None:
  228. rowseps = result
  229. return rowseps, colseps
  230. return None
  231. def scan_up(self, top, left, bottom, right):
  232. """
  233. Noting row boundaries, see if we can return to the starting point.
  234. """
  235. rowseps = {}
  236. for i in range(bottom - 1, top, -1):
  237. if self.block[i][left] == '+':
  238. rowseps[i] = [left]
  239. elif self.block[i][left] != '|':
  240. return None
  241. return rowseps
  242. def structure_from_cells(self):
  243. """
  244. From the data collected by `scan_cell()`, convert to the final data
  245. structure.
  246. """
  247. rowseps = list(self.rowseps.keys()) # list of row boundaries
  248. rowseps.sort()
  249. rowindex = {}
  250. for i in range(len(rowseps)):
  251. rowindex[rowseps[i]] = i # row boundary -> row number mapping
  252. colseps = list(self.colseps.keys()) # list of column boundaries
  253. colseps.sort()
  254. colindex = {}
  255. for i in range(len(colseps)):
  256. colindex[colseps[i]] = i # column boundary -> col number map
  257. colspecs = [(colseps[i] - colseps[i - 1] - 1)
  258. for i in range(1, len(colseps))] # list of column widths
  259. # prepare an empty table with the correct number of rows & columns
  260. onerow = [None for i in range(len(colseps) - 1)]
  261. rows = [onerow[:] for i in range(len(rowseps) - 1)]
  262. # keep track of # of cells remaining; should reduce to zero
  263. remaining = (len(rowseps) - 1) * (len(colseps) - 1)
  264. for top, left, bottom, right, block in self.cells:
  265. rownum = rowindex[top]
  266. colnum = colindex[left]
  267. assert rows[rownum][colnum] is None, (
  268. 'Cell (row %s, column %s) already used.'
  269. % (rownum + 1, colnum + 1))
  270. morerows = rowindex[bottom] - rownum - 1
  271. morecols = colindex[right] - colnum - 1
  272. remaining -= (morerows + 1) * (morecols + 1)
  273. # write the cell into the table
  274. rows[rownum][colnum] = (morerows, morecols, top + 1, block)
  275. assert remaining == 0, 'Unused cells remaining.'
  276. if self.head_body_sep: # separate head rows from body rows
  277. numheadrows = rowindex[self.head_body_sep]
  278. headrows = rows[:numheadrows]
  279. bodyrows = rows[numheadrows:]
  280. else:
  281. headrows = []
  282. bodyrows = rows
  283. return (colspecs, headrows, bodyrows)
  284. class SimpleTableParser(TableParser):
  285. """
  286. Parse a simple table using `parse()`.
  287. Here's an example of a simple table::
  288. ===== =====
  289. col 1 col 2
  290. ===== =====
  291. 1 Second column of row 1.
  292. 2 Second column of row 2.
  293. Second line of paragraph.
  294. 3 - Second column of row 3.
  295. - Second item in bullet
  296. list (row 3, column 2).
  297. 4 is a span
  298. ------------
  299. 5
  300. ===== =====
  301. Top and bottom borders use '=', column span underlines use '-', column
  302. separation is indicated with spaces.
  303. Passing the above table to the `parse()` method will result in the
  304. following data structure, whose interpretation is the same as for
  305. `GridTableParser`::
  306. ([5, 25],
  307. [[(0, 0, 1, ['col 1']),
  308. (0, 0, 1, ['col 2'])]],
  309. [[(0, 0, 3, ['1']),
  310. (0, 0, 3, ['Second column of row 1.'])],
  311. [(0, 0, 4, ['2']),
  312. (0, 0, 4, ['Second column of row 2.',
  313. 'Second line of paragraph.'])],
  314. [(0, 0, 6, ['3']),
  315. (0, 0, 6, ['- Second column of row 3.',
  316. '',
  317. '- Second item in bullet',
  318. ' list (row 3, column 2).'])],
  319. [(0, 1, 10, ['4 is a span'])],
  320. [(0, 0, 12, ['5']),
  321. (0, 0, 12, [''])]])
  322. """
  323. head_body_separator_pat = re.compile('=[ =]*$')
  324. span_pat = re.compile('-[ -]*$')
  325. def setup(self, block):
  326. self.block = block[:] # make a copy; it will be modified
  327. self.block.disconnect() # don't propagate changes to parent
  328. # Convert top & bottom borders to column span underlines:
  329. self.block[0] = self.block[0].replace('=', '-')
  330. self.block[-1] = self.block[-1].replace('=', '-')
  331. self.head_body_sep = None
  332. self.columns = []
  333. self.border_end = None
  334. self.table = []
  335. self.done = [-1] * len(block[0])
  336. self.rowseps = {0: [0]}
  337. self.colseps = {0: [0]}
  338. def parse_table(self):
  339. """
  340. First determine the column boundaries from the top border, then
  341. process rows. Each row may consist of multiple lines; accumulate
  342. lines until a row is complete. Call `self.parse_row` to finish the
  343. job.
  344. """
  345. # Top border must fully describe all table columns.
  346. self.columns = self.parse_columns(self.block[0], 0)
  347. self.border_end = self.columns[-1][1]
  348. firststart, firstend = self.columns[0]
  349. offset = 1 # skip top border
  350. start = 1
  351. text_found = None
  352. while offset < len(self.block):
  353. line = self.block[offset]
  354. if self.span_pat.match(line):
  355. # Column span underline or border; row is complete.
  356. self.parse_row(self.block[start:offset], start,
  357. (line.rstrip(), offset))
  358. start = offset + 1
  359. text_found = None
  360. elif line[firststart:firstend].strip():
  361. # First column not blank, therefore it's a new row.
  362. if text_found and offset != start:
  363. self.parse_row(self.block[start:offset], start)
  364. start = offset
  365. text_found = 1
  366. elif not text_found:
  367. start = offset + 1
  368. offset += 1
  369. def parse_columns(self, line, offset):
  370. """
  371. Given a column span underline, return a list of (begin, end) pairs.
  372. """
  373. cols = []
  374. end = 0
  375. while True:
  376. begin = line.find('-', end)
  377. end = line.find(' ', begin)
  378. if begin < 0:
  379. break
  380. if end < 0:
  381. end = len(line)
  382. cols.append((begin, end))
  383. if self.columns:
  384. if cols[-1][1] != self.border_end:
  385. raise TableMarkupError('Column span incomplete in table '
  386. 'line %s.' % (offset+1),
  387. offset=offset)
  388. # Allow for an unbounded rightmost column:
  389. cols[-1] = (cols[-1][0], self.columns[-1][1])
  390. return cols
  391. def init_row(self, colspec, offset):
  392. i = 0
  393. cells = []
  394. for start, end in colspec:
  395. morecols = 0
  396. try:
  397. assert start == self.columns[i][0]
  398. while end != self.columns[i][1]:
  399. i += 1
  400. morecols += 1
  401. except (AssertionError, IndexError):
  402. raise TableMarkupError('Column span alignment problem '
  403. 'in table line %s.' % (offset+2),
  404. offset=offset+1)
  405. cells.append([0, morecols, offset, []])
  406. i += 1
  407. return cells
  408. def parse_row(self, lines, start, spanline=None):
  409. """
  410. Given the text `lines` of a row, parse it and append to `self.table`.
  411. The row is parsed according to the current column spec (either
  412. `spanline` if provided or `self.columns`). For each column, extract
  413. text from each line, and check for text in column margins. Finally,
  414. adjust for insignificant whitespace.
  415. """
  416. if not (lines or spanline):
  417. # No new row, just blank lines.
  418. return
  419. if spanline:
  420. columns = self.parse_columns(*spanline)
  421. span_offset = spanline[1]
  422. else:
  423. columns = self.columns[:]
  424. span_offset = start
  425. self.check_columns(lines, start, columns)
  426. row = self.init_row(columns, start)
  427. for i in range(len(columns)):
  428. start, end = columns[i]
  429. cellblock = lines.get_2D_block(0, start, len(lines), end)
  430. cellblock.disconnect() # lines in cell can't sync with parent
  431. cellblock.replace(self.double_width_pad_char, '')
  432. row[i][3] = cellblock
  433. self.table.append(row)
  434. def check_columns(self, lines, first_line, columns):
  435. """
  436. Check for text in column margins and text overflow in the last column.
  437. Raise TableMarkupError if anything but whitespace is in column margins.
  438. Adjust the end value for the last column if there is text overflow.
  439. """
  440. # "Infinite" value for a dummy last column's beginning, used to
  441. # check for text overflow:
  442. columns.append((sys.maxsize, None))
  443. lastcol = len(columns) - 2
  444. # combining characters do not contribute to the column width
  445. lines = [strip_combining_chars(line) for line in lines]
  446. for i in range(len(columns) - 1):
  447. start, end = columns[i]
  448. nextstart = columns[i+1][0]
  449. offset = 0
  450. for line in lines:
  451. if i == lastcol and line[end:].strip():
  452. text = line[start:].rstrip()
  453. new_end = start + len(text)
  454. columns[i] = (start, new_end)
  455. main_start, main_end = self.columns[-1]
  456. if new_end > main_end:
  457. self.columns[-1] = (main_start, new_end)
  458. elif line[end:nextstart].strip():
  459. raise TableMarkupError('Text in column margin '
  460. 'in table line %s.' % (first_line+offset+1),
  461. offset=first_line+offset)
  462. offset += 1
  463. columns.pop()
  464. def structure_from_cells(self):
  465. colspecs = [end - start for start, end in self.columns]
  466. first_body_row = 0
  467. if self.head_body_sep:
  468. for i in range(len(self.table)):
  469. if self.table[i][0][2] > self.head_body_sep:
  470. first_body_row = i
  471. break
  472. return (colspecs, self.table[:first_body_row],
  473. self.table[first_body_row:])
  474. def update_dict_of_lists(master, newdata):
  475. """
  476. Extend the list values of `master` with those from `newdata`.
  477. Both parameters must be dictionaries containing list values.
  478. """
  479. for key, values in list(newdata.items()):
  480. master.setdefault(key, []).extend(values)