B \1R@szdZdZddlZddlZddlmZddlmZGdddeZGdd d Z Gd d d e Z Gd d d e Z ddZ dS)a This module defines table parser classes,which parse plaintext-graphic tables and produce a well-formed data structure suitable for building a CALS table. :Classes: - `GridTableParser`: Parse fully-formed tables represented with a grid. - `SimpleTableParser`: Parse simple tables, delimited by top & bottom borders. :Exception class: `TableMarkupError` :Function: `update_dict_of_lists()`: Merge two dictionaries containing list values. ZreStructuredTextN) DataError)strip_combining_charsc@seZdZdZddZdS)TableMarkupErrorz Raise if there is any problem with table markup. The keyword argument `offset` denotes the offset of the problem from the table's start line. cOs"|dd|_tj|f|dS)Noffsetr)poprr__init__)selfargskwargsr D/tmp/pip-build-uw_ogi45/docutils/docutils/parsers/rst/tableparser.pyr&szTableMarkupError.__init__N)__name__ __module__ __qualname____doc__rr r r r rsrc@s(eZdZdZdZdZddZddZdS) TableParserzR Abstract superclass for the common parts of the syntax-specific parsers. NcCs&|||||}|S)an Analyze the text `block` and return a table data structure. Given a plaintext-graphic table in `block` (list of lines of text; no whitespace padding), parse the table, construct and return the data necessary to construct a CALS table or equivalent. Raise `TableMarkupError` if there is any problem with the markup. )setupfind_head_body_sep parse_tablestructure_from_cells)rblockZ structurer r r parse7s zTableParser.parsecCsxjtt|jD]X}|j|}|j|r|jrPtd|jd|df|dq||_|dd|j|<qW|jdks|jt|jdkrtd|ddS) z>Look for a head/body row separator line; store the line index.zLMultiple head/body row separators (table lines %s and %s); only one allowed.)r=-rzKThe head/body row separator may not be the first or last line of the table.N)rangelenrhead_body_separator_patmatch head_body_seprreplace)riliner r r rGs  zTableParser.find_head_body_sep)r rrrrdouble_width_pad_charrrr r r r r+s rc@sjeZdZdZedZddZddZddZ d d Z d d Z d dZ ddZ ddZddZddZdS)GridTableParserai Parse a grid table using `parse()`. Here's an example of a grid table:: +------------------------+------------+----------+----------+ | Header row, column 1 | Header 2 | Header 3 | Header 4 | +========================+============+==========+==========+ | body row 1, column 1 | column 2 | column 3 | column 4 | +------------------------+------------+----------+----------+ | body row 2 | Cells may span columns. | +------------------------+------------+---------------------+ | body row 3 | Cells may | - Table cells | +------------------------+ span rows. | - contain | | body row 4 | | - body elements. | +------------------------+------------+---------------------+ Intersections use '+', row separators use '-' (except for one optional head/body row separator, which uses '='), and column separators use '|'. Passing the above table to the `parse()` method will result in the following data structure:: ([24, 12, 10, 10], [[(0, 0, 1, ['Header row, column 1']), (0, 0, 1, ['Header 2']), (0, 0, 1, ['Header 3']), (0, 0, 1, ['Header 4'])]], [[(0, 0, 3, ['body row 1, column 1']), (0, 0, 3, ['column 2']), (0, 0, 3, ['column 3']), (0, 0, 3, ['column 4'])], [(0, 0, 5, ['body row 2']), (0, 2, 5, ['Cells may span columns.']), None, None], [(0, 0, 7, ['body row 3']), (1, 0, 7, ['Cells may', 'span rows.', '']), (1, 1, 7, ['- Table cells', '- contain', '- body elements.']), None], [(0, 0, 9, ['body row 4']), None, None, None]]) The first item is a list containing column widths (colspecs). The second item is a list of head rows, and the third is a list of body rows. Each row contains a list of cells. Each cell is either None (for a cell unused because of another cell's span), or a tuple. A cell tuple contains four items: the number of extra rows used by the cell in a vertical span (morerows); the number of extra columns used by the cell in a horizontal span (morecols); the line offset of the first line of the cell contents; and the cell contents, a list of lines of text. z\+=[=+]+=\+ *$cCst|dd|_|jt|d|_t|dd|_d|_dgt|d|_g|_ddgi|_ddgi|_ dS)Nrr) r disconnectrbottomrightr donecellsrowsepscolseps)rrr r r rs  zGridTableParser.setupc Csdg}x|r|d\}}||jks||jks||j|kr>q|||}|sPq|\}}}}t|j|t|j|||||||j |d|d||} | | |j d|j||||| f|||f||fg|qW|stddS)a  Start with a queue of upper-left corners, containing the upper-left corner of the table itself. Trace out one rectangular cell, remember it, and add its upper-right and lower-left corners to the queue of potential upper-left corners of further cells. Process the queue in top-to-bottom order, keeping track of how much of each text column has been seen. We'll end up knowing all the row and column boundaries, cell positions and their dimensions. )rrrrz"Malformed table; parse incomplete.N)rr(r)r* scan_cellupdate_dict_of_listsr,r- mark_doner get_2D_blockr'r!r$r+appendextendsortcheck_parse_completer) rZcornerstopleftresultr(r)r,r- cellblockr r r rs,      zGridTableParser.parse_tablecCsD|d}|d}x.t||D] }|j||ks2t||j|<qWdS)z@For keeping track of how much of each text column has been seen.rN)rr*AssertionError)rr7r8r(r)beforeaftercolr r r r1s zGridTableParser.mark_donecCs4|jd}x$t|jD]}|j||krdSqWdS)z2Each text column should have been completely seen.rFT)r(rr)r*)rlastr>r r r r6s  z$GridTableParser.check_parse_completecCs&|j||dkst|||}|S)z:Starting at the top-left corner, start tracing out a cell.+)rr; scan_right)rr7r8r9r r r r/s zGridTableParser.scan_cellc Csi}|j|}xvt|d|jdD]^}||dkrr|g||<||||}|r|\}}} t|| ||||fSq$||dkr$dSq$WdS)zr Look for the top-right corner of the cell, and make note of all column boundaries ('+'). rr@rN)rrr) scan_downr0) rr7r8r-r#r"r9r(r,Z newcolsepsr r r rAs      zGridTableParser.scan_rightc Csi}xt|d|jdD]h}|j||dkrl|g||<|||||}|r|\}}t|||||fSq|j||dkrdSqWdS)zj Look for the bottom-right corner of the cell, making note of all row boundaries. rr@|N)rr(r scan_leftr0) rr7r8r)r,r"r9Z newrowsepsr-r r r rBs   zGridTableParser.scan_downc Csi}|j|}x@t|d|dD],}||dkr<|g||<q ||dkr dSq W||dkr`dS|||||}|dk r|} | |fSdS)z Noting column boundaries, look for the bottom-left corner of the cell. It must line up with the starting point. rr&r@rN)rrscan_up) rr7r8r(r)r-r#r"r9r,r r r rDs     zGridTableParser.scan_leftcCsVi}xLt|d|dD]8}|j||dkr8|g||<q|j||dkrdSqW|S)zT Noting row boundaries, see if we can return to the starting point. rr&r@rCN)rr)rr7r8r(r)r,r"r r r rEs zGridTableParser.scan_upcst|j}|i}x tt|D]}||||<q(Wt|ji}x ttD]}|||<qdWfddtdtD}ddttdDfddtt|dD}t|dtd}x|jD]\}} } } } ||} || }|| |dks4td| d|df|| | d}|| |d}||d|d8}|||d| f|| |<qW|dkstd |j r||j }|d|}||d}ng}|}|||fS) zh From the data collected by `scan_cell()`, convert to the final data structure. cs$g|]}||ddqS)rr ).0r")r-r r +sz8GridTableParser.structure_from_cells..rcSsg|]}dqS)Nr )rFr"r r r rG.scsg|]}ddqS)Nr )rFr")onerowr r rG/sNz&Cell (row %s, column %s) already used.rzUnused cells remaining.) listr,keysr5rrr-r+r;r )rr,Zrowindexr"ZcolindexcolspecsZrows remainingr7r8r(r)rZrownumcolnumZmorerowsmorecolsZ numheadrowsZheadrowsZbodyrowsr )r-rHr rsB   z$GridTableParser.structure_from_cellsN)r rrrrecompilerrrr1r6r/rArBrDrErr r r r r%[s4  # r%c@s^eZdZdZedZedZddZddZ dd Z d d Z dd dZ ddZ ddZd S)SimpleTableParseraQ Parse a simple table using `parse()`. Here's an example of a simple table:: ===== ===== col 1 col 2 ===== ===== 1 Second column of row 1. 2 Second column of row 2. Second line of paragraph. 3 - Second column of row 3. - Second item in bullet list (row 3, column 2). 4 is a span ------------ 5 ===== ===== Top and bottom borders use '=', column span underlines use '-', column separation is indicated with spaces. Passing the above table to the `parse()` method will result in the following data structure, whose interpretation is the same as for `GridTableParser`:: ([5, 25], [[(0, 0, 1, ['col 1']), (0, 0, 1, ['col 2'])]], [[(0, 0, 3, ['1']), (0, 0, 3, ['Second column of row 1.'])], [(0, 0, 4, ['2']), (0, 0, 4, ['Second column of row 2.', 'Second line of paragraph.'])], [(0, 0, 6, ['3']), (0, 0, 6, ['- Second column of row 3.', '', '- Second item in bullet', ' list (row 3, column 2).'])], [(0, 1, 10, ['4 is a span'])], [(0, 0, 12, ['5']), (0, 0, 12, [''])]]) z=[ =]*$z-[ -]*$cCs|dd|_|j|jddd|jd<|jddd|jd<d|_g|_d|_g|_dgt|d|_ddgi|_ ddgi|_ dS)Nrrrr&) rr'r!r columns border_endtablerr*r,r-)rrr r r rzs  zSimpleTableParser.setupcCs||jdd|_|jdd|_|jd\}}d}d}d}x|t|jkr|j|}|j|r||j|||||f|d}d}nH||| r|r||kr||j||||}d}n |s|d}|d7}q@WdS)z First determine the column boundaries from the top border, then process rows. Each row may consist of multiple lines; accumulate lines until a row is complete. Call `self.parse_row` to finish the job. rr&rN) parse_columnsrrRrSrspan_patr parse_rowrstripstrip)rZ firststartZfirstendrstartZ text_foundr#r r r rs*   zSimpleTableParser.parse_tablecCsg}d}xD|d|}|d|}|dkr,P|dkr.rrr&z'Text in column margin in table line %s.)r) r3sysmaxsizerrrYrXrRmaxrr)rre first_linerRZlastcolr"rZr^Z nextstartrr#textZnew_endZ main_startZmain_endr r r rds*      zSimpleTableParser.check_columnscCsndd|jD}d}|jrPx4tt|jD]"}|j|dd|jkr*|}Pq*W||jd||j|dfS)NcSsg|]\}}||qSr r )rFrZr^r r r rGsz:SimpleTableParser.structure_from_cells..rr`)rRr rrrT)rrKZfirst_body_rowr"r r r r sz&SimpleTableParser.structure_from_cells)N)r rrrrOrPrrVrrrUrbrWrdrr r r r rQHs-     rQcCs0x*t|D]\}}||g|qWdS)z Extend the list values of `master` with those from `newdata`. Both parameters must be dictionaries containing list values. N)rIitems setdefaultr4)Zmasternewdatakeyvaluesr r r r0sr0) rZ __docformat__rOrgZdocutilsrZdocutils.utilsrrrr%rQr0r r r r s  0nR