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

Skipping inline code when replacing linebreaks and super/sub scripts

parent 0fe7ecd5
Loading
Loading
Loading
Loading
+20 −2
Changes for generateBaseline/pandocFilter.py: 20 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -108,6 +108,7 @@ def checkInCodeBlock(line:str) -> bool:

# Patterns for skipping transforms inside code blocks and tables.
_BLOCKQUOTE_CODE_REGEX = re.compile(r'^\s*>\s*(?:```|    )')
_INLINE_CODE_REGEX = re.compile(r'`[^`\n]+`')
_MATCH_TABLE = re.compile(r'^\s*\|.*\|\s*$')
_MATCH_TABLE_SEPARATOR = re.compile(r'^\s*\|([-:]+\|)+\s*$')
_MATCH_GRID_TABLE = re.compile(r'^\s*(\+[:-]+)+\+\s*$')
@@ -123,6 +124,9 @@ class SkipCodeAndTables:
	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.

	Inline code spans (`` `like this` ``) are handled separately by
	``map_outside_inline_code`` when applying per-line transforms.
	"""

	def __init__(self):
@@ -178,16 +182,30 @@ class SkipCodeAndTables:

		return False

	@staticmethod
	def map_outside_inline_code(line: str, transform) -> str:
		"""Apply ``transform`` only outside single-backtick inline code spans."""
		parts: list[str] = []
		last = 0
		for match in _INLINE_CODE_REGEX.finditer(line):
			if match.start() > last:
				parts.append(transform(line[last:match.start()]))
			parts.append(match.group(0))
			last = match.end()
		if last < len(line) or last == 0:
			parts.append(transform(line[last:]))
		return ''.join(parts)


def map_outside_code_and_tables(md_lines: list[str], transform) -> list[str]:
	"""Apply ``transform(line)`` only outside code blocks and tables."""
	"""Apply ``transform(line)`` only outside code blocks, tables, and inline code."""
	skipper = SkipCodeAndTables()
	result: list[str] = []
	for line in md_lines:
		if skipper.should_skip(line):
			result.append(line)
		else:
			result.append(transform(line))
			result.append(skipper.map_outside_inline_code(line, transform))
	return result