Skip to content

Instantly share code, notes, and snippets.

@calmez
Last active August 29, 2015 14:26
Show Gist options
  • Save calmez/a1672dac4ab624a77d21 to your computer and use it in GitHub Desktop.
Save calmez/a1672dac4ab624a77d21 to your computer and use it in GitHub Desktop.
Little tool to filter tex(t) files
#!/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()
@calmez
Copy link
Author

calmez commented Jul 30, 2015

CleanFootnotesFilterAction is an example of an filter action -- only the action methods needs to get implemented.
Cleaner instances can be configured with FilterActions on instantiation (lines 59f).

@calmez
Copy link
Author

calmez commented Jul 30, 2015

The initial use case was to alter generated tex-files ;)

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