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

Some fixes:

- Annex X.1 becomes Heading 1, further ones follow this Heading numbering (X.1.1.1 -> Heading 3)
- References are formatted as normal (except those in Clause 2)
- Clean consecutive notes
- Keep table and its caption together in the same page
- keep references-like patterns in the same like (i.e. clause x.y.z, table x.y.z,...)
- Keep lines together in all normal paragraphs to avoid split of lines
parent fc1bc045
Loading
Loading
Loading
Loading
Loading
+201 −28
Changes for generateBaseline/postprocessing.py: 201 added lines, 28 removed lines.
Original line number Diff line number Diff line
@@ -34,6 +34,7 @@ DEFAULT_FORMAT_STYLE_UPDATES = {
    "add_no_break_hyphens": True,
    "update_references_style": True,
    "update_source_code_style": True,
    "add_non_breaking_spaces": True,
    "add_break_after_code_blocks_and_tables": True,
    "update_equation_style": True,
    "correct_quotes_docx": True,
@@ -968,30 +969,16 @@ def update_heading_styles(docx_input, docx_output):
    ns = {"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"}
    
    def insert_page_break_before_heading(para, heading_text):
        parent = para.getparent()
        if parent is None:
            return
        
        # Find the position of the "Scope" Heading1 paragraph
        insert_index = list(parent).index(para)

        # Special case: BookmarkStart directly before
        if insert_index > 0:
            prev_elem = parent[insert_index - 1]
            if prev_elem.tag.endswith('}bookmarkStart'):
                insert_index -= 1
        
        # Create a new paragraph with a page break
        page_break_para = OxmlElement('w:p')
        page_break_run = OxmlElement('w:r')
        page_break = OxmlElement('w:br')
        page_break.set(f"{{{ns['w']}}}type", "page")
        page_break_run.append(page_break)
        page_break_para.append(page_break_run)
        
        # Insert the page break paragraph before the "Scope" Heading1 paragraph
        parent.insert(insert_index, page_break_para)
        print(f'Inserted page break before Heading: {heading_text}')
        # w:pageBreakBefore starts the heading on a new page. Unlike a
        # w:br w:type="page" paragraph, it does not add a blank page when
        # the heading is already at the top of a page.
        pPr = para.find(f"{{{ns['w']}}}pPr")
        if pPr is None:
            pPr = OxmlElement('w:pPr')
            para.insert(0, pPr)
        if not pPr.xpath('./w:pageBreakBefore', namespaces=ns):
            pPr.append(OxmlElement('w:pageBreakBefore'))
        print(f'Page break before Heading: {heading_text}')

    def create_new_run(para, number, rest_text, tab_or_break = None):
        if tab_or_break is None:
@@ -1095,13 +1082,20 @@ def update_heading_styles(docx_input, docx_output):
            # Change style from Heading 2 to Heading 9
            pStyle_elems = para.xpath('./w:pPr/w:pStyle[@w:val="Heading2"]', namespaces=ns)
            if pStyle_elems:
                pStyle_elems[0].set(f"{{{ns['w']}}}val", "Heading2")# Heading9 for certain specs. editHelp is going to harmonise that    
                pStyle_elems[0].set(f"{{{ns['w']}}}val", "Heading1")# Heading9 for certain specs. editHelp is going to harmonise that    
            counter_annex += 1
        # 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)
            annex_title = match.group(2)
            
            # Change style from Heading 3 to Heading 2, Heading 4 to Heading 3, etc..
            for i in range(3, 10):
                pStyle_elems = para.xpath(f'./w:pPr/w:pStyle[@w:val="Heading{i}"]', namespaces=ns)
                if pStyle_elems:
                    pStyle_elems[0].set(f"{{{ns['w']}}}val", f"Heading{i-1}")# Heading9 for certain specs. editHelp is going to harmonise that    
                    counter_annex += 1

            # Clear all existing runs from the paragraph
            for run in runs:
                para.remove(run)
@@ -2018,6 +2012,10 @@ def update_table_captions(docx_input, docx_output):
            continue
        old_val = elem.get(f"{{{ns['w']}}}val")
        elem.set(f"{{{ns['w']}}}val", new_style)
        # keepNext is a child of pPr, which is the parent of this pStyle.
        #pPr = elem.getparent()
        #if pPr is not None and not pPr.xpath('./w:keepNext', namespaces=ns):
        #    pPr.append(etree.Element(f"{{{ns['w']}}}keepNext"))
        counter += 1
        
    print(f'Changed style "TableCaption" to "TH" {counter} times')
@@ -2133,7 +2131,18 @@ def update_table_rows(docx_input, docx_output):
                        #if table_caption_elem:
                        #    table_name = table_caption_elem[0].get(f"{{{ns['w']}}}val")
                        #print(f'Removed child {child.tag} from pPr of table {table_name}')
            
                # Add keepnext to all header elements to keep them together with the table caption
                # <w:keepNext w:val="0"/>
				# <w:keepLines w:val="0"/>
                keepnext_elem = etree.Element(f"{{{ns['w']}}}keepNext")
                keepnext_elem.set(f"{{{ns['w']}}}val", "0")
                pPr_elem.append(keepnext_elem)
                keeplines_elem = etree.Element(f"{{{ns['w']}}}keepLines")
                keeplines_elem.set(f"{{{ns['w']}}}val", "0")
                pPr_elem.append(keeplines_elem)
                widowcontrol_elem = etree.Element(f"{{{ns['w']}}}widowControl")
                widowcontrol_elem.set(f"{{{ns['w']}}}val", "0")
                pPr_elem.append(widowcontrol_elem)
            # Add w:b w:val="true" to each run to ensure bold is applied
            runs = para.xpath('./w:r', namespaces=ns)
            for run in runs:
@@ -2179,6 +2188,20 @@ def update_table_rows(docx_input, docx_output):
                    # center or other, default to TAC
                    pStyle_elem.set(f"{{{ns['w']}}}val", "TAC")
                    counter_tac += 1
            # Add keepnext to all rows elements to keep them together with the table caption
            # <w:keepNext w:val="0"/>
			# <w:keepLines w:val="0"/>
			# <w:widowControl w:val="0"/>
            pPr_elem = pStyle_elem.getparent()
            keepnext_elem = etree.Element(f"{{{ns['w']}}}keepNext")
            keepnext_elem.set(f"{{{ns['w']}}}val", "0")
            pPr_elem.append(keepnext_elem)
            keeplines_elem = etree.Element(f"{{{ns['w']}}}keepLines")
            keeplines_elem.set(f"{{{ns['w']}}}val", "0")
            pPr_elem.append(keeplines_elem)
            widowcontrol_elem = etree.Element(f"{{{ns['w']}}}widowControl")
            widowcontrol_elem.set(f"{{{ns['w']}}}val", "0")
            pPr_elem.append(widowcontrol_elem)
            
    print(f'Changed style "Compact/TableHeading" to "TAH" {counter_tah} times, "Compact/TableRow" to "TAL" {counter_tal} times, to "TAR" {counter_tar} times, to "TAC" {counter_tac} times')

@@ -2311,6 +2334,15 @@ def update_notes(docx_input, docx_output):
            # Re-append all original children (runs and hyperlinks) in their original order
            for child in all_children:
                para.append(child)
            # Remove the last run only when it is a break and nothing else:
            # <w:r><w:br/></w:r>
            runs = para.xpath('./w:r', namespaces=ns)
            if runs:
                run = runs[-1]
                content = [child for child in run if etree.QName(child).localname != 'rPr']
                if len(content) == 1 and etree.QName(content[0]).localname == 'br':
                    para.remove(run)
                    print(f'Removed <w:br/> run from NOTE paragraph (line {para.sourceline})')
        elif example_match:
            # Change style to EX
            pStyle_elem.set(f"{{{ns['w']}}}val", example_style)
@@ -2354,6 +2386,15 @@ def update_notes(docx_input, docx_output):
            # Re-append all original children (runs and hyperlinks) in their original order
            for child in all_children:
                para.append(child)
            # Remove the last run only when it is a break and nothing else:
            # <w:r><w:br/></w:r>
            runs = para.xpath('./w:r', namespaces=ns)
            if runs:
                run = runs[-1]
                content = [child for child in run if etree.QName(child).localname != 'rPr']
                if len(content) == 1 and etree.QName(content[0]).localname == 'br':
                    para.remove(run)
                    print(f'Removed <w:br/> run from EXAMPLE paragraph (line {para.sourceline})')
        else:
            # Check whether BlockText is preceded by paragraph style "EX".
            # Rules:
@@ -2387,6 +2428,8 @@ def update_notes(docx_input, docx_output):
            
    print(f'Changed style "BlockText/Notes" to "NO" {counter_no} times and "BlockText/Examples" to "EX" {counter_ew} times')



    xml_data = etree.tostring(root, xml_declaration=True, encoding="UTF-8", standalone="yes")
    
    # create temp file
@@ -2968,6 +3011,11 @@ def update_body_text_style(docx_input, docx_output):

        else:
            elem.set(f"{{{ns['w']}}}val", new_style)
            # Add keeplines in all normal paragraphs
            keeplines_elem = etree.Element(f"{{{ns['w']}}}keepLines")
            keeplines_elem.set(f"{{{ns['w']}}}val", "1")
            pPr_elem = elem.getparent()
            pPr_elem.append(keeplines_elem)
        counter += 1
        
    print(f'Changed style "BodyText/FirstParagraph" to "Normal" {counter} times and "H6" {h6_counter} times')
@@ -3114,6 +3162,10 @@ def update_references_style(docx_input, docx_output):
    """
    Updates references style from 'Hyperlink' to 'Normal' 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.

    Parameters
    ----------
    docx_input : str
@@ -3131,8 +3183,37 @@ 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

    # Clause 2 runs from the Heading1 "2 References" (or "References") through
    # the paragraph before the next Heading1. Heading numbers are already split
    # into their own run, so the text is "2" + "References".
    body = root.find(f"{{{ns['w']}}}body")
    body_children = list(body) if body is not None else []
    references_start = None
    references_end = None
    for index, child in enumerate(body_children):
        if etree.QName(child).localname != 'p':
            continue
        styles = child.xpath('./w:pPr/w:pStyle/@w:val', namespaces=ns)
        if not styles or styles[0] != 'Heading1':
            continue
        text = re.sub(r'\s+', '', ''.join(child.xpath('.//w:t/text()', namespaces=ns))).lower()
        if references_start is None and re.fullmatch(r'(?:2)?references', text):
            references_start = index
        elif references_start is not None:
            references_end = index
            break
    if references_start is not None and references_end is None:
        references_end = len(body_children)

    def _in_clause_2(elem):
        if references_start is None:
            return False
        index = _body_child_index(elem, body_children)
        return index is not None and references_start <= index < references_end

    # Pattern to match internal references: [i.1] or [1] or [i.12] or [12]
    reference_pattern = re.compile(r'^\[(i\.)?\d+\]$', re.IGNORECASE)

@@ -3168,7 +3249,8 @@ def update_references_style(docx_input, docx_output):
    for elem in root.xpath('.//w:rStyle[@w:val="Hyperlink"]', namespaces=ns):
        if not after_toc(elem):
            continue
        # Change the style to "Normal" if it is an internal reference (matches \[(i\.)?\d+\])
        # 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
@@ -3187,6 +3269,10 @@ def update_references_style(docx_input, docx_output):
        full_text = raw_text.strip()

        if not reference_pattern.match(full_text):
            if _in_clause_2(elem):
                continue
            elem.set(f"{{{ns['w']}}}val", new_style)
            other_counter += 1
            continue

        elem.set(f"{{{ns['w']}}}val", new_style)
@@ -3233,7 +3319,25 @@ def update_references_style(docx_input, docx_output):
            parent.insert(index + offset, elem)
        field_counter += 1

    print(f'Changed style "Hyperlink" to "Normal" {counter} times')
    # Keep hyperlink text such as "clause 6.2.3" on one line.
    nbsp = '\u00A0'
    nbsp_counter = 0
    xml_space = '{http://www.w3.org/XML/1998/namespace}space'
    for hyperlink in root.xpath('.//w:hyperlink', namespaces=ns):
        if not after_toc(hyperlink) or _in_clause_2(hyperlink):
            continue
        changed = False
        for text_elem in hyperlink.xpath('.//w:t', namespaces=ns):
            if text_elem.text and ' ' in text_elem.text:
                text_elem.text = text_elem.text.replace(' ', nbsp)
                text_elem.set(xml_space, 'preserve')
                changed = True
        if changed:
            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 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")
@@ -3261,6 +3365,74 @@ def update_references_style(docx_input, docx_output):
        if os.path.exists(tmp_path):
            os.remove(tmp_path)

def add_non_breaking_spaces(docx_input, docx_output):
    """
    Replace the space in references such as "clause 6.2.3", "table 7.1-1"
    and "figure 6-1" with a non-breaking space.

    Paragraphs whose style is listed in ignore_styles are left unchanged.
    """
    ns = {"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"}
    ignore_styles = ('SourceCode', 'PL', 'Hyperlink', 'Verbatim', 'VerbatimChar', 'TH', 'Heading', 'TF')

    with zipfile.ZipFile(docx_input, 'r') as zin:
        xml_data = zin.read("word/document.xml")

    root = etree.fromstring(xml_data)
    after_toc = _content_after_toc(root, ns)
    nbsp = '\u00A0'
    phrase_counter = 0
    xml_space = '{http://www.w3.org/XML/1998/namespace}space'
    # Examples:
    # clause 6.3.2
    # table 7.1-1
    # figure 6-1
    # section 6.3.2
    # appendix A
    # annex A
    # appendix A-1
    # annex A-1
    # appendix A-1
    # RFC 1234
    ref_phrase = re.compile(
        r'\b((?:clauses?|tables?|figures?|sections?|appendices?|annexes?|RFCs?)\s+(?:[A-Z](?:\.\d+)+|\d+(?:[.\-]\d+)*))',
        re.IGNORECASE,
    )

    for para in root.xpath('.//w:p', namespaces=ns):
        if not after_toc(para) or _paragraph_style_val(para, ns) in ignore_styles:
            continue
        for text_elem in para.xpath('.//w:t', namespaces=ns):
            if not text_elem.text or text_elem.xpath('ancestor::w:hyperlink', namespaces=ns):
                continue
            if not ref_phrase.search(text_elem.text):
                continue
            text_elem.text = ref_phrase.sub(lambda match: match.group(0).replace(' ', nbsp), text_elem.text)
            text_elem.set(xml_space, 'preserve')
            phrase_counter += 1

    print(f'Replaced spaces in clause/table/figure references {phrase_counter} times')

    xml_data = etree.tostring(root, xml_declaration=True, encoding="UTF-8", standalone="yes")

    tmp_fd, tmp_path = tempfile.mkstemp(suffix=".docx")
    os.close(tmp_fd)

    try:
        with zipfile.ZipFile(docx_input, 'r') as zin, zipfile.ZipFile(tmp_path, 'w', zipfile.ZIP_DEFLATED) as zout:
            for item in zin.infolist():
                if item.filename != "word/document.xml":
                    data = zin.read(item.filename)
                    zout.writestr(item.filename, data)
            zout.writestr("word/document.xml", xml_data)

        shutil.move(tmp_path, docx_output)
        os.chmod(docx_output, 0o644)
    finally:
        if os.path.exists(tmp_path):
            os.remove(tmp_path)


def update_source_code_style(docx_input, docx_output):
    """
    Updates source code styles from 'SourceCode' to 'PL' in a DOCX file.
@@ -3740,6 +3912,7 @@ def update_format_styles_cli():
        ("add_no_break_hyphens", add_no_break_hyphens),
        ("update_references_style", update_references_style),
        ("update_source_code_style", update_source_code_style),
        ("add_non_breaking_spaces", add_non_breaking_spaces),
        ("add_break_after_code_blocks_and_tables", add_break_after_code_blocks_and_tables),
        ("update_equation_style", update_equation_style),
        ("correct_quotes_docx", correct_quotes_docx)