Last active
August 29, 2015 14:26
-
-
Save calmez/a1672dac4ab624a77d21 to your computer and use it in GitHub Desktop.
Little tool to filter tex(t) files
This file contains hidden or 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 | |
# -*- coding: UTF-8 -*- | |
import os | |
class Cleaner: | |
def __init__(self, filename, *filter_actions): | |
self.file = open(filename, 'r') | |
self.filter_actions = filter_actions | |
def __enter__(self): | |
return self | |
def __exit__(self, type, value, traceback): | |
self.file.close() | |
def clean(self): | |
for action in self.filter_actions: | |
with action(self) as a: | |
a.filter() | |
class AbstractFilterAction: | |
def __init__(self, cleaner): | |
self.cleaner = cleaner | |
self.file = open(".%s.%s" % (self.cleaner.file.name, | |
self.__class__.__name__), | |
'w') | |
def __enter__(self): | |
return self | |
def __exit__(self, type, value, traceback): | |
self.file.close() | |
os.rename(self.file.name, self.cleaner.file.name) | |
@property | |
def input_file(self): | |
return self.cleaner.file | |
def filter(self): | |
self.cleaner.file.seek(0) | |
self.file.writelines(self.action()) | |
def action(self): | |
pass | |
class CleanFootnotesFilterAction(AbstractFilterAction): | |
def action(self): | |
lines = [] | |
for line in self.input_file: | |
if line.startswith("\\footnote"): | |
lines[-1] = "".join([lines[-1][:-1], line]) | |
else: | |
lines.append(line.replace(" \\footnote{", "\\footnote{")) | |
return lines | |
if __name__ == "__main__": | |
import sys | |
if len(sys.argv) < 2: | |
print("Please provide the filename for the tex file to filter") | |
with Cleaner(sys.argv[1], | |
CleanFootnotesFilterAction) as c: | |
c.clean() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The initial use case was to alter generated tex-files ;)