Loading generateBaseline/pandocFilter.py +41 −13 Changes for generateBaseline/pandocFilter.py: 41 added lines, 13 removed lines. Original line number Diff line number Diff line Loading @@ -96,13 +96,30 @@ def writeMDFile(progress:Progress, mdLines:list[str], document:str, outDirectory progress.stop_task(_taskID) # Clause and table anchors are recreated as Word bookmarks in postprocessing. # Leaving the span in the markdown makes Pandoc store an empty or hashed bookmark. # Author anchors are kept. Pandoc turns the id into a bookmark, and postprocessing # adds the numbered bookmark beside it. An id that starts with a digit is removed: # Pandoc replaces that name with a hash. # An empty <a name=...></a> includes the closing tag. An anchor that wraps text, # such as <a name="_ref_1">[1]</a>, keeps that text. _TARGET_ANCHOR = re.compile( r'''\s*<span\s+id=(?:"[^"]*"|'[^']*'|[^\s>]+)>\s*</span>|\s*<a\s+name=(?:"[^"]*"|'[^']*'|[^\s>]+)>''', r'''\s*<(?:span\s+id=(?P<span_id>"[^"]*"|'[^']*'|[^\s>]+)>\s*</span>|a\s+name=(?P<a_id>"[^"]*"|'[^']*'|[^\s>]+)>\s*(?:</a>)?)''', re.IGNORECASE, ) def _anchor_id(raw:str) -> str: if len(raw) >= 2 and raw[0] in '"\'' and raw[-1] == raw[0]: return raw[1:-1] return raw def _strip_numeric_anchors(text:str) -> str: """Remove an anchor whose id starts with a digit.""" def replace(match): raw = match.group('span_id') or match.group('a_id') or '' if _anchor_id(raw)[:1].isdigit(): return '' return match.group(0) return _TARGET_ANCHOR.sub(replace, text) _inCodeBlock = False def resetCodeBlockState() -> None: global _inCodeBlock Loading Loading @@ -272,9 +289,9 @@ def replaceTableCaptions(progress:Progress, mdLines:list[str]) -> list[str]: continue if matches: raw_rest = line.replace(matches[0], '') cleaned_rest = _TARGET_ANCHOR.sub('', raw_rest) cleaned_rest = _strip_numeric_anchors(raw_rest) if cleaned_rest != raw_rest: print(f'Removed table anchor markup from caption: {matches[0]}') print(f'Removed numeric anchor from table caption: {matches[0]}') rest_of_line = cleaned_rest.strip().lstrip('*') # move the caption to the beginning of the table and add a "Table:" prefix _idx = len(_lines) - 1 Loading @@ -291,9 +308,9 @@ def replaceTableCaptions(progress:Progress, mdLines:list[str]) -> list[str]: return _lines def stripClauseAnchors(progress:Progress, mdLines:list[str]) -> list[str]: """Remove span and anchor markup from headings. Citation links are left unchanged.""" _taskID = progress.add_task('[blue]Removing clause anchors', total=0) def stripNumericAnchors(progress:Progress, mdLines:list[str]) -> list[str]: """Remove heading anchors whose id starts with a digit. Other labels are kept.""" _taskID = progress.add_task('[blue]Removing numeric anchors', total=0) resetCodeBlockState() heading = re.compile(r'^#{1,6}\s') _lines:list[str] = [] Loading @@ -301,9 +318,9 @@ def stripClauseAnchors(progress:Progress, mdLines:list[str]) -> list[str]: if checkInCodeBlock(line) or not heading.match(line): _lines.append(line) continue new_line = _TARGET_ANCHOR.sub('', line) new_line = _strip_numeric_anchors(line) if new_line != line: print(f'Removed clause anchor markup from heading: {new_line.strip()}') print(f'Removed numeric anchor from heading: {new_line.strip()}') _lines.append(new_line) progress.stop_task(_taskID) return _lines Loading @@ -328,11 +345,22 @@ def replaceFigureCaptions(progress:Progress, mdLines:list[str]) -> list[str]: if matches: # Replace the previous figure markdown name with the captions. # Skip blank lines, then attach only if that line is an image. raw_rest = line.replace(matches[0], '') cleaned_rest = _strip_numeric_anchors(raw_rest) if cleaned_rest != raw_rest: print(f'Removed numeric anchor from figure caption: {matches[0]}') rest_of_line = cleaned_rest.strip().lstrip('*') _idx = len(_lines) - 1 while _idx >= 0 and _lines[_idx].strip() == '': _idx -= 1 if _idx >= 0 and _lines[_idx].count('![') > 0: _lines[_idx] = re.sub(r'!.*]', f'![{matches[0]}]', _lines[_idx]) image_line = re.sub(r'!.*]', f'![{matches[0]}]', _lines[_idx]) _lines[_idx] = re.sub( r'!\[[^\]]*\]\([^)]*\)', lambda match: f'{match.group(0)}{rest_of_line}', image_line, count=1, ) else: _lines.append(line) print(f'Corresponding figure not found for caption: {matches[0]}, figure caption is not removed') Loading Loading @@ -853,8 +881,8 @@ def process(args) -> None: print(f'Number of lines in the original document: {len(mdLines)}') mdLines = correctTOC(progress, mdLines) 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 = stripNumericAnchors(progress, mdLines) 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 = replaceTableCaptions(progress, mdLines) Loading generateBaseline/postprocessing.py +2 −2 Changes for generateBaseline/postprocessing.py: 2 added lines, 2 removed lines. Original line number Diff line number Diff line Loading @@ -1114,10 +1114,10 @@ def update_heading_styles(docx_input, docx_output): nonlocal next_bookmark_id if label_run is None: return # "10.1" + "Imports other md files" becomes "101-imports-other-md-files". # "10.1" + "Imports other md files" becomes "101-imports-other-md-files". Any other symbols ".", ",", ":", ";", "!", "[", "]" are removed. # The bookmark covers the number run only. Pandoc's heading bookmark is left unchanged. title_slug = re.sub(r'\s+', '-', title.strip()).lower() title_slug = re.sub(r'[.,:;!]', '', title_slug) title_slug = re.sub(r'[.,:;![\]]', '', title_slug) bookmark_name = f"{number.replace('.', '')}-{title_slug}" _remove_bookmarks(root, ns, {bookmark_name}, paragraph=para, hashed=True) _insert_bookmark_around(label_run, bookmark_name, next_bookmark_id, ns) Loading Loading
generateBaseline/pandocFilter.py +41 −13 Changes for generateBaseline/pandocFilter.py: 41 added lines, 13 removed lines. Original line number Diff line number Diff line Loading @@ -96,13 +96,30 @@ def writeMDFile(progress:Progress, mdLines:list[str], document:str, outDirectory progress.stop_task(_taskID) # Clause and table anchors are recreated as Word bookmarks in postprocessing. # Leaving the span in the markdown makes Pandoc store an empty or hashed bookmark. # Author anchors are kept. Pandoc turns the id into a bookmark, and postprocessing # adds the numbered bookmark beside it. An id that starts with a digit is removed: # Pandoc replaces that name with a hash. # An empty <a name=...></a> includes the closing tag. An anchor that wraps text, # such as <a name="_ref_1">[1]</a>, keeps that text. _TARGET_ANCHOR = re.compile( r'''\s*<span\s+id=(?:"[^"]*"|'[^']*'|[^\s>]+)>\s*</span>|\s*<a\s+name=(?:"[^"]*"|'[^']*'|[^\s>]+)>''', r'''\s*<(?:span\s+id=(?P<span_id>"[^"]*"|'[^']*'|[^\s>]+)>\s*</span>|a\s+name=(?P<a_id>"[^"]*"|'[^']*'|[^\s>]+)>\s*(?:</a>)?)''', re.IGNORECASE, ) def _anchor_id(raw:str) -> str: if len(raw) >= 2 and raw[0] in '"\'' and raw[-1] == raw[0]: return raw[1:-1] return raw def _strip_numeric_anchors(text:str) -> str: """Remove an anchor whose id starts with a digit.""" def replace(match): raw = match.group('span_id') or match.group('a_id') or '' if _anchor_id(raw)[:1].isdigit(): return '' return match.group(0) return _TARGET_ANCHOR.sub(replace, text) _inCodeBlock = False def resetCodeBlockState() -> None: global _inCodeBlock Loading Loading @@ -272,9 +289,9 @@ def replaceTableCaptions(progress:Progress, mdLines:list[str]) -> list[str]: continue if matches: raw_rest = line.replace(matches[0], '') cleaned_rest = _TARGET_ANCHOR.sub('', raw_rest) cleaned_rest = _strip_numeric_anchors(raw_rest) if cleaned_rest != raw_rest: print(f'Removed table anchor markup from caption: {matches[0]}') print(f'Removed numeric anchor from table caption: {matches[0]}') rest_of_line = cleaned_rest.strip().lstrip('*') # move the caption to the beginning of the table and add a "Table:" prefix _idx = len(_lines) - 1 Loading @@ -291,9 +308,9 @@ def replaceTableCaptions(progress:Progress, mdLines:list[str]) -> list[str]: return _lines def stripClauseAnchors(progress:Progress, mdLines:list[str]) -> list[str]: """Remove span and anchor markup from headings. Citation links are left unchanged.""" _taskID = progress.add_task('[blue]Removing clause anchors', total=0) def stripNumericAnchors(progress:Progress, mdLines:list[str]) -> list[str]: """Remove heading anchors whose id starts with a digit. Other labels are kept.""" _taskID = progress.add_task('[blue]Removing numeric anchors', total=0) resetCodeBlockState() heading = re.compile(r'^#{1,6}\s') _lines:list[str] = [] Loading @@ -301,9 +318,9 @@ def stripClauseAnchors(progress:Progress, mdLines:list[str]) -> list[str]: if checkInCodeBlock(line) or not heading.match(line): _lines.append(line) continue new_line = _TARGET_ANCHOR.sub('', line) new_line = _strip_numeric_anchors(line) if new_line != line: print(f'Removed clause anchor markup from heading: {new_line.strip()}') print(f'Removed numeric anchor from heading: {new_line.strip()}') _lines.append(new_line) progress.stop_task(_taskID) return _lines Loading @@ -328,11 +345,22 @@ def replaceFigureCaptions(progress:Progress, mdLines:list[str]) -> list[str]: if matches: # Replace the previous figure markdown name with the captions. # Skip blank lines, then attach only if that line is an image. raw_rest = line.replace(matches[0], '') cleaned_rest = _strip_numeric_anchors(raw_rest) if cleaned_rest != raw_rest: print(f'Removed numeric anchor from figure caption: {matches[0]}') rest_of_line = cleaned_rest.strip().lstrip('*') _idx = len(_lines) - 1 while _idx >= 0 and _lines[_idx].strip() == '': _idx -= 1 if _idx >= 0 and _lines[_idx].count('![') > 0: _lines[_idx] = re.sub(r'!.*]', f'![{matches[0]}]', _lines[_idx]) image_line = re.sub(r'!.*]', f'![{matches[0]}]', _lines[_idx]) _lines[_idx] = re.sub( r'!\[[^\]]*\]\([^)]*\)', lambda match: f'{match.group(0)}{rest_of_line}', image_line, count=1, ) else: _lines.append(line) print(f'Corresponding figure not found for caption: {matches[0]}, figure caption is not removed') Loading Loading @@ -853,8 +881,8 @@ def process(args) -> None: print(f'Number of lines in the original document: {len(mdLines)}') mdLines = correctTOC(progress, mdLines) 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 = stripNumericAnchors(progress, mdLines) 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 = replaceTableCaptions(progress, mdLines) Loading
generateBaseline/postprocessing.py +2 −2 Changes for generateBaseline/postprocessing.py: 2 added lines, 2 removed lines. Original line number Diff line number Diff line Loading @@ -1114,10 +1114,10 @@ def update_heading_styles(docx_input, docx_output): nonlocal next_bookmark_id if label_run is None: return # "10.1" + "Imports other md files" becomes "101-imports-other-md-files". # "10.1" + "Imports other md files" becomes "101-imports-other-md-files". Any other symbols ".", ",", ":", ";", "!", "[", "]" are removed. # The bookmark covers the number run only. Pandoc's heading bookmark is left unchanged. title_slug = re.sub(r'\s+', '-', title.strip()).lower() title_slug = re.sub(r'[.,:;!]', '', title_slug) title_slug = re.sub(r'[.,:;![\]]', '', title_slug) bookmark_name = f"{number.replace('.', '')}-{title_slug}" _remove_bookmarks(root, ns, {bookmark_name}, paragraph=para, hashed=True) _insert_bookmark_around(label_run, bookmark_name, next_bookmark_id, ns) Loading