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

Remove indentation of grid tables so Pandoc can write proper Word tables

parent af73449a
Loading
Loading
Loading
Loading
Loading
+126
Changes for generateBaseline/pandocFilter.py: 126 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -674,6 +674,130 @@ def replaceSuperscriptsAndSubscripts(progress:Progress, mdLines:list[str]) -> li
	progress.stop_task(_taskID)
	return _lines

def _is_grid_table_line(line:str) -> bool:
	"""A grid-table line starts with + or | once its leading indent is ignored."""
	if line.strip() == '':
		return False
	body = line.lstrip(' \t')
	return (
		_MATCH_GRID_TABLE.match(body) is not None
		or _MATCH_GRID_TABLE_HEADER_SEPARATOR.match(body) is not None
		or _MATCH_GRID_TABLE_BODY_SEPARATOR.match(body) is not None
		or re.match(r'^\|.*\|', body) is not None
	)


def _line_body(line:str) -> str:
	if line.endswith('\r\n'):
		return line[:-2]
	if line.endswith('\n'):
		return line[:-1]
	return line


def _is_table_caption(line:str) -> bool:
	"""A markdown table caption, or a caption already written as ``Table:``."""
	text = line.strip()
	if re.match(r'^Table\s*:', text, re.IGNORECASE):
		return True
	return re.match(r'^\*\*Table\b.*\*\*\s*$', text, re.IGNORECASE) is not None


def _strip_shared_indent(lines:list[str]) -> list[str]:
	"""Remove the indent shared by the grid-table lines, keeping each line ending.

	The amount is taken from the table lines, so a caption with the same indent
	is moved with them.
	"""
	bodies = [_line_body(line) for line in lines]
	measured = [body for line, body in zip(lines, bodies) if _is_grid_table_line(line)]
	if not measured:
		measured = [body for body in bodies if body.strip()]
	indents = [len(re.match(r'[ \t]*', body).group(0)) for body in measured if body.strip()]
	if not indents or min(indents) == 0:
		return lines
	indent = min(indents)
	stripped = []
	for line, body in zip(lines, bodies):
		ending = line[len(body):]
		stripped.append(re.sub(rf'^[ \t]{{0,{indent}}}', '', body) + ending)
	return stripped


def _take_preceding_caption(lines:list[str]) -> list[str]:
	"""Lift a caption, and the blank lines between it and the table, off the output."""
	if not lines:
		return []
	blanks:list[str] = []
	while lines and lines[-1].strip() == '':
		blanks.append(lines.pop())
	if lines and _is_table_caption(lines[-1]):
		caption = lines.pop()
		blanks.reverse()
		return [caption, *blanks]
	lines.extend(reversed(blanks))
	return []


def removeGridTableIndent(progress:Progress, mdLines:list[str]) -> list[str]:
	"""Remove the leading indent of a grid table so Pandoc can read it.

	Pandoc recognizes a grid table only when its first + is in column 1.
	A table indented under a list item is moved to the left margin, together
	with a caption line immediately before or after it.
	"""
	_taskID = progress.add_task('[blue]Removing grid table indentation', total=0)
	resetCodeBlockState()

	_lines:list[str] = []
	block:list[str] = []
	after_blanks:list[str] = []

	def _flush() -> None:
		nonlocal block
		if not block:
			return
		dedented = _strip_shared_indent(block)
		if dedented != block:
			print(f'Removed indentation from grid table: {dedented[0].strip()}')
		_lines.extend(dedented)
		block = []

	for line in mdLines:
		if checkInCodeBlock(line):
			_flush()
			_lines.extend(after_blanks)
			after_blanks = []
			_lines.append(line)
			continue
		if block:
			if _is_grid_table_line(line) and not after_blanks:
				block.append(line)
				continue
			if line.strip() == '':
				after_blanks.append(line)
				continue
			if _is_table_caption(line):
				block.extend(after_blanks)
				block.append(line)
				after_blanks = []
				_flush()
				continue
			_flush()
			_lines.extend(after_blanks)
			after_blanks = []
		if _is_grid_table_line(line) and re.match(r'^[ \t]+\+', line):
			block.extend(_take_preceding_caption(_lines))
			block.append(line)
			continue
		_lines.append(line)
	_flush()
	_lines.extend(after_blanks)

	progress.stop_task(_taskID)
	return _lines


def convertHtmlTablesTogridTables(progress:Progress, mdLines:list[str]) -> list[str]:
	"""	Convert HTML tables to grid tables.
	"""
@@ -716,6 +840,8 @@ def process(args) -> None:
		print(f'Number of lines in the document after correcting TOC: {len(mdLines)}')
		mdLines = stripClauseAnchors(progress, mdLines)
		print(f'Number of lines in the document after removing clause anchors: {len(mdLines)}')
		mdLines = removeGridTableIndent(progress, mdLines)
		print(f'Number of lines in the document after removing grid table indentation: {len(mdLines)}')
		mdLines = replaceTableCaptions(progress, mdLines)
		print(f'Number of lines in the document after replacing table captions: {len(mdLines)}')
		mdLines = replaceFigureCaptions(progress, mdLines)