""" Extra elements """ from __future__ import annotations import itertools import re from typing import Any, cast from marko import block, inline from marko.element import _SourceMap from marko.source import Source class Paragraph(block.Paragraph): _task_list_item_pattern = re.compile(r"(\[[\sxX]\])\s+\S") override = True def __init__(self, lines): super().__init__(lines) m = self._task_list_item_pattern.match(self.inline_body) if m: self.checked = m.group(1)[1:-1].lower() == "x" self.inline_body = self.inline_body[m.end(1) :] if self._inline_positions is not None: self._inline_positions = self._inline_positions[m.end(1) :] class Strikethrough(inline.InlineElement): pattern = re.compile(r"(? link_text.count("("): shift = link_text.count(")") - link_text.count("(") match = _MatchObj(match, end_shift=-shift) else: m = re.search(r"&[a-zA-Z]+;$", link_text) if m: match = _MatchObj(match, end_shift=-len(m.group())) yield match class Table(block.BlockElement): """A table element.""" _prefix = "" def __init__(self, children: list[TableRow], delimiters: list[str]) -> None: self.children = children self.delimiters = delimiters @property def head(self) -> TableRow: return cast(TableRow, self.children[0]) @property def num_of_cols(self) -> int: return len(self.head.children) @classmethod def match(cls, source): table_start = source._current_pos source.anchor() if not TableRow.match(source) or source.context.is_delimiter: return False head_span = source.context.row_span if TableRow.splitter.search(source.next_line()) is None: return False # consume the first row, we don't use source.consume() here # because that may unexpectedly update the line prefix. source.pos = source.match.end() head = TableRow( [ TableCell(cell, start) for cell, start in zip(source.context.cells, source.context.cell_starts) ] ) head.source_span = head_span if ( not TableRow.match(source) or not source.context.is_delimiter or len(source.context.cells) != len(head.children) ): source.reset() # invalid table, revert the source position return False source.context.table_info = { "children": [head], "delimiters": source.context.cells, } source.context.table_start = table_start source.consume() # consume the second row return True @classmethod def parse(cls, source): rv = cls(**source.context.table_info) table_start = source.context.table_start with source.under_state(rv): for d, th in zip(rv.delimiters, rv.head.children): stripped_d = d.strip() th.header = True if stripped_d[0] == ":" and stripped_d[-1] == ":": th.align = "center" elif stripped_d[0] == ":": th.align = "left" elif stripped_d[-1] == ":": th.align = "right" while not source.exhausted: for e in source.parser._build_block_element_list(): if issubclass(e, (Table, block.Paragraph)): continue if e.match(source): break else: if TableRow.match(source): rv.children.append(TableRow.parse(source)) continue break rv.source_span = (table_start, source.pos) return rv class TableRow(block.BlockElement): """A table row element.""" splitter = re.compile(r"\s*(? None: self.children = cells @classmethod def match(cls, source: Source) -> Any: line = source.next_line() if not line or not re.match(r" {,3}\S", line): return False line_start = source.match.start() if source.match else source.pos source.context.row_span = (line_start, line_start + len(line)) stripped = line.strip() leading = len(line) - len(line.lstrip()) parts = [] starts = [] last = 0 for m in cls.splitter.finditer(stripped): parts.append(stripped[last : m.start()]) starts.append(line_start + leading + last) last = m.end() parts.append(stripped[last:]) starts.append(line_start + leading + last) if parts and not parts[0]: parts.pop(0) starts.pop(0) if parts and not parts[-1]: parts.pop() starts.pop() if len(parts) < 1: return False source.context.cells = parts source.context.cell_starts = starts source.context.is_delimiter = all(cls.delimiter.match(cell) for cell in parts) return True @classmethod def parse(cls, source: Source) -> TableRow: source.consume() parent = cast(Table, source.state) cells: list[str] = source.context.cells[:] starts: list[int | None] = source.context.cell_starts[:] if len(cells) < parent.num_of_cols: pad = parent.num_of_cols - len(cells) cells.extend("" for _ in range(pad)) starts.extend(None for _ in range(pad)) elif len(cells) > parent.num_of_cols: cells = cells[: parent.num_of_cols] starts = starts[: parent.num_of_cols] cell_elements = [TableCell(cell, start) for cell, start in zip(cells, starts)] for head, cell in zip(parent.head.children, cell_elements): cell.align = cast(TableCell, head).align rv = cls(cell_elements) rv.source_span = source.context.row_span return rv class TableCell(block.BlockElement): """A table cell element.""" virtual = True def __init__(self, text: str, position: int | None = None) -> None: stripped = text.strip() self.inline_body = stripped.replace("\\|", "|") self.header = False self.align: str | None = None if position is not None: self.source_span = (position, position + len(text)) pos = position + (len(text) - len(text.lstrip())) self._inline_positions = _SourceMap.from_positions( pos + i for i in range(len(stripped)) if not ( stripped[i] == "\\" and i + 1 < len(stripped) and stripped[i + 1] == "|" ) ) class Alert(block.Quote): """Alert block element: block quote with a header like WARNING, NOTE, TIP, IMPORTANT, or CAUTION.""" priority = block.Quote.priority + 1 @classmethod def match(cls, source): return source.expect_re( r"(?im) {,3}>\s*\[\!(WARNING|NOTE|TIP|IMPORTANT|CAUTION)\]\s*$" ) @classmethod def parse(cls, source): alert_type = source.match.group(1).upper() source.next_line(require_prefix=False) source.consume() state = cls(alert_type) with source.under_state(state): state.children = source.parser.parse_source(source) return state def __init__(self, alert_type): self.alert_type = alert_type