Created
February 14, 2020 04:24
-
-
Save smacke/ca4c5ca16ff349edb5e299d17544d7fa to your computer and use it in GitHub Desktop.
Add a suffix to all labels / references in specified latex files, accounting for multiple comma-separated references in a single command as might occur with cleveref.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import sys | |
import argparse | |
import re | |
LABEL_REGEX = r'label\{([:\w]+)\}' | |
REF_REGEX = r'ref\{([:\w,]+)\}' | |
def _append_if_unchanged(ref, suffix): | |
if ref.endswith(':' + suffix): | |
return ref # unchanged | |
else: | |
return '{}:{}'.format(ref, suffix) | |
def make_ref_replace_callback(suffix): | |
def _ref_replace_callback(m): | |
refs = m.group(1).split(',') | |
refs = ','.join(map( | |
lambda ref: _append_if_unchanged(ref, suffix), refs)) | |
return r'ref{%s}' % refs | |
return _ref_replace_callback | |
def main(): | |
label_regex = re.compile(LABEL_REGEX) | |
ref_regex = re.compile(REF_REGEX) | |
parser = argparse.ArgumentParser( | |
description='Append suffix to all references.') | |
parser.add_argument('--suffix', required=True, | |
help='Suffix to append to all labels / refs.') | |
parser.add_argument('--files', nargs='+', required=True, | |
help='Files to search + replace.') | |
parser.add_argument('--backup', help='File extension for backup', | |
default=None) | |
args = parser.parse_args() | |
ref_replace_callback = make_ref_replace_callback(args.suffix) | |
for fname in args.files: | |
with open(fname, 'r') as f: | |
contents = f.read() | |
label_repl = r'label{\1:%s}' % args.suffix | |
new_contents = re.sub(label_regex, label_repl, contents) | |
new_contents = re.sub(ref_regex, ref_replace_callback, new_contents) | |
if args.backup is not None: | |
with open(fname + '.' + args.backup, 'w') as f: | |
f.write(contents) | |
with open(fname, 'w') as f: | |
f.write(new_contents) | |
return 0 | |
if __name__ == "__main__": | |
sys.exit(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage:
python add_ref_suffix.py --suffix chp1 --files *.tex