Created
January 26, 2023 18:30
-
-
Save yzh119/bcd52d28c2fca76d7e4ead54e2f8ebdf to your computer and use it in GitHub Desktop.
Automatically add `~` before each appearance of `\cite`
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
import os | |
import sys | |
import glob | |
import logging | |
logging.basicConfig(level=logging.INFO) | |
def fix_cite_format(line_number: int, line: str): | |
out = "" | |
start = 0 | |
command = r"\cite" | |
while True: | |
pos = line.find(command, start) | |
if pos == -1: | |
break | |
out += line[start:pos] | |
if line[pos - 1] != "~": | |
logging.warning( | |
"Missing ~ before {} at line {} pos {}, surrounding text: {}".format( | |
command, line_number, pos, line[pos - 10 : pos + 30] | |
) | |
) | |
out += "~" | |
out += command | |
start = pos + len(command) | |
out += line[start:] | |
return out | |
for fpath in glob.iglob('./**/*.tex', recursive=True): | |
logging.info("Scanning file {}".format(fpath)) | |
filename = os.path.basename(fpath) | |
formatted_text = "" | |
with open(fpath, "r") as f: | |
lines = f.readlines() | |
for i, line in enumerate(lines): | |
original_line = line | |
line = fix_cite_format(i, line) | |
if original_line != line: | |
print("---") | |
print(original_line) | |
print("+++") | |
print(line) | |
formatted_text += line | |
with open(fpath, "w") as f: | |
f.write(formatted_text) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment