forked from johnjosephhorton/flatex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflatex.py
83 lines (70 loc) · 2.62 KB
/
flatex.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import click
import os
import re
import sys
def is_input(line):
"""
Determines whether or not a read in line contains an uncommented out
\input{} statement. Allows only spaces between start of line and
'\input{}'.
"""
#tex_input_re = r"""^\s*\\input{[^}]*}""" # input only
tex_input_re = r"""(^[^\%]*\\input{[^}]*})|(^[^\%]*\\include{[^}]*})""" # input or include
return re.search(tex_input_re, line)
def get_input(line):
"""
Gets the file name from a line containing an input statement.
"""
tex_input_filename_re = r"""{[^}]*"""
m = re.search(tex_input_filename_re, line)
return m.group()[1:]
def combine_path(base_path, relative_ref):
"""
Combines the base path of the tex document being worked on with the
relate reference found in that document.
"""
if (base_path != ""):
os.chdir(base_path)
# Handle if .tex is supplied directly with file name or not
if relative_ref.endswith('.tex'):
return os.path.join(base_path, relative_ref)
else:
return os.path.abspath(relative_ref) + '.tex'
def expand_file(base_file, current_path, include_bbl):
"""
Recursively-defined function that takes as input a file and returns it
with all the inputs replaced with the contents of the referenced file.
"""
output_lines = []
f = open(base_file, "r")
for line in f:
if is_input(line):
new_base_file = combine_path(current_path, get_input(line))
output_lines += expand_file(new_base_file, current_path, include_bbl)
output_lines.append('\n') # add a new line after each file input
elif include_bbl and line.startswith("\\bibliography") and (not line.startswith("\\bibliographystyle")):
output_lines += bbl_file(base_file)
else:
output_lines.append(line)
f.close()
return output_lines
def bbl_file(base_file):
"""
Return content of associated .bbl file
"""
bbl_path = os.path.abspath(os.path.splitext(base_file)[0]) + '.bbl'
return open(bbl_path).readlines()
@click.command()
@click.argument('base_file', type = click.Path())
@click.argument('output_file', type = click.Path())
@click.option('--include_bbl/--no_bbl', default=False)
def main(base_file, output_file, include_bbl = False):
"""
This "flattens" a LaTeX document by replacing all \input{X} lines w/ the
text actually contained in X. See associated README.md for details.
"""
current_path = os.path.split(base_file)[0]
g = open(output_file, "w")
g.write(''.join(expand_file(base_file, current_path, include_bbl)))
g.close()
return None