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

Remove indent from notes, examples and code blocks + ensure lead-in keep next for code blocks

parent 2cd5ad54
Loading
Loading
Loading
Loading
Loading
+130
Changes for generateBaseline/pandocFilter.py: 130 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -840,6 +840,134 @@ def removeGridTableIndent(progress:Progress, mdLines:list[str]) -> list[str]:
	progress.stop_task(_taskID)
	return _lines

_NOTE_OR_EXAMPLE = re.compile(
	r'^[ \t]+(?:>[ \t]*)?(?:NOTES?|EXAMPLES?)\b',
	re.IGNORECASE,
)
_FENCE_OPEN = re.compile(r'^([ \t]+)(`{3,}|~{3,})([^`\n]*)$')


def _leading_indent(line:str) -> int:
	return len(re.match(r'[ \t]*', _line_body(line)).group(0))


def _remove_indent(lines:list[str], indent:int) -> list[str]:
	"""Drop up to ``indent`` leading spaces or tabs, keeping each line ending."""
	if indent <= 0:
		return lines
	stripped = []
	for line in lines:
		body = _line_body(line)
		ending = line[len(body):]
		stripped.append(re.sub(rf'^[ \t]{{0,{indent}}}', '', body) + ending)
	return stripped


def _is_fence_close(line:str, marker:str) -> bool:
	body = _line_body(line).strip()
	return len(body) >= len(marker) and body == marker[0] * len(body)


def _note_block_end(lines:list[str], start:int, indent:int) -> int:
	"""Index one past the last continuation of an indented note or example.

	A continuation stays at least as indented as the opening line and, at that
	same indent, keeps the blockquote marker. One blank line is kept when the
	blockquote goes on after it.
	"""
	i = start + 1
	while i < len(lines):
		body = _line_body(lines[i])
		if _NOTE_OR_EXAMPLE.match(body):
			break
		if body.strip() == '':
			nxt = i + 1
			if (nxt < len(lines)
					and not _NOTE_OR_EXAMPLE.match(_line_body(lines[nxt]))
					and _continues_blockquote(lines[nxt], indent)):
				i += 1
				continue
			break
		if not _continues_blockquote(lines[i], indent) and _leading_indent(lines[i]) <= indent:
			break
		i += 1
	return i


def _continues_blockquote(line:str, indent:int) -> bool:
	body = _line_body(line)
	line_indent = len(re.match(r'[ \t]*', body).group(0))
	if line_indent < indent:
		return False
	rest = body[line_indent:]
	return line_indent > indent or rest.startswith('>')


def removeBlockIndent(progress:Progress, mdLines:list[str]) -> list[str]:
	"""Move an indented note, example, or fenced code block to column 1.

	Pandoc keeps a block indented under a list item inside that item. The
	indent shared with the opening line is removed, as for a grid table.
	A fence that is itself inside a code block is left unchanged.
	"""
	_taskID = progress.add_task('[blue]Removing note, example and code block indentation', total=0)

	_lines:list[str] = []
	in_code = False
	i = 0
	while i < len(mdLines):
		line = mdLines[i]
		body = _line_body(line)
		if re.match(r'^(`{3,}|~{3,})', body):
			in_code = not in_code
			_lines.append(line)
			i += 1
			continue
		if in_code:
			_lines.append(line)
			i += 1
			continue

		fence = _FENCE_OPEN.match(body)
		if fence:
			marker = fence.group(2)
			close = None
			open_indent = len(fence.group(1))
			for j in range(i + 1, len(mdLines)):
				# The closing fence carries the same indent. A fence at column 1
				# belongs to another block, so this one is left as it is.
				if _leading_indent(mdLines[j]) >= open_indent and _is_fence_close(mdLines[j], marker):
					close = j
					break
				if re.match(r'^(`{3,}|~{3,})', _line_body(mdLines[j])):
					break
			if close is not None:
				block = mdLines[i:close + 1]
				dedented = _remove_indent(block, open_indent)
				if dedented != block:
					print(f'Removed indentation from code block: {dedented[0].strip()}')
				_lines.extend(dedented)
				i = close + 1
				continue

		if _NOTE_OR_EXAMPLE.match(body):
			indent = _leading_indent(line)
			end = _note_block_end(mdLines, i, indent)
			block = mdLines[i:end]
			dedented = _remove_indent(block, indent)
			if dedented != block:
				kind = 'example' if re.match(r'^[ \t]*>?[ \t]*EXAMPLE', body, re.IGNORECASE) else 'note'
				print(f'Removed indentation from {kind}: {dedented[0].strip()}')
			_lines.extend(dedented)
			i = end
			continue

		_lines.append(line)
		i += 1

	progress.stop_task(_taskID)
	return _lines


def convertHtmlTablesTogridTables(progress:Progress, mdLines:list[str]) -> list[str]:
	"""	Convert HTML tables to grid tables.
@@ -885,6 +1013,8 @@ def process(args) -> None:
		print(f'Number of lines in the document after removing numeric anchors: {len(mdLines)}')
		mdLines = removeGridTableIndent(progress, mdLines)
		print(f'Number of lines in the document after removing grid table indentation: {len(mdLines)}')
		mdLines = removeBlockIndent(progress, mdLines)
		print(f'Number of lines in the document after removing note, example and code block 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)
+22
Changes for generateBaseline/postprocessing.py: 22 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -3787,6 +3787,28 @@ def update_source_code_style(docx_input, docx_output):

        # Remove other rPr:rStyle elements
        para = pPr.getparent()
        if para is not None:
            # A code block of several paragraphs stays together. The paragraph
            # before the block stays with it when that paragraph ends with ':'.
            def _is_code_para(candidate):
                return (candidate is not None and candidate.tag == f"{{{ns['w']}}}p"
                        and candidate.xpath('./w:pPr/w:pStyle[@w:val="SourceCode" or @w:val="PL"]', namespaces=ns))

            def _ensure_keep_next(target):
                target_pPr = target.find(f"{{{ns['w']}}}pPr")
                if target_pPr is None:
                    target_pPr = etree.Element(f"{{{ns['w']}}}pPr")
                    target.insert(0, target_pPr)
                if not target_pPr.xpath('./w:keepNext', namespaces=ns):
                    target_pPr.append(etree.Element(f"{{{ns['w']}}}keepNext"))

            if _is_code_para(para.getnext()):
                _ensure_keep_next(para)
            previous = para.getprevious()
            if (not _is_code_para(previous)
                    and previous is not None and previous.tag == f"{{{ns['w']}}}p"
                    and _paragraph_text(previous).endswith(':')):
                _ensure_keep_next(previous)
        for rStyle in para.xpath('./w:r/w:rPr/w:rStyle', namespaces=ns):
            rPr = rStyle.getparent()
            if rPr is not None: