mistune icon indicating copy to clipboard operation
mistune copied to clipboard

Table plugin lacks Markdown rendering

Open strawgate opened this issue 6 months ago • 1 comments

It would be very nice if the Table plugin supported rendering the table back to markdown to simplify table extraction during markdown -> ast -> markdown workflows.

It seems like it might be relatively straightforward?

    def render_table(renderer: MarkdownRenderer, node: dict[str, Any], block_state: BlockState) -> str:
        rows = [renderer.render_token(child, block_state) for child in node.get("children", [])]
        return "\n".join(rows)

    def render_table_head(renderer: MarkdownRenderer, node: dict[str, Any], block_state: BlockState) -> str:
        first_row = render_table_row(renderer, node, block_state)

        # Take the first row and replace everything but the | with dashes
        second_row = "".join(["-" if c != "|" else c for c in first_row])

        return "\n".join([first_row, second_row])

    def render_table_body(renderer: MarkdownRenderer, node: dict[str, Any], block_state: BlockState) -> str:
        return "\n".join([renderer.render_token(child, block_state) for child in node.get("children", [])])

    def render_table_row(renderer: MarkdownRenderer, node: dict[str, Any], block_state: BlockState) -> str:
        cells = [renderer.render_token(child, block_state) for child in node.get("children", [])]
        return "| " + " | ".join(cells) + " |"

    def render_table_cell(renderer: MarkdownRenderer, node: dict[str, Any], block_state: BlockState) -> str:
        return renderer.render_tokens(node.get("children", []), block_state)

Perhaps with escapes for any embedded pipes?

Would you be open to a contribution that adds this?

strawgate avatar Jun 15 '25 03:06 strawgate

Sure, PR is welcome.

lepture avatar Jun 15 '25 06:06 lepture