Skip to content

Fix refs #59

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Apr 11, 2025
Merged

Conversation

jonathan-taylor
Copy link
Collaborator

LaTeX refs migrated back into the labs. Replaced using .aux files

@jonathan-taylor
Copy link
Collaborator Author

This script was helpful, but probably not worth committing.
'''
import re
import argparse
import os

def replace_refs_in_file(aux_file_paths, input_file_path, output_file_path, overwrite=False):
"""
Replaces \ref, \eqref, and \pageref references in a file using data from a list of .aux files.
Replaces "\ref" and "\eqref" with " \ref" and " \eqref" respectively.

Args:
    aux_file_paths: A list of paths to .aux files.
    input_file_path: Path to the input file containing references.
    output_file_path: Path to the output file with replaced references.
"""

label_values_ref = {}
label_values_pageref = {}

# Gather label-value pairs from all .aux files
for aux_file_path in aux_file_paths:
    try:
        with open(aux_file_path, 'r', encoding='utf-8') as aux_file:
            aux_content = aux_file.read()

        # Extract \newlabel data
        ref_matches = re.findall(r'\\newlabel\{([^}]+)\}\{\{(.*?)\}\}', aux_content)

        for label, page_info in ref_matches:
            page_numbers = page_info.split('}{')
            print(page_info)
            if len(page_numbers) >= 2:
                label_values_pageref[label] = page_numbers[1]
                label_values_ref[label] = page_numbers[0]
            elif len(page_numbers) == 1:
                label_values_ref[label] = page_numbers[0]

    except FileNotFoundError as e:
        print(f"Warning: File not found: {e}")

try:
    with open(input_file_path, 'r', encoding='utf-8') as input_file:
        input_content = input_file.read()
except FileNotFoundError as e:
    print(f"Error: Input File not found: {e}")
    return

def replace_ref(match):
    label = match.group(1)
    if label in label_values_ref:
        return label_values_ref[label]
    else:
        return match.group(0)  # Keep original if label not found

def replace_pageref(match):
    label = match.group(1)
    if label in label_values_pageref:
        return label_values_pageref[label]
    else:
        return match.group(0)  # Keep original if label not found

# Replace \ref, \eqref, and \pageref in the input file
output_content = re.sub(r'~\s*\\ref', r' \\ref', input_content)
output_content = re.sub(r'~\s*\\eqref', r' \\eqref', output_content)
output_content = re.sub(r'~\s*\\pageref', r' \\pageref', output_content)
output_content = re.sub(r'\\pageref\{([^}]+)\}', replace_pageref, output_content)
output_content = re.sub(r'~(\\ref\{([^}]+)\})', lambda m: f'({replace_ref(m)})', output_content)
output_content = re.sub(r'\\ref\{([^}]+)\}', replace_ref, output_content)
output_content = re.sub(r'\\eqref\{([^}]+)\}', lambda m: f'({replace_ref(m)})', output_content)

try:
    with open(output_file_path, 'w', encoding='utf-8') as output_file:
        output_file.write(output_content)
    print(f"References replaced and saved to {output_file_path}")
except IOError as e:
    print(f"Error writing to output file: {e}")

if overwrite:
    os.remove(input_file_path)
    os.rename(output_file_path, input_file_path)

if name == "main":
parser = argparse.ArgumentParser(description="Replace LaTeX references using an .aux file.")
parser.add_argument("--auxfile", action="append", required=True, help="Path to an .aux file. Can be used multiple times.")
parser.add_argument("--infile", help="Path to the input file.")
parser.add_argument("--outfile", help="Path to the output file.")
parser.add_argument("--overwrite", dest='overwrite', default=False, action='store_true', help="Overwrite the input and remove the output?")

args = parser.parse_args()

replace_refs_in_file(args.auxfile, args.infile, args.outfile, overwrite=args.overwrite)

'''

@jonathan-taylor jonathan-taylor merged commit f7d7153 into intro-stat-learning:main Apr 11, 2025
@trevorhastie
Copy link
Collaborator

trevorhastie commented Apr 12, 2025 via email

@tschm
Copy link
Contributor

tschm commented Apr 13, 2025

https://github.com/tschm/cradle/blob/main/actions/age/action.yml

Here's an example how to use a Python script as a workflow. You could use this strategy to replace/remove/... links designed for LaTeX. You could have hyperlinks to an existing page/document etc.

I recommend to have one single truth. This should be the ipynb notebooks (not sure how Marimo can deal with R)
All other variations should be built by workflows.

You may want to include a latex skeleton version of the book which is just importing the latex versions of the notebooks and compile as a workflow after every commit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants