MCPcopy Create free account
hub / github.com/Python-Markdown/markdown / TableProcessor

Class TableProcessor

markdown/extensions/tables.py:38–228  ·  view source on GitHub ↗

Process Tables.

Source from the content-addressed store, hash-verified

36
37
38class TableProcessor(BlockProcessor):
39 """ Process Tables. """
40
41 RE_CODE_PIPES = re.compile(r'(?:(\\\\)|(\\`+)|(`+)|(\\\|)|(\|))')
42 RE_END_BORDER = re.compile(r'(?<!\\)(?:\\\\)*\|$')
43
44 def __init__(self, parser: blockparser.BlockParser, config: dict[str, Any]):
45 self.border: bool | int = False
46 self.separator: Sequence[str] = ''
47 self.config = config
48
49 super().__init__(parser)
50
51 def test(self, parent: etree.Element, block: str) -> bool:
52 """
53 Ensure first two rows (column header and separator row) are valid table rows.
54
55 Keep border check and separator row do avoid repeating the work.
56 """
57 is_table = False
58 # Only the first two rows are needed in most cases. Splitting the whole
59 # block here would make every test linear in the size of the block.
60 rows = [row.strip(' ') for row in block.split('\n', 2)[:2]]
61 if len(rows) > 1:
62 header0 = rows[0]
63 self.border = PIPE_NONE
64 if header0.startswith('|'):
65 self.border |= PIPE_LEFT
66 if self.RE_END_BORDER.search(header0) is not None:
67 self.border |= PIPE_RIGHT
68 row = self._split_row(header0)
69 row0_len = len(row)
70 is_table = row0_len > 1
71
72 # Each row in a single column table needs at least one pipe.
73 if not is_table and row0_len == 1 and self.border:
74 for row in block.split('\n')[1:]:
75 row = row.strip(' ')
76 is_table = row.startswith('|')
77 if not is_table:
78 is_table = self.RE_END_BORDER.search(row) is not None
79 if not is_table:
80 break
81
82 if is_table:
83 row = self._split_row(rows[1])
84 is_table = (len(row) == row0_len) and set(''.join(row)) <= set('|:- ')
85 if is_table:
86 self.separator = row
87
88 return is_table
89
90 def run(self, parent: etree.Element, blocks: list[str]) -> None:
91 """ Parse a table block and build table. """
92 block = blocks.pop(0).split('\n')
93 header = block[0].strip(' ')
94 rows = [] if len(block) < 3 else block[2:]
95

Callers 1

extendMarkdownMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected