Skip to content

Instantly share code, notes, and snippets.

@smacke
Created February 14, 2020 04:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smacke/ca4c5ca16ff349edb5e299d17544d7fa to your computer and use it in GitHub Desktop.
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.
#!/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())
@smacke
Copy link
Author

smacke commented Feb 14, 2020

Example usage:
python add_ref_suffix.py --suffix chp1 --files *.tex

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment