Commit 3713bd0f authored by Miguel Angel Reina Ortega's avatar Miguel Angel Reina Ortega
Browse files

Skipping tables and code blocks when replacing linebreaks and super/sub scripts

parent cddaf948
Loading
Loading
Loading
Loading
+100 −35
Changes for generateBaseline/pandocFilter.py: 100 added lines, 35 removed lines.
Original line number Diff line number Diff line
@@ -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.
	"""
@@ -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

@@ -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)
@@ -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

@@ -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: