summaryrefslogtreecommitdiffstats
path: root/tex-un-include
blob: 440c626085f3761ed12ad5e8c7faef8f0b24ce27 (plain) (blame)
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
#!/usr/bin/env python

import sys
import re
from os import path

comment_re = re.compile(r'([^\\]|^)%')
input_re   = re.compile(r'\\(?:input|bibliography)\{([^}]*)\}')

def strip_comment(line):
    g = comment_re.search(line)
    if g:
        # we matched some non-\ character
        return line[0:g.start() + 1]
    else:
        return line

def chomp(line):
    if line and line[-1] == '\n':
        return line[:-1]
    else:
        return line

def open_tex_file(fname, mode='r'):
    if path.exists(fname + '.bbl'):
        # try bibliography file
        fname += '.bbl'    
    elif path.exists(fname + '.tex'):
        # try tex file
        fname += '.tex'
    return open(fname, mode)

def process_file(fname, out=sys.stdout):
    for line in open_tex_file(fname):
        line = chomp(strip_comment(line))
        idx = 0
        for g in input_re.finditer(line):
            out.write(line[idx:g.start()])
            fname = g.group(1)
            # recurse into file
            out.write("%%!!!!! processing %s !!!!!\n" % fname)
            process_file(fname, out)
            idx = g.end()
        out.write(line[idx:])
        out.write('\n')


def main(args=sys.argv[1:]):
    for fname in args:
        process_file(fname)

if __name__ == '__main__':
    main()