Loading generateBaseline/htmlToGridTable.py +36 −5 Changes for generateBaseline/htmlToGridTable.py: 36 added lines, 5 removed lines. Original line number Diff line number Diff line Loading @@ -13,6 +13,7 @@ Cell content (including existing markdown) is preserved as-is. from __future__ import annotations import re from typing import Optional, Any from bs4 import BeautifulSoup, NavigableString, Comment Loading Loading @@ -76,7 +77,8 @@ def _extractHtmlCellContent(cell) -> str: - <br> becomes a line break - <a href="...">text</a> becomes [text](url) - Whitespace-only lines from HTML formatting are removed - Leading/trailing blank lines from HTML formatting are removed - Internal blank lines are kept (paragraph breaks) - Non-empty line content is preserved (markdown syntax kept) """ parts: list[str] = [] Loading Loading @@ -108,10 +110,39 @@ def _extractHtmlCellContent(cell) -> str: text = ''.join(parts).replace('\r\n', '\n').replace('\r', '\n') lines = [line.strip() for line in text.split('\n')] lines = [line for line in lines if line] while lines and lines[0] == '': lines.pop(0) while lines and lines[-1] == '': lines.pop() return '\n'.join(lines) # Lines that start a markdown block inside a table cell. A hard-break backslash # must NOT be added before these, or Pandoc will not parse lists/quotes correctly. _CELL_BLOCK_START = re.compile( r'^(?:' r'$|' # blank line (paragraph break) r'[-*+]\s+|' # unordered list r'\d+\.\s+|' # ordered list r'>|' # blockquote r'```' # fenced code r')' ) def _cellLineNeedsHardBreak(cell_lines: list[str], line_index: int) -> bool: """True when this line should end with ' \\' for a Pandoc hard line break.""" if line_index >= len(cell_lines) - 1: return False # Never put a hard break on a blank line if cell_lines[line_index] == '': return False # Next line starts a block (list, quote, blank, ...) — keep a plain newline if _CELL_BLOCK_START.match(cell_lines[line_index + 1]): return False return True def _extractRowsFromTrs(trs) -> list[list[_HtmlCell]]: """Parse <tr> elements into cells, respecting colspan/rowspan occupancy.""" occupied: dict[tuple[int, int], bool] = {} Loading Loading @@ -296,8 +327,8 @@ def _updateColWidths(table: list[list[_HtmlCell]], maxCols: int, colWidths: list cellLines = cell.content.split('\n') maxLineLength = 0 for i, line in enumerate(cellLines): # Pandoc multi-line continuation adds ' \' (+2) on non-last lines extra = 2 if len(cellLines) > 1 and i < len(cellLines) - 1 else 0 # Pandoc hard-break continuation adds ' \' (+2) on some non-last lines extra = 2 if _cellLineNeedsHardBreak(cellLines, i) else 0 maxLineLength = max(maxLineLength, len(line) + extra) if maxLineLength == 0: continue Loading Loading @@ -338,7 +369,7 @@ def _generateGridSubTable(table: list[list[_HtmlCell]], maxCols: int, colWidths: if len(cellLines) > 1: if lineIndex < len(cellLines): lineContent = cellLines[lineIndex] if lineIndex < len(cellLines) - 1: if _cellLineNeedsHardBreak(cellLines, lineIndex): lineContent += ' \\' line += _formatCellContent(lineContent, width) else: Loading generateBaseline/pandocFilter.py +100 −35 Changes for generateBaseline/pandocFilter.py: 100 added lines, 35 removed lines. Original line number Diff line number Diff line Loading @@ -106,6 +106,91 @@ def checkInCodeBlock(line:str) -> bool: return _inCodeBlock # Patterns for skipping transforms inside code blocks and tables. _BLOCKQUOTE_CODE_REGEX = re.compile(r'^\s*>\s*(?:```| )') _MATCH_TABLE = re.compile(r'^\s*\|.*\|\s*$') _MATCH_TABLE_SEPARATOR = re.compile(r'^\s*\|([-:]+\|)+\s*$') _MATCH_GRID_TABLE = re.compile(r'^\s*(\+[:-]+)+\+\s*$') _MATCH_GRID_TABLE_HEADER_SEPARATOR = re.compile(r'^\+([=:]+\+)+$') _MATCH_GRID_TABLE_BODY_SEPARATOR = re.compile(r'^[+|](.*(\+[:-]+\+($|.*[+|]$))|[-]+[|+]$)') _MATCH_HTML_TABLE_START = re.compile(r'<\s*table\b', re.IGNORECASE) _MATCH_HTML_TABLE_END = re.compile(r'<\s*/\s*table\s*>', re.IGNORECASE) class SkipCodeAndTables: """Track whether the current markdown line is inside a code block or table. Call ``should_skip(line)`` once per line while iterating. Returns True when the line is inside a fenced/indented/blockquote code block, or a pipe, grid, or HTML table, and should be left unchanged by transforms. """ def __init__(self): self._in_code_block = False self._in_table = False self._in_grid_table = False self._in_html_table = False self._table_has_separator = False def should_skip(self, line: str) -> bool: # Code: fenced ```, 4-space indent, or the same inside a blockquote if (line.lstrip().startswith('```') or line.startswith(' ') or _BLOCKQUOTE_CODE_REGEX.match(line)): self._in_code_block = not self._in_code_block return True if self._in_code_block: return True # HTML tables (may still be present before convertHtmlTablesTogridTables) if _MATCH_HTML_TABLE_START.search(line) and not self._in_html_table: self._in_html_table = True if self._in_html_table: if _MATCH_HTML_TABLE_END.search(line): self._in_html_table = False return True # Pipe tables if _MATCH_TABLE.match(line) and not self._in_table and not self._in_grid_table: self._in_table = True return True if self._in_table: if _MATCH_TABLE_SEPARATOR.match(line) and not self._table_has_separator: self._table_has_separator = True return True if _MATCH_TABLE.match(line): return True self._in_table = False self._table_has_separator = False # Fall through: first line after the table is not skipped # Grid tables if _MATCH_GRID_TABLE.match(line) and not self._in_grid_table: self._in_grid_table = True return True if self._in_grid_table: if (_MATCH_GRID_TABLE_HEADER_SEPARATOR.match(line) or _MATCH_GRID_TABLE_BODY_SEPARATOR.match(line) or _MATCH_TABLE.match(line)): return True self._in_grid_table = False # Fall through: first line after the grid table is not skipped return False def map_outside_code_and_tables(md_lines: list[str], transform) -> list[str]: """Apply ``transform(line)`` only outside code blocks and tables.""" skipper = SkipCodeAndTables() result: list[str] = [] for line in md_lines: if skipper.should_skip(line): result.append(line) else: result.append(transform(line)) return result def correctTOC(progress:Progress, mdLines:list[str], tocSection:str = 'Contents') -> list[str]: """ Correct the TOC to be compatible with pandoc. """ Loading Loading @@ -283,32 +368,18 @@ def replaceFiguresPathSvgToPng(progress: Progress, mdLines: list[str]) -> list[s def replaceLineBreaks(progress: Progress, mdLines: list[str]) -> list[str]: """ Replace <br /> linebreaks by pandoc escaped_line_breaks extension \(newline). Do not replace inside code blocks or tables (pipe, grid, or HTML). """ _taskID = progress.add_task('[blue]Replacing linebreaks', total=0) # progress.update() linebreaksregex = re.compile('<\s*br\s*/?\s*>') # Blockquote code boundary: > then optional spaces, then ``` or 4-space indent (do not strip the line first). blockquotecoderegex = re.compile(r'^\s*>\s*(?:```| )') _lines: list[str] = [] _inCodeBlock = False for line in mdLines: # 1- fenced ``` (leading whitespace allowed), 2- 4-space indent on raw line, # 3- same inside a blockquote (> optional spaces before ``` or indent) if line.lstrip().startswith('```') or line.startswith(' ') or blockquotecoderegex.match(line): _inCodeBlock = not _inCodeBlock if _inCodeBlock: _lines.append(line) continue linebreaksregex = re.compile(r'<\s*br\s*/?\s*>') # Replace linebreaks matches = re.findall(linebreaksregex, line) if matches: # Replace the linebreak with "\(newline)" _lines.append(re.sub(linebreaksregex, f'\\\n', line)) else: _lines.append(line) def _transform(line: str) -> str: if re.search(linebreaksregex, line): print(f'{line.rstrip()} has been modified to replace a linebreak') return re.sub(linebreaksregex, '\\\n', line) return line _lines = map_outside_code_and_tables(mdLines, _transform) progress.stop_task(_taskID) return _lines Loading Loading @@ -386,7 +457,7 @@ def instertLineAfterTableOrCodeBlock(progress:Progress, mdLines:list[str]) -> li matchCodefenceEnd = re.compile(r'^\s*(?:>\s*)*```\s?$', re.IGNORECASE) matchTable = re.compile(r'^\s*\|.*\|\s*$', re.IGNORECASE) matchTableSeparator = re.compile(r'^\s*\|([-: ]+\|)+\s*$', re.IGNORECASE) matchGridTable = re.compile(r'^\s*\+-.*\+\s$', re.IGNORECASE) matchGridTable = re.compile(r'^\s*(\+[:-]+)+\+\s*$', re.IGNORECASE) matchGridTableHeaderSeparator = re.compile(r'^\+([=:]+\+)+$', re.IGNORECASE) matchGridTableBodySeparator = re.compile(r'^[+|](.*(\+[:-]+\+($|.*[+|]$))|[-]+[|+]$)', re.IGNORECASE) matchNote = re.compile(r'^\s*>\s*', re.IGNORECASE) Loading Loading @@ -522,23 +593,18 @@ def replaceBulletedLettersLists(progress:Progress, mdLines:list[str]) -> list[st def replaceSuperscriptsAndSubscripts(progress:Progress, mdLines:list[str]) -> list[str]: """ Replace superscripts and subscripts with pandoc superscript and subscript extensions. Do not replace inside code blocks or tables (pipe, grid, or HTML). """ _taskID = progress.add_task('[blue]Replacing superscripts and subscripts', total=0) # progress.update() _lines:list[str] = [] for line in mdLines: # If we are in a code block, we are not in a list if checkInCodeBlock(line): _lines.append(line) continue # Replace all superscript/subscript tags in the same line. def _transform(line: str) -> str: converted_line = line.replace('<sup>', '^').replace('</sup>', '^') converted_line = converted_line.replace('<sub>', '~').replace('</sub>', '~') _lines.append(converted_line) if converted_line != line: print(f'{line.rstrip()} has been modified to replace superscripts and subscripts') return converted_line #print(f'{_lines}') _lines = map_outside_code_and_tables(mdLines, _transform) progress.stop_task(_taskID) return _lines Loading @@ -565,7 +631,6 @@ def convertHtmlTablesTogridTables(progress:Progress, mdLines:list[str]) -> list[ htmlTable += line inTable = False gridTable = generateGridTableFromHtml(htmlTable) print(f'{gridTable}') _lines.append(gridTable) htmlTable = '' elif inTable: Loading Loading
generateBaseline/htmlToGridTable.py +36 −5 Changes for generateBaseline/htmlToGridTable.py: 36 added lines, 5 removed lines. Original line number Diff line number Diff line Loading @@ -13,6 +13,7 @@ Cell content (including existing markdown) is preserved as-is. from __future__ import annotations import re from typing import Optional, Any from bs4 import BeautifulSoup, NavigableString, Comment Loading Loading @@ -76,7 +77,8 @@ def _extractHtmlCellContent(cell) -> str: - <br> becomes a line break - <a href="...">text</a> becomes [text](url) - Whitespace-only lines from HTML formatting are removed - Leading/trailing blank lines from HTML formatting are removed - Internal blank lines are kept (paragraph breaks) - Non-empty line content is preserved (markdown syntax kept) """ parts: list[str] = [] Loading Loading @@ -108,10 +110,39 @@ def _extractHtmlCellContent(cell) -> str: text = ''.join(parts).replace('\r\n', '\n').replace('\r', '\n') lines = [line.strip() for line in text.split('\n')] lines = [line for line in lines if line] while lines and lines[0] == '': lines.pop(0) while lines and lines[-1] == '': lines.pop() return '\n'.join(lines) # Lines that start a markdown block inside a table cell. A hard-break backslash # must NOT be added before these, or Pandoc will not parse lists/quotes correctly. _CELL_BLOCK_START = re.compile( r'^(?:' r'$|' # blank line (paragraph break) r'[-*+]\s+|' # unordered list r'\d+\.\s+|' # ordered list r'>|' # blockquote r'```' # fenced code r')' ) def _cellLineNeedsHardBreak(cell_lines: list[str], line_index: int) -> bool: """True when this line should end with ' \\' for a Pandoc hard line break.""" if line_index >= len(cell_lines) - 1: return False # Never put a hard break on a blank line if cell_lines[line_index] == '': return False # Next line starts a block (list, quote, blank, ...) — keep a plain newline if _CELL_BLOCK_START.match(cell_lines[line_index + 1]): return False return True def _extractRowsFromTrs(trs) -> list[list[_HtmlCell]]: """Parse <tr> elements into cells, respecting colspan/rowspan occupancy.""" occupied: dict[tuple[int, int], bool] = {} Loading Loading @@ -296,8 +327,8 @@ def _updateColWidths(table: list[list[_HtmlCell]], maxCols: int, colWidths: list cellLines = cell.content.split('\n') maxLineLength = 0 for i, line in enumerate(cellLines): # Pandoc multi-line continuation adds ' \' (+2) on non-last lines extra = 2 if len(cellLines) > 1 and i < len(cellLines) - 1 else 0 # Pandoc hard-break continuation adds ' \' (+2) on some non-last lines extra = 2 if _cellLineNeedsHardBreak(cellLines, i) else 0 maxLineLength = max(maxLineLength, len(line) + extra) if maxLineLength == 0: continue Loading Loading @@ -338,7 +369,7 @@ def _generateGridSubTable(table: list[list[_HtmlCell]], maxCols: int, colWidths: if len(cellLines) > 1: if lineIndex < len(cellLines): lineContent = cellLines[lineIndex] if lineIndex < len(cellLines) - 1: if _cellLineNeedsHardBreak(cellLines, lineIndex): lineContent += ' \\' line += _formatCellContent(lineContent, width) else: Loading
generateBaseline/pandocFilter.py +100 −35 Changes for generateBaseline/pandocFilter.py: 100 added lines, 35 removed lines. Original line number Diff line number Diff line Loading @@ -106,6 +106,91 @@ def checkInCodeBlock(line:str) -> bool: return _inCodeBlock # Patterns for skipping transforms inside code blocks and tables. _BLOCKQUOTE_CODE_REGEX = re.compile(r'^\s*>\s*(?:```| )') _MATCH_TABLE = re.compile(r'^\s*\|.*\|\s*$') _MATCH_TABLE_SEPARATOR = re.compile(r'^\s*\|([-:]+\|)+\s*$') _MATCH_GRID_TABLE = re.compile(r'^\s*(\+[:-]+)+\+\s*$') _MATCH_GRID_TABLE_HEADER_SEPARATOR = re.compile(r'^\+([=:]+\+)+$') _MATCH_GRID_TABLE_BODY_SEPARATOR = re.compile(r'^[+|](.*(\+[:-]+\+($|.*[+|]$))|[-]+[|+]$)') _MATCH_HTML_TABLE_START = re.compile(r'<\s*table\b', re.IGNORECASE) _MATCH_HTML_TABLE_END = re.compile(r'<\s*/\s*table\s*>', re.IGNORECASE) class SkipCodeAndTables: """Track whether the current markdown line is inside a code block or table. Call ``should_skip(line)`` once per line while iterating. Returns True when the line is inside a fenced/indented/blockquote code block, or a pipe, grid, or HTML table, and should be left unchanged by transforms. """ def __init__(self): self._in_code_block = False self._in_table = False self._in_grid_table = False self._in_html_table = False self._table_has_separator = False def should_skip(self, line: str) -> bool: # Code: fenced ```, 4-space indent, or the same inside a blockquote if (line.lstrip().startswith('```') or line.startswith(' ') or _BLOCKQUOTE_CODE_REGEX.match(line)): self._in_code_block = not self._in_code_block return True if self._in_code_block: return True # HTML tables (may still be present before convertHtmlTablesTogridTables) if _MATCH_HTML_TABLE_START.search(line) and not self._in_html_table: self._in_html_table = True if self._in_html_table: if _MATCH_HTML_TABLE_END.search(line): self._in_html_table = False return True # Pipe tables if _MATCH_TABLE.match(line) and not self._in_table and not self._in_grid_table: self._in_table = True return True if self._in_table: if _MATCH_TABLE_SEPARATOR.match(line) and not self._table_has_separator: self._table_has_separator = True return True if _MATCH_TABLE.match(line): return True self._in_table = False self._table_has_separator = False # Fall through: first line after the table is not skipped # Grid tables if _MATCH_GRID_TABLE.match(line) and not self._in_grid_table: self._in_grid_table = True return True if self._in_grid_table: if (_MATCH_GRID_TABLE_HEADER_SEPARATOR.match(line) or _MATCH_GRID_TABLE_BODY_SEPARATOR.match(line) or _MATCH_TABLE.match(line)): return True self._in_grid_table = False # Fall through: first line after the grid table is not skipped return False def map_outside_code_and_tables(md_lines: list[str], transform) -> list[str]: """Apply ``transform(line)`` only outside code blocks and tables.""" skipper = SkipCodeAndTables() result: list[str] = [] for line in md_lines: if skipper.should_skip(line): result.append(line) else: result.append(transform(line)) return result def correctTOC(progress:Progress, mdLines:list[str], tocSection:str = 'Contents') -> list[str]: """ Correct the TOC to be compatible with pandoc. """ Loading Loading @@ -283,32 +368,18 @@ def replaceFiguresPathSvgToPng(progress: Progress, mdLines: list[str]) -> list[s def replaceLineBreaks(progress: Progress, mdLines: list[str]) -> list[str]: """ Replace <br /> linebreaks by pandoc escaped_line_breaks extension \(newline). Do not replace inside code blocks or tables (pipe, grid, or HTML). """ _taskID = progress.add_task('[blue]Replacing linebreaks', total=0) # progress.update() linebreaksregex = re.compile('<\s*br\s*/?\s*>') # Blockquote code boundary: > then optional spaces, then ``` or 4-space indent (do not strip the line first). blockquotecoderegex = re.compile(r'^\s*>\s*(?:```| )') _lines: list[str] = [] _inCodeBlock = False for line in mdLines: # 1- fenced ``` (leading whitespace allowed), 2- 4-space indent on raw line, # 3- same inside a blockquote (> optional spaces before ``` or indent) if line.lstrip().startswith('```') or line.startswith(' ') or blockquotecoderegex.match(line): _inCodeBlock = not _inCodeBlock if _inCodeBlock: _lines.append(line) continue linebreaksregex = re.compile(r'<\s*br\s*/?\s*>') # Replace linebreaks matches = re.findall(linebreaksregex, line) if matches: # Replace the linebreak with "\(newline)" _lines.append(re.sub(linebreaksregex, f'\\\n', line)) else: _lines.append(line) def _transform(line: str) -> str: if re.search(linebreaksregex, line): print(f'{line.rstrip()} has been modified to replace a linebreak') return re.sub(linebreaksregex, '\\\n', line) return line _lines = map_outside_code_and_tables(mdLines, _transform) progress.stop_task(_taskID) return _lines Loading Loading @@ -386,7 +457,7 @@ def instertLineAfterTableOrCodeBlock(progress:Progress, mdLines:list[str]) -> li matchCodefenceEnd = re.compile(r'^\s*(?:>\s*)*```\s?$', re.IGNORECASE) matchTable = re.compile(r'^\s*\|.*\|\s*$', re.IGNORECASE) matchTableSeparator = re.compile(r'^\s*\|([-: ]+\|)+\s*$', re.IGNORECASE) matchGridTable = re.compile(r'^\s*\+-.*\+\s$', re.IGNORECASE) matchGridTable = re.compile(r'^\s*(\+[:-]+)+\+\s*$', re.IGNORECASE) matchGridTableHeaderSeparator = re.compile(r'^\+([=:]+\+)+$', re.IGNORECASE) matchGridTableBodySeparator = re.compile(r'^[+|](.*(\+[:-]+\+($|.*[+|]$))|[-]+[|+]$)', re.IGNORECASE) matchNote = re.compile(r'^\s*>\s*', re.IGNORECASE) Loading Loading @@ -522,23 +593,18 @@ def replaceBulletedLettersLists(progress:Progress, mdLines:list[str]) -> list[st def replaceSuperscriptsAndSubscripts(progress:Progress, mdLines:list[str]) -> list[str]: """ Replace superscripts and subscripts with pandoc superscript and subscript extensions. Do not replace inside code blocks or tables (pipe, grid, or HTML). """ _taskID = progress.add_task('[blue]Replacing superscripts and subscripts', total=0) # progress.update() _lines:list[str] = [] for line in mdLines: # If we are in a code block, we are not in a list if checkInCodeBlock(line): _lines.append(line) continue # Replace all superscript/subscript tags in the same line. def _transform(line: str) -> str: converted_line = line.replace('<sup>', '^').replace('</sup>', '^') converted_line = converted_line.replace('<sub>', '~').replace('</sub>', '~') _lines.append(converted_line) if converted_line != line: print(f'{line.rstrip()} has been modified to replace superscripts and subscripts') return converted_line #print(f'{_lines}') _lines = map_outside_code_and_tables(mdLines, _transform) progress.stop_task(_taskID) return _lines Loading @@ -565,7 +631,6 @@ def convertHtmlTablesTogridTables(progress:Progress, mdLines:list[str]) -> list[ htmlTable += line inTable = False gridTable = generateGridTableFromHtml(htmlTable) print(f'{gridTable}') _lines.append(gridTable) htmlTable = '' elif inTable: Loading