Loading generateBaseline/pandocFilter.py +14 Changes for generateBaseline/pandocFilter.py: 14 added lines, 0 removed lines. Original line number Diff line number Diff line Loading @@ -97,6 +97,10 @@ def writeMDFile(progress:Progress, mdLines:list[str], document:str, outDirectory _inCodeBlock = False def resetCodeBlockState() -> None: global _inCodeBlock _inCodeBlock = False def checkInCodeBlock(line:str) -> bool: global _inCodeBlock Loading Loading @@ -248,6 +252,7 @@ def replaceTableCaptions(progress:Progress, mdLines:list[str]) -> list[str]: """ Replace table captions with a pandoc table caption. """ _taskID = progress.add_task('[blue]Replacing table captions', total=0) resetCodeBlockState() # progress.update() tableregex = re.compile('^\*\*(Table .*)\*\*') Loading Loading @@ -279,6 +284,7 @@ def replaceFigureCaptions(progress:Progress, mdLines:list[str]) -> list[str]: """ Replace figure captions with a pandoc figure caption. """ _taskID = progress.add_task('[blue]Replacing figure captions', total=0) resetCodeBlockState() # progress.update() figureregex = re.compile('^\*\*(Figure .*)\*\*') nocaptionfigureregex = re.compile('!\[~~CAPTION~~\].*') Loading @@ -291,12 +297,14 @@ def replaceFigureCaptions(progress:Progress, mdLines:list[str]) -> list[str]: _lines.append(line) continue if matches: print(f'Replacing figure caption found: {matches[0]}') # Replace the previous figure markdown name with the captions. # Skip blank lines, then attach only if that line is an image. _idx = len(_lines) - 1 while _idx >= 0 and _lines[_idx].strip() == '': _idx -= 1 if _idx >= 0 and _lines[_idx].count('![') > 0: print(f'Replacing figure caption: {matches[0]} in line: {_lines[_idx]}') _lines[_idx] = re.sub(r'!.*]', f'![{matches[0]}]', _lines[_idx]) else: _lines.append(line) Loading @@ -313,6 +321,7 @@ def replaceFigureCaptions(progress:Progress, mdLines:list[str]) -> list[str]: def addFigureDimensions(progress: Progress, mdLines: list[str], document: str) -> list[str]: """Add a pandoc width or height attribute; default to natural width when within limits.""" _taskID = progress.add_task('[blue]Adding figure dimensions', total=0) resetCodeBlockState() _lines: list[str] = [] for line in mdLines: Loading Loading @@ -368,6 +377,7 @@ def replaceFiguresPathSvgToPng(progress: Progress, mdLines: list[str]) -> list[s """ Replace figure extensions from svg to png. """ _taskID = progress.add_task('[blue]Replacing figure captions', total=0) resetCodeBlockState() # progress.update() figurePathRegex = re.compile('media\/.*\.svg') Loading Loading @@ -413,6 +423,7 @@ def correctTableSeparators(progress: Progress, mdLines: list[str]) -> list[str]: And that is not always wanted """ _taskID = progress.add_task('[blue]Correcting table separators', total=0) resetCodeBlockState() tableSeparatorRegex = re.compile('^(\s*)(\|[-\|]*\|)\s*$') _lines: list[str] = [] Loading @@ -435,6 +446,7 @@ def instertLineBeforeStartOfList(progress:Progress, mdLines:list[str]) -> list[s """ Insert a line before the start of a list. """ _taskID = progress.add_task('[blue]Inserting line before start of list', total=0) resetCodeBlockState() # progress.update() # A line starts with a dash, asterisk, plus or number followed by a space for a list item. There might be several spaces for sublists. listregex = re.compile('^(\s*)(-|\*|\+|\d+\.)\s+.*') Loading Loading @@ -593,6 +605,7 @@ def replaceBulletedLettersLists(progress:Progress, mdLines:list[str]) -> list[st """ Replace bulleted letters lists with numbered lists. """ _taskID = progress.add_task('[blue]Replacing bulleted letters lists', total=0) resetCodeBlockState() # progress.update() # Match "- " only when followed by a letter, ")" or ".", and a space Loading Loading @@ -638,6 +651,7 @@ def convertHtmlTablesTogridTables(progress:Progress, mdLines:list[str]) -> list[ """ Convert HTML tables to grid tables. """ _taskID = progress.add_task('[blue]Converting HTML tables to grid tables', total=0) resetCodeBlockState() # progress.update() inTable = False Loading generateBaseline/postprocessing.py +156 −58 Changes for generateBaseline/postprocessing.py: 156 added lines, 58 removed lines. Original line number Diff line number Diff line Loading @@ -846,6 +846,8 @@ def update_figure_captions(docx_input, docx_output): after_toc = _content_after_toc(root, ns) new_style = "TF" counter = 0 bookmark_ids = root.xpath('.//w:bookmarkStart/@w:id | .//w:bookmarkEnd/@w:id', namespaces=ns) next_bookmark_id = max((int(i) for i in bookmark_ids if str(i).isdigit()), default=0) + 1 # Loop over all elements to find "ImageCaption" and change to "TF" for elem in root.xpath('.//w:pStyle[@w:val="ImageCaption"]', namespaces=ns): Loading @@ -855,6 +857,23 @@ def update_figure_captions(docx_input, docx_output): elem.set(f"{{{ns['w']}}}val", new_style) counter += 1 # If no bookmarkStart in the same paragraph, add one right after figure caption text pPr = elem.getparent() if pPr is not None: para = pPr.getparent() if para is not None: figure_name = para.xpath('./w:r/w:t', namespaces=ns) if figure_name: figure_name = figure_name[0].text bookmarkStart = etree.Element(f"{{{ns['w']}}}bookmarkStart") bookmarkStart.set(f"{{{ns['w']}}}name", f"{figure_name.split(':')[0].strip().replace(' ', '_').lower()}") bookmarkStart.set(f"{{{ns['w']}}}id", f"{next_bookmark_id}") bookmarkEnd = etree.Element(f"{{{ns['w']}}}bookmarkEnd") bookmarkEnd.set(f"{{{ns['w']}}}id", f"{next_bookmark_id}") para.append(bookmarkStart) para.append(bookmarkEnd) # The bookmarkEnd is needed to close the bookmarkStart next_bookmark_id += 1 print(f'Changed style "ImageCaption" to "TF" {counter} times') xml_data = etree.tostring(root, xml_declaration=True, encoding="UTF-8", standalone="yes") Loading Loading @@ -1006,6 +1025,31 @@ def update_heading_styles(docx_input, docx_output): # Add the new run to the paragraph para.append(new_run) def _rename_clause_bookmark(para, number, title): # Pandoc's own heading bookmark (for example "imports-other-md-files") stays # as it is. The span id "10-imports-other-md-files" starts with a number, so # Pandoc stores that bookmark as X plus a SHA1 hash. Rename the hash to the # span id, and point hyperlinks that used the hash at the same name. # "10.1" + "Imports other md files" becomes "101-imports-other-md-files". title_slug = re.sub(r'\s+', '-', title.strip()).lower() bookmark_name = f"{number.replace('.', '')}-{title_slug}" hashed_name = re.compile(r'^X[0-9a-fA-F]+$') # Direct children of this heading. The hash bookmark sits here, beside # the run. The bookmark Pandoc places before the paragraph is not touched. old_names = [] for start in para.xpath('./w:bookmarkStart', namespaces=ns): old_name = start.get(f"{{{ns['w']}}}name") if not old_name or not hashed_name.fullmatch(old_name): continue start.set(f"{{{ns['w']}}}name", bookmark_name) if old_name not in old_names: old_names.append(old_name) for old_name in old_names: for hyperlink in root.xpath('.//w:hyperlink', namespaces=ns): if hyperlink.get(f"{{{ns['w']}}}anchor") == old_name: hyperlink.set(f"{{{ns['w']}}}anchor", bookmark_name) print(f"Updating bookmarkStart for clause {number} from {old_name} to {bookmark_name}") # Read XML with zipfile.ZipFile(docx_input, 'r') as zin: xml_data = zin.read("word/document.xml") Loading Loading @@ -1044,6 +1088,9 @@ def update_heading_styles(docx_input, docx_output): # Create new run with number + tab + rest create_new_run(para, number, rest_text, "tab") counter += 1 # Rename the hashed span bookmark inside this heading. Pandoc's own # heading bookmark is left unchanged. _rename_clause_bookmark(para, number, rest_text) # Insert page break before "Scope" Heading1 and "History" Heading1 if re.match(r'^1\s+Scope\s*', full_text): insert_page_break_before_heading(para, full_text) Loading @@ -1066,6 +1113,7 @@ def update_heading_styles(docx_input, docx_output): pStyle_elems[0].set(f"{{{ns['w']}}}val", "Heading8")# Heading8 for certain specs. editHelp is going to harmonise that else: pStyle_elems[0].set(f"{{{ns['w']}}}val", "Heading9")# Heading9 for certain specs. editHelp is going to harmonise that _rename_clause_bookmark(para, annex_letter, annex_title) insert_page_break_before_heading(para, full_text) counter_annex += 1 # Annex subheading Heading 2: "A.1 Title", not matching "A.1.1 Title" Loading @@ -1084,6 +1132,9 @@ def update_heading_styles(docx_input, docx_output): if pStyle_elems: pStyle_elems[0].set(f"{{{ns['w']}}}val", "Heading1")# Heading9 for certain specs. editHelp is going to harmonise that counter_annex += 1 _rename_clause_bookmark(para, annex_letter, annex_title) # Annex subheading Heading 3+: "A.1.1 Title", "A.1.1.1 Title" elif (match := re.match(r'^\s*([A-Z]\.\d+(?:\.\d+)+)\s+(.+)$', full_text)) is not None: annex_letter = match.group(1) Loading @@ -1103,6 +1154,9 @@ def update_heading_styles(docx_input, docx_output): # Create new run with number + break + rest create_new_run(para, annex_letter, annex_title, "tab") counter_annex += 1 _rename_clause_bookmark(para, annex_letter, annex_title) elif re.match(r'^\s*History\s*', full_text): insert_page_break_before_heading(para, full_text) elif full_text.strip().lower() == "essential patents" or full_text.strip().lower() == "trademarks": Loading Loading @@ -2006,6 +2060,9 @@ def update_table_captions(docx_input, docx_output): new_style = "TH" counter = 0 bookmark_ids = root.xpath('.//w:bookmarkStart/@w:id | .//w:bookmarkEnd/@w:id', namespaces=ns) next_bookmark_id = max((int(i) for i in bookmark_ids if str(i).isdigit()), default=0) + 1 # Loop over all elements to find "TableCaption" and change to "TH" for elem in root.xpath('.//w:pStyle[@w:val="TableCaption"]', namespaces=ns): if not after_toc(elem): Loading @@ -2016,6 +2073,24 @@ def update_table_captions(docx_input, docx_output): #pPr = elem.getparent() #if pPr is not None and not pPr.xpath('./w:keepNext', namespaces=ns): # pPr.append(etree.Element(f"{{{ns['w']}}}keepNext")) # If no bookmarkStart in the same paragraph, add one right after table caption text pPr = elem.getparent() if pPr is not None: para = pPr.getparent() if para is not None: table_name = para.xpath('./w:t', namespaces=ns) if table_name: table_name = table_name[0].text bookmarkStart = etree.Element(f"{{{ns['w']}}}bookmarkStart") bookmarkStart.set(f"{{{ns['w']}}}name", f"{table_name.split(':')[0].strip().replace(' ', '_').lower()}") bookmarkStart.set(f"{{{ns['w']}}}id", f"{next_bookmark_id}") bookmarkEnd = etree.Element(f"{{{ns['w']}}}bookmarkEnd") bookmarkEnd.set(f"{{{ns['w']}}}id", f"{next_bookmark_id}") para.append(bookmarkStart) para.append(bookmarkEnd) # The bookmarkEnd is needed to close the bookmarkStart next_bookmark_id += 1 counter += 1 print(f'Changed style "TableCaption" to "TH" {counter} times') Loading Loading @@ -3160,11 +3235,13 @@ def add_no_break_hyphens(docx_input, docx_output): def update_references_style(docx_input, docx_output): """ Updates references style from 'Hyperlink' to 'Normal' in a DOCX file. Updates citation hyperlinks in a DOCX file. Internal citations such as [1] and [i.1] become Normal and, when a REF_ bookmark exists, a REF field. Every other hyperlink also becomes Normal, except hyperlinks in clause 2 (the References clause), which stay Hyperlink. bookmark exists, a REF field. Clause, figure and table citations ("Clause X.Y.Z", "Figure X.Y-Z", "Table X.Y-Z") also become Normal REF fields. Every other hyperlink stays a hyperlink. Hyperlinks in clause 2 (the References clause) stay Hyperlink, except the [1] / [i.1] citations. Parameters ---------- Loading @@ -3183,8 +3260,8 @@ def update_references_style(docx_input, docx_output): after_toc = _content_after_toc(root, ns) new_style = "Normal" counter = 0 other_counter = 0 field_counter = 0 citation_counter = 0 # Clause 2 runs from the Heading1 "2 References" (or "References") through # the paragraph before the next Heading1. Heading numbers are already split Loading Loading @@ -3216,6 +3293,12 @@ def update_references_style(docx_input, docx_output): # Pattern to match internal references: [i.1] or [1] or [i.12] or [12] reference_pattern = re.compile(r'^\[(i\.)?\d+\]$', re.IGNORECASE) # Clause 6.2.3, Figure 6-1 or Figure 6.2-1, Table 7.1-1. clause_pattern = re.compile(r'^clauses?\s+(\d+(?:\.\d+)*)$', re.IGNORECASE) figure_pattern = re.compile(r'^figures?\s+\d+(?:\.\d+)*-\d+$', re.IGNORECASE) table_pattern = re.compile(r'^tables?\s+\d+(?:\.\d+)*-\d+$', re.IGNORECASE) figure_anchor_pattern = re.compile(r'^figure_\d+(?:\.\d+)*-\d+$', re.IGNORECASE) table_anchor_pattern = re.compile(r'^table_\d+(?:\.\d+)*-\d+$', re.IGNORECASE) # Old declaration bookmark name -> REF_ bookmark added by update_references. # The old bookmarks stay in the document. Loading Loading @@ -3244,64 +3327,84 @@ def update_references_style(docx_input, docx_output): run.append(fld) return run # Loop over all elements to find "Hyperlink" and change to "Normal" # [1] / [i.1], and Clause / Figure / Table citations, become Normal REF # fields. Any other hyperlink is left unchanged. pending_fields = [] for elem in root.xpath('.//w:rStyle[@w:val="Hyperlink"]', namespaces=ns): if not after_toc(elem): continue # Internal citations [1] / [i.1] become Normal. Other hyperlinks become # Normal too, except those inside clause 2. rPr = elem.getparent() if rPr is None: continue r = rPr.getparent() if r is None: continue hyperlink = r.getparent() if hyperlink is None: continue if hyperlink.tag != f"{{{ns['w']}}}hyperlink": continue t = r.xpath(".//w:t", namespaces=ns) if not t: for hyperlink in root.xpath('.//w:hyperlink', namespaces=ns): if not after_toc(hyperlink): continue raw_text = "".join((text_elem.text or "") for text_elem in t) full_text = raw_text.strip() if not reference_pattern.match(full_text): if _in_clause_2(elem): anchor = hyperlink.get(f"{{{ns['w']}}}anchor") text_nodes = hyperlink.xpath('.//w:t', namespaces=ns) if not text_nodes: continue raw_text = "".join((text_elem.text or "") for text_elem in text_nodes) full_text = raw_text.replace('\u00A0', ' ').strip() rPr_list = hyperlink.xpath('./w:r/w:rPr', namespaces=ns) rPr = rPr_list[0] if rPr_list else None clause_match = clause_pattern.match(full_text) is_reference = reference_pattern.match(full_text) is not None is_figure = bool( figure_pattern.match(full_text) and anchor and figure_anchor_pattern.match(anchor) ) is_table = bool( table_pattern.match(full_text) and anchor and table_anchor_pattern.match(anchor) ) is_clause = bool( clause_match and anchor and anchor.startswith(clause_match.group(1).replace('.', '') + '-') ) if not is_reference and _in_clause_2(hyperlink): continue elem.set(f"{{{ns['w']}}}val", new_style) other_counter += 1 if not (is_reference or is_figure or is_table or is_clause): continue elem.set(f"{{{ns['w']}}}val", new_style) if is_reference: counter += 1 anchor = hyperlink.get(f"{{{ns['w']}}}anchor") ref_name = anchor_to_ref.get(anchor) if ref_name: pending_fields.append((hyperlink, rPr, raw_text, ref_name)) if ref_name and rPr is not None: inner = full_text[1:-1] if full_text.startswith('[') and full_text.endswith(']') else full_text pending_fields.append((hyperlink, rPr, inner, ref_name, True)) continue result_text = full_text.replace(' ', '\u00A0') pending_fields.append((hyperlink, rPr, result_text, anchor, False)) for hyperlink, rPr, raw_text, ref_name in pending_fields: for hyperlink, rPr, result_text, ref_name, bracketed in pending_fields: parent = hyperlink.getparent() if parent is None: continue index = list(parent).index(hyperlink) # The REF_ bookmark is the number, or "i." plus the number. Keep the # square brackets outside the field so shading and field update cover # only that bookmark text. result_text = raw_text.strip() if result_text.startswith('[') and result_text.endswith(']'): result_text = result_text[1:-1] def _text_run(text): run = OxmlElement('w:r') run.append(etree.fromstring(etree.tostring(rPr))) copied_rPr = etree.fromstring(etree.tostring(rPr)) for style in copied_rPr.findall(qn('w:rStyle')): style.set(qn('w:val'), new_style) run.append(copied_rPr) text_elem = OxmlElement('w:t') text_elem.text = text run.append(text_elem) return run def _normal_result(text): run = OxmlElement('w:r') result_rPr = OxmlElement('w:rPr') result_style = OxmlElement('w:rStyle') result_style.set(qn('w:val'), 'Normal') result_rPr.append(result_style) run.append(result_rPr) text_elem = OxmlElement('w:t') if '\u00A0' in text: text_elem.set('{http://www.w3.org/XML/1998/namespace}space', 'preserve') text_elem.text = text run.append(text_elem) return run begin_run = _fld_run('begin') instr_run = OxmlElement('w:r') instr = OxmlElement('w:instrText') Loading @@ -3309,24 +3412,19 @@ def update_references_style(docx_input, docx_output): instr.text = f' REF {ref_name} \\h \\* MERGEFORMAT ' instr_run.append(instr) separate_run = _fld_run('separate') #result_hyperlink = OxmlElement('w:hyperlink') #result_hyperlink.set(qn('w:anchor'), ref_name) #result_hyperlink.set(qn('w:history'), '1') #result_hyperlink.append(_text_run(result_text))result_run = OxmlElement('w:r') result_run = OxmlElement('w:r') result_rPr = OxmlElement('w:rPr') result_style = OxmlElement('w:rStyle') result_style.set(qn('w:val'), 'Normal') result_rPr.append(result_style) result_text_elem = OxmlElement('w:t') result_text_elem.text = result_text result_run.append(result_rPr) result_run.append(result_text_elem) result_run = _normal_result(result_text) end_run = _fld_run('end') # Reference bookmarks cover the number only, so the brackets stay # outside the field. Clause, figure and table citations are the whole result. parts = [begin_run, instr_run, separate_run, result_run, end_run] if bracketed: parts = [_text_run('[')] + parts + [_text_run(']')] parent.remove(hyperlink) for offset, elem in enumerate((_text_run('['), begin_run, instr_run, separate_run, result_run, end_run, _text_run(']'))): for offset, elem in enumerate(parts): parent.insert(index + offset, elem) field_counter += 1 if not bracketed: citation_counter += 1 # Keep hyperlink text such as "clause 6.2.3" on one line. nbsp = '\u00A0' Loading @@ -3345,9 +3443,9 @@ def update_references_style(docx_input, docx_output): nbsp_counter += 1 print(f'Changed style "Hyperlink" to "Normal" {counter} times for internal references') print(f'Changed style "Hyperlink" to "Normal" {other_counter} times for other references outside clause 2') print(f'Replaced reference hyperlinks with REF fields {field_counter - citation_counter} times') print(f'Replaced clause, figure and table citations with REF fields {citation_counter} times') print(f'Replaced spaces with non-breaking spaces in {nbsp_counter} hyperlinks outside clause 2') print(f'Replaced reference hyperlinks with REF fields {field_counter} times') xml_data = etree.tostring(root, xml_declaration=True, encoding="UTF-8", standalone="yes") Loading Loading
generateBaseline/pandocFilter.py +14 Changes for generateBaseline/pandocFilter.py: 14 added lines, 0 removed lines. Original line number Diff line number Diff line Loading @@ -97,6 +97,10 @@ def writeMDFile(progress:Progress, mdLines:list[str], document:str, outDirectory _inCodeBlock = False def resetCodeBlockState() -> None: global _inCodeBlock _inCodeBlock = False def checkInCodeBlock(line:str) -> bool: global _inCodeBlock Loading Loading @@ -248,6 +252,7 @@ def replaceTableCaptions(progress:Progress, mdLines:list[str]) -> list[str]: """ Replace table captions with a pandoc table caption. """ _taskID = progress.add_task('[blue]Replacing table captions', total=0) resetCodeBlockState() # progress.update() tableregex = re.compile('^\*\*(Table .*)\*\*') Loading Loading @@ -279,6 +284,7 @@ def replaceFigureCaptions(progress:Progress, mdLines:list[str]) -> list[str]: """ Replace figure captions with a pandoc figure caption. """ _taskID = progress.add_task('[blue]Replacing figure captions', total=0) resetCodeBlockState() # progress.update() figureregex = re.compile('^\*\*(Figure .*)\*\*') nocaptionfigureregex = re.compile('!\[~~CAPTION~~\].*') Loading @@ -291,12 +297,14 @@ def replaceFigureCaptions(progress:Progress, mdLines:list[str]) -> list[str]: _lines.append(line) continue if matches: print(f'Replacing figure caption found: {matches[0]}') # Replace the previous figure markdown name with the captions. # Skip blank lines, then attach only if that line is an image. _idx = len(_lines) - 1 while _idx >= 0 and _lines[_idx].strip() == '': _idx -= 1 if _idx >= 0 and _lines[_idx].count('![') > 0: print(f'Replacing figure caption: {matches[0]} in line: {_lines[_idx]}') _lines[_idx] = re.sub(r'!.*]', f'![{matches[0]}]', _lines[_idx]) else: _lines.append(line) Loading @@ -313,6 +321,7 @@ def replaceFigureCaptions(progress:Progress, mdLines:list[str]) -> list[str]: def addFigureDimensions(progress: Progress, mdLines: list[str], document: str) -> list[str]: """Add a pandoc width or height attribute; default to natural width when within limits.""" _taskID = progress.add_task('[blue]Adding figure dimensions', total=0) resetCodeBlockState() _lines: list[str] = [] for line in mdLines: Loading Loading @@ -368,6 +377,7 @@ def replaceFiguresPathSvgToPng(progress: Progress, mdLines: list[str]) -> list[s """ Replace figure extensions from svg to png. """ _taskID = progress.add_task('[blue]Replacing figure captions', total=0) resetCodeBlockState() # progress.update() figurePathRegex = re.compile('media\/.*\.svg') Loading Loading @@ -413,6 +423,7 @@ def correctTableSeparators(progress: Progress, mdLines: list[str]) -> list[str]: And that is not always wanted """ _taskID = progress.add_task('[blue]Correcting table separators', total=0) resetCodeBlockState() tableSeparatorRegex = re.compile('^(\s*)(\|[-\|]*\|)\s*$') _lines: list[str] = [] Loading @@ -435,6 +446,7 @@ def instertLineBeforeStartOfList(progress:Progress, mdLines:list[str]) -> list[s """ Insert a line before the start of a list. """ _taskID = progress.add_task('[blue]Inserting line before start of list', total=0) resetCodeBlockState() # progress.update() # A line starts with a dash, asterisk, plus or number followed by a space for a list item. There might be several spaces for sublists. listregex = re.compile('^(\s*)(-|\*|\+|\d+\.)\s+.*') Loading Loading @@ -593,6 +605,7 @@ def replaceBulletedLettersLists(progress:Progress, mdLines:list[str]) -> list[st """ Replace bulleted letters lists with numbered lists. """ _taskID = progress.add_task('[blue]Replacing bulleted letters lists', total=0) resetCodeBlockState() # progress.update() # Match "- " only when followed by a letter, ")" or ".", and a space Loading Loading @@ -638,6 +651,7 @@ def convertHtmlTablesTogridTables(progress:Progress, mdLines:list[str]) -> list[ """ Convert HTML tables to grid tables. """ _taskID = progress.add_task('[blue]Converting HTML tables to grid tables', total=0) resetCodeBlockState() # progress.update() inTable = False Loading
generateBaseline/postprocessing.py +156 −58 Changes for generateBaseline/postprocessing.py: 156 added lines, 58 removed lines. Original line number Diff line number Diff line Loading @@ -846,6 +846,8 @@ def update_figure_captions(docx_input, docx_output): after_toc = _content_after_toc(root, ns) new_style = "TF" counter = 0 bookmark_ids = root.xpath('.//w:bookmarkStart/@w:id | .//w:bookmarkEnd/@w:id', namespaces=ns) next_bookmark_id = max((int(i) for i in bookmark_ids if str(i).isdigit()), default=0) + 1 # Loop over all elements to find "ImageCaption" and change to "TF" for elem in root.xpath('.//w:pStyle[@w:val="ImageCaption"]', namespaces=ns): Loading @@ -855,6 +857,23 @@ def update_figure_captions(docx_input, docx_output): elem.set(f"{{{ns['w']}}}val", new_style) counter += 1 # If no bookmarkStart in the same paragraph, add one right after figure caption text pPr = elem.getparent() if pPr is not None: para = pPr.getparent() if para is not None: figure_name = para.xpath('./w:r/w:t', namespaces=ns) if figure_name: figure_name = figure_name[0].text bookmarkStart = etree.Element(f"{{{ns['w']}}}bookmarkStart") bookmarkStart.set(f"{{{ns['w']}}}name", f"{figure_name.split(':')[0].strip().replace(' ', '_').lower()}") bookmarkStart.set(f"{{{ns['w']}}}id", f"{next_bookmark_id}") bookmarkEnd = etree.Element(f"{{{ns['w']}}}bookmarkEnd") bookmarkEnd.set(f"{{{ns['w']}}}id", f"{next_bookmark_id}") para.append(bookmarkStart) para.append(bookmarkEnd) # The bookmarkEnd is needed to close the bookmarkStart next_bookmark_id += 1 print(f'Changed style "ImageCaption" to "TF" {counter} times') xml_data = etree.tostring(root, xml_declaration=True, encoding="UTF-8", standalone="yes") Loading Loading @@ -1006,6 +1025,31 @@ def update_heading_styles(docx_input, docx_output): # Add the new run to the paragraph para.append(new_run) def _rename_clause_bookmark(para, number, title): # Pandoc's own heading bookmark (for example "imports-other-md-files") stays # as it is. The span id "10-imports-other-md-files" starts with a number, so # Pandoc stores that bookmark as X plus a SHA1 hash. Rename the hash to the # span id, and point hyperlinks that used the hash at the same name. # "10.1" + "Imports other md files" becomes "101-imports-other-md-files". title_slug = re.sub(r'\s+', '-', title.strip()).lower() bookmark_name = f"{number.replace('.', '')}-{title_slug}" hashed_name = re.compile(r'^X[0-9a-fA-F]+$') # Direct children of this heading. The hash bookmark sits here, beside # the run. The bookmark Pandoc places before the paragraph is not touched. old_names = [] for start in para.xpath('./w:bookmarkStart', namespaces=ns): old_name = start.get(f"{{{ns['w']}}}name") if not old_name or not hashed_name.fullmatch(old_name): continue start.set(f"{{{ns['w']}}}name", bookmark_name) if old_name not in old_names: old_names.append(old_name) for old_name in old_names: for hyperlink in root.xpath('.//w:hyperlink', namespaces=ns): if hyperlink.get(f"{{{ns['w']}}}anchor") == old_name: hyperlink.set(f"{{{ns['w']}}}anchor", bookmark_name) print(f"Updating bookmarkStart for clause {number} from {old_name} to {bookmark_name}") # Read XML with zipfile.ZipFile(docx_input, 'r') as zin: xml_data = zin.read("word/document.xml") Loading Loading @@ -1044,6 +1088,9 @@ def update_heading_styles(docx_input, docx_output): # Create new run with number + tab + rest create_new_run(para, number, rest_text, "tab") counter += 1 # Rename the hashed span bookmark inside this heading. Pandoc's own # heading bookmark is left unchanged. _rename_clause_bookmark(para, number, rest_text) # Insert page break before "Scope" Heading1 and "History" Heading1 if re.match(r'^1\s+Scope\s*', full_text): insert_page_break_before_heading(para, full_text) Loading @@ -1066,6 +1113,7 @@ def update_heading_styles(docx_input, docx_output): pStyle_elems[0].set(f"{{{ns['w']}}}val", "Heading8")# Heading8 for certain specs. editHelp is going to harmonise that else: pStyle_elems[0].set(f"{{{ns['w']}}}val", "Heading9")# Heading9 for certain specs. editHelp is going to harmonise that _rename_clause_bookmark(para, annex_letter, annex_title) insert_page_break_before_heading(para, full_text) counter_annex += 1 # Annex subheading Heading 2: "A.1 Title", not matching "A.1.1 Title" Loading @@ -1084,6 +1132,9 @@ def update_heading_styles(docx_input, docx_output): if pStyle_elems: pStyle_elems[0].set(f"{{{ns['w']}}}val", "Heading1")# Heading9 for certain specs. editHelp is going to harmonise that counter_annex += 1 _rename_clause_bookmark(para, annex_letter, annex_title) # Annex subheading Heading 3+: "A.1.1 Title", "A.1.1.1 Title" elif (match := re.match(r'^\s*([A-Z]\.\d+(?:\.\d+)+)\s+(.+)$', full_text)) is not None: annex_letter = match.group(1) Loading @@ -1103,6 +1154,9 @@ def update_heading_styles(docx_input, docx_output): # Create new run with number + break + rest create_new_run(para, annex_letter, annex_title, "tab") counter_annex += 1 _rename_clause_bookmark(para, annex_letter, annex_title) elif re.match(r'^\s*History\s*', full_text): insert_page_break_before_heading(para, full_text) elif full_text.strip().lower() == "essential patents" or full_text.strip().lower() == "trademarks": Loading Loading @@ -2006,6 +2060,9 @@ def update_table_captions(docx_input, docx_output): new_style = "TH" counter = 0 bookmark_ids = root.xpath('.//w:bookmarkStart/@w:id | .//w:bookmarkEnd/@w:id', namespaces=ns) next_bookmark_id = max((int(i) for i in bookmark_ids if str(i).isdigit()), default=0) + 1 # Loop over all elements to find "TableCaption" and change to "TH" for elem in root.xpath('.//w:pStyle[@w:val="TableCaption"]', namespaces=ns): if not after_toc(elem): Loading @@ -2016,6 +2073,24 @@ def update_table_captions(docx_input, docx_output): #pPr = elem.getparent() #if pPr is not None and not pPr.xpath('./w:keepNext', namespaces=ns): # pPr.append(etree.Element(f"{{{ns['w']}}}keepNext")) # If no bookmarkStart in the same paragraph, add one right after table caption text pPr = elem.getparent() if pPr is not None: para = pPr.getparent() if para is not None: table_name = para.xpath('./w:t', namespaces=ns) if table_name: table_name = table_name[0].text bookmarkStart = etree.Element(f"{{{ns['w']}}}bookmarkStart") bookmarkStart.set(f"{{{ns['w']}}}name", f"{table_name.split(':')[0].strip().replace(' ', '_').lower()}") bookmarkStart.set(f"{{{ns['w']}}}id", f"{next_bookmark_id}") bookmarkEnd = etree.Element(f"{{{ns['w']}}}bookmarkEnd") bookmarkEnd.set(f"{{{ns['w']}}}id", f"{next_bookmark_id}") para.append(bookmarkStart) para.append(bookmarkEnd) # The bookmarkEnd is needed to close the bookmarkStart next_bookmark_id += 1 counter += 1 print(f'Changed style "TableCaption" to "TH" {counter} times') Loading Loading @@ -3160,11 +3235,13 @@ def add_no_break_hyphens(docx_input, docx_output): def update_references_style(docx_input, docx_output): """ Updates references style from 'Hyperlink' to 'Normal' in a DOCX file. Updates citation hyperlinks in a DOCX file. Internal citations such as [1] and [i.1] become Normal and, when a REF_ bookmark exists, a REF field. Every other hyperlink also becomes Normal, except hyperlinks in clause 2 (the References clause), which stay Hyperlink. bookmark exists, a REF field. Clause, figure and table citations ("Clause X.Y.Z", "Figure X.Y-Z", "Table X.Y-Z") also become Normal REF fields. Every other hyperlink stays a hyperlink. Hyperlinks in clause 2 (the References clause) stay Hyperlink, except the [1] / [i.1] citations. Parameters ---------- Loading @@ -3183,8 +3260,8 @@ def update_references_style(docx_input, docx_output): after_toc = _content_after_toc(root, ns) new_style = "Normal" counter = 0 other_counter = 0 field_counter = 0 citation_counter = 0 # Clause 2 runs from the Heading1 "2 References" (or "References") through # the paragraph before the next Heading1. Heading numbers are already split Loading Loading @@ -3216,6 +3293,12 @@ def update_references_style(docx_input, docx_output): # Pattern to match internal references: [i.1] or [1] or [i.12] or [12] reference_pattern = re.compile(r'^\[(i\.)?\d+\]$', re.IGNORECASE) # Clause 6.2.3, Figure 6-1 or Figure 6.2-1, Table 7.1-1. clause_pattern = re.compile(r'^clauses?\s+(\d+(?:\.\d+)*)$', re.IGNORECASE) figure_pattern = re.compile(r'^figures?\s+\d+(?:\.\d+)*-\d+$', re.IGNORECASE) table_pattern = re.compile(r'^tables?\s+\d+(?:\.\d+)*-\d+$', re.IGNORECASE) figure_anchor_pattern = re.compile(r'^figure_\d+(?:\.\d+)*-\d+$', re.IGNORECASE) table_anchor_pattern = re.compile(r'^table_\d+(?:\.\d+)*-\d+$', re.IGNORECASE) # Old declaration bookmark name -> REF_ bookmark added by update_references. # The old bookmarks stay in the document. Loading Loading @@ -3244,64 +3327,84 @@ def update_references_style(docx_input, docx_output): run.append(fld) return run # Loop over all elements to find "Hyperlink" and change to "Normal" # [1] / [i.1], and Clause / Figure / Table citations, become Normal REF # fields. Any other hyperlink is left unchanged. pending_fields = [] for elem in root.xpath('.//w:rStyle[@w:val="Hyperlink"]', namespaces=ns): if not after_toc(elem): continue # Internal citations [1] / [i.1] become Normal. Other hyperlinks become # Normal too, except those inside clause 2. rPr = elem.getparent() if rPr is None: continue r = rPr.getparent() if r is None: continue hyperlink = r.getparent() if hyperlink is None: continue if hyperlink.tag != f"{{{ns['w']}}}hyperlink": continue t = r.xpath(".//w:t", namespaces=ns) if not t: for hyperlink in root.xpath('.//w:hyperlink', namespaces=ns): if not after_toc(hyperlink): continue raw_text = "".join((text_elem.text or "") for text_elem in t) full_text = raw_text.strip() if not reference_pattern.match(full_text): if _in_clause_2(elem): anchor = hyperlink.get(f"{{{ns['w']}}}anchor") text_nodes = hyperlink.xpath('.//w:t', namespaces=ns) if not text_nodes: continue raw_text = "".join((text_elem.text or "") for text_elem in text_nodes) full_text = raw_text.replace('\u00A0', ' ').strip() rPr_list = hyperlink.xpath('./w:r/w:rPr', namespaces=ns) rPr = rPr_list[0] if rPr_list else None clause_match = clause_pattern.match(full_text) is_reference = reference_pattern.match(full_text) is not None is_figure = bool( figure_pattern.match(full_text) and anchor and figure_anchor_pattern.match(anchor) ) is_table = bool( table_pattern.match(full_text) and anchor and table_anchor_pattern.match(anchor) ) is_clause = bool( clause_match and anchor and anchor.startswith(clause_match.group(1).replace('.', '') + '-') ) if not is_reference and _in_clause_2(hyperlink): continue elem.set(f"{{{ns['w']}}}val", new_style) other_counter += 1 if not (is_reference or is_figure or is_table or is_clause): continue elem.set(f"{{{ns['w']}}}val", new_style) if is_reference: counter += 1 anchor = hyperlink.get(f"{{{ns['w']}}}anchor") ref_name = anchor_to_ref.get(anchor) if ref_name: pending_fields.append((hyperlink, rPr, raw_text, ref_name)) if ref_name and rPr is not None: inner = full_text[1:-1] if full_text.startswith('[') and full_text.endswith(']') else full_text pending_fields.append((hyperlink, rPr, inner, ref_name, True)) continue result_text = full_text.replace(' ', '\u00A0') pending_fields.append((hyperlink, rPr, result_text, anchor, False)) for hyperlink, rPr, raw_text, ref_name in pending_fields: for hyperlink, rPr, result_text, ref_name, bracketed in pending_fields: parent = hyperlink.getparent() if parent is None: continue index = list(parent).index(hyperlink) # The REF_ bookmark is the number, or "i." plus the number. Keep the # square brackets outside the field so shading and field update cover # only that bookmark text. result_text = raw_text.strip() if result_text.startswith('[') and result_text.endswith(']'): result_text = result_text[1:-1] def _text_run(text): run = OxmlElement('w:r') run.append(etree.fromstring(etree.tostring(rPr))) copied_rPr = etree.fromstring(etree.tostring(rPr)) for style in copied_rPr.findall(qn('w:rStyle')): style.set(qn('w:val'), new_style) run.append(copied_rPr) text_elem = OxmlElement('w:t') text_elem.text = text run.append(text_elem) return run def _normal_result(text): run = OxmlElement('w:r') result_rPr = OxmlElement('w:rPr') result_style = OxmlElement('w:rStyle') result_style.set(qn('w:val'), 'Normal') result_rPr.append(result_style) run.append(result_rPr) text_elem = OxmlElement('w:t') if '\u00A0' in text: text_elem.set('{http://www.w3.org/XML/1998/namespace}space', 'preserve') text_elem.text = text run.append(text_elem) return run begin_run = _fld_run('begin') instr_run = OxmlElement('w:r') instr = OxmlElement('w:instrText') Loading @@ -3309,24 +3412,19 @@ def update_references_style(docx_input, docx_output): instr.text = f' REF {ref_name} \\h \\* MERGEFORMAT ' instr_run.append(instr) separate_run = _fld_run('separate') #result_hyperlink = OxmlElement('w:hyperlink') #result_hyperlink.set(qn('w:anchor'), ref_name) #result_hyperlink.set(qn('w:history'), '1') #result_hyperlink.append(_text_run(result_text))result_run = OxmlElement('w:r') result_run = OxmlElement('w:r') result_rPr = OxmlElement('w:rPr') result_style = OxmlElement('w:rStyle') result_style.set(qn('w:val'), 'Normal') result_rPr.append(result_style) result_text_elem = OxmlElement('w:t') result_text_elem.text = result_text result_run.append(result_rPr) result_run.append(result_text_elem) result_run = _normal_result(result_text) end_run = _fld_run('end') # Reference bookmarks cover the number only, so the brackets stay # outside the field. Clause, figure and table citations are the whole result. parts = [begin_run, instr_run, separate_run, result_run, end_run] if bracketed: parts = [_text_run('[')] + parts + [_text_run(']')] parent.remove(hyperlink) for offset, elem in enumerate((_text_run('['), begin_run, instr_run, separate_run, result_run, end_run, _text_run(']'))): for offset, elem in enumerate(parts): parent.insert(index + offset, elem) field_counter += 1 if not bracketed: citation_counter += 1 # Keep hyperlink text such as "clause 6.2.3" on one line. nbsp = '\u00A0' Loading @@ -3345,9 +3443,9 @@ def update_references_style(docx_input, docx_output): nbsp_counter += 1 print(f'Changed style "Hyperlink" to "Normal" {counter} times for internal references') print(f'Changed style "Hyperlink" to "Normal" {other_counter} times for other references outside clause 2') print(f'Replaced reference hyperlinks with REF fields {field_counter - citation_counter} times') print(f'Replaced clause, figure and table citations with REF fields {citation_counter} times') print(f'Replaced spaces with non-breaking spaces in {nbsp_counter} hyperlinks outside clause 2') print(f'Replaced reference hyperlinks with REF fields {field_counter} times') xml_data = etree.tostring(root, xml_declaration=True, encoding="UTF-8", standalone="yes") Loading