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

Fix for long name references (Pandoc supports up to 40 characters)

parent 2fcd1756
Loading
Loading
Loading
Loading
Loading
+51
Changes for generateBaseline/pandocFilter.py: 51 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -1003,6 +1003,55 @@ def convertHtmlTablesTogridTables(progress:Progress, mdLines:list[str]) -> list[
	progress.stop_task(_taskID)
	return _lines

# Word shows a 40-character bookmark one character shorter. Citation targets
# are cut to 39 here, and postprocessing stores the same cut on the heading.
# Figure, table and reference anchors use a different bookmark and are left unchanged.
_BOOKMARK_LIMIT = 39
_CITATION_TARGET = re.compile(r'(\]\(#)([^)\s]+)')

def _cut_citation_anchor(anchor:str) -> str:
	if anchor.lower().startswith(('figure_', 'table_', '_ref')) or len(anchor) <= _BOOKMARK_LIMIT:
		return anchor
	return anchor[:_BOOKMARK_LIMIT]

def shortenCitationAnchors(progress:Progress, mdLines:list[str]) -> list[str]:
	"""Cut internal heading targets to Word's 39 character bookmark limit.

	Code blocks and grid tables are left unchanged.
	"""
	_taskID = progress.add_task('[blue]Shortening citation anchors', total=0)
	resetCodeBlockState()
	in_grid_table = False
	lines:list[str] = []

	def _transform(line:str) -> str:
		def replace(match):
			anchor = match.group(2)
			cut = _cut_citation_anchor(anchor)
			if cut != anchor:
				print(f'Shortened anchor "{anchor}" to "{cut}"')
			return match.group(1) + cut
		return _CITATION_TARGET.sub(replace, line)

	for line in mdLines:
		if checkInCodeBlock(line):
			in_grid_table = False
			lines.append(line)
			continue
		if in_grid_table:
			if _is_grid_table_line(line):
				lines.append(line)
				continue
			in_grid_table = False
		if _MATCH_GRID_TABLE.match(line.lstrip(' \t')):
			in_grid_table = True
			lines.append(line)
			continue
		lines.append(SkipCodeAndTables.map_outside_inline_code(line, _transform))

	progress.stop_task(_taskID)
	return lines

def process(args) -> None:
	with Progress(TextColumn('{task.description}'),  TimeElapsedColumn()) as progress:
		mdLines = readMDFile(progress, args.document)
@@ -1039,6 +1088,8 @@ def process(args) -> None:
		print(f'Number of lines in the document after replacing superscripts and subscripts: {len(mdLines)}')
		mdLines = convertHtmlTablesTogridTables(progress, mdLines)
		print(f'Number of lines in the document after converting HTML tables to grid tables: {len(mdLines)}')
		mdLines = shortenCitationAnchors(progress, mdLines)
		print(f'Number of lines in the document after shortening citation anchors: {len(mdLines)}')
		writeMDFile(progress, mdLines, args.document, args.outDirectory)


+36 −4
Changes for generateBaseline/postprocessing.py: 36 added lines, 4 removed lines.
Original line number Diff line number Diff line
@@ -826,6 +826,27 @@ def _is_in_abbreviations_clause(para, ns):
    return False


# Word shows a 40-character bookmark one character shorter, so the name that
# resolves is 39 characters. The pandoc filter cuts citation targets to this
# same length before Pandoc sees them.
_BOOKMARK_LIMIT = 39


def _limit_bookmark_name(name):
    if name and len(name) > _BOOKMARK_LIMIT:
        return name[:_BOOKMARK_LIMIT]
    return name


def _heading_slug(text):
    """Slug of a whole heading, matching the markdown anchor."""
    slug = re.sub(r'\s+', '-', text.strip()).lower()
    slug = slug.replace("'", '').replace('\u2019', '').replace('\u2018', '')
    slug = re.sub(r'[.,:;![\]<>"\\(){}]', '', slug)
    slug = re.sub(r'-{2,}', '-', slug).strip('-')
    return slug


def _pandoc_bookmark_name(name):
    """Match Pandoc's toBookmarkName. A legal name starts with a letter and is at most 40 characters."""
    if name and name[0].isalpha() and len(name) <= 40:
@@ -1183,15 +1204,17 @@ def update_heading_styles(docx_input, docx_output):
        para.append(run)
        return run

    def _place_label_bookmark(para, label_run, number, title):
    def _place_label_bookmark(para, label_run, number, title, bookmark_name=None):
        nonlocal next_bookmark_id
        if label_run is None:
            return
        # "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.
        # The bookmark covers the number run only. A name longer than Word's limit is cut to 39 characters.
        if not bookmark_name:
            title_slug = re.sub(r'\s+', '-', title.strip()).lower()
            title_slug = re.sub(r'[.,:;![\]<>"\\(){}]', '', title_slug)
            bookmark_name = f"{number.replace('.', '')}-{title_slug}"
        bookmark_name = _limit_bookmark_name(bookmark_name)
        _remove_bookmarks(root, ns, {bookmark_name}, paragraph=para, hashed=True)
        _insert_bookmark_around(label_run, bookmark_name, next_bookmark_id, ns)
        next_bookmark_id += 1
@@ -1279,7 +1302,12 @@ 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 
            _place_label_bookmark(para, label_run, (annex_letter or 'annex').lower(), annex_title)
            # The markdown anchor is the slug of the whole heading, for example
            # annex-b-informative-introduction-of-external-organizations-data-models.
            _place_label_bookmark(
                para, label_run, (annex_letter or 'annex').lower(), annex_title,
                bookmark_name=_heading_slug(full_text),
            )
            insert_page_break_before_heading(para, full_text)  
            counter_annex += 1
        # Annex subheading Heading 2: "A.1 Title", not matching "A.1.1 Title"
@@ -3603,7 +3631,11 @@ def update_references_style(docx_input, docx_output):
    for start in root.xpath('.//w:bookmarkStart', namespaces=ns):
        name = start.get(f"{{{ns['w']}}}name")
        number = _bookmark_inner_text(start).replace('\u00A0', ' ').strip()
        if name and re.fullmatch(r'(?:[A-Z]|\d+)(?:\.\d+)*', number, re.IGNORECASE) and name.lower().startswith(number.replace('.', '').lower() + '-'):
        # "5.2" is stored as "52-...". An annex letter is stored as "annex-a-...".
        number_key = number.replace('.', '').lower()
        name_key = (name or '').lower()
        is_clause_bookmark = name_key.startswith(number_key + '-') or name_key.startswith('annex-' + number_key + '-')
        if name and re.fullmatch(r'(?:[A-Z]|\d+)(?:\.\d+)*', number, re.IGNORECASE) and is_clause_bookmark:
            clause_targets[number.lower()] = name

    # Old declaration bookmark name -> REF_ bookmark added by update_references.