Fred Drake | dd244a0 | 1998-02-09 22:17:52 +0000 | [diff] [blame^] | 1 | #! /usr/bin/env python |
| 2 | |
| 3 | """Combine similar index entries into an entry and subentries. |
| 4 | |
| 5 | For example: |
| 6 | |
| 7 | \item {foobar} (in module flotz), 23 |
| 8 | \item {foobar} (in module whackit), 4323 |
| 9 | |
| 10 | becomes |
| 11 | |
| 12 | \item {foobar} |
| 13 | \subitem in module flotz, 23 |
| 14 | \subitem in module whackit, 4323 |
| 15 | |
| 16 | Note that an item which matches the format of a collapsable item but which |
| 17 | isn't part of a group of similar items is not modified. |
| 18 | """ |
| 19 | __version__ = '$Revision$' |
| 20 | |
| 21 | import re |
| 22 | import string |
| 23 | import StringIO |
| 24 | import sys |
| 25 | |
| 26 | |
| 27 | def strcasecmp(e1, e2, lower=string.lower): |
| 28 | return cmp(lower(e1[1]), lower(e2[1])) or cmp(e1, e2) |
| 29 | |
| 30 | |
| 31 | def dump_entries(ofp, entries): |
| 32 | if len(entries) == 1: |
| 33 | ofp.write(" \\item %s (%s)%s\n" % entries[0]) |
| 34 | return |
| 35 | ofp.write(" \item %s\n" % entries[0][0]) |
| 36 | # now sort these in a case insensitive manner: |
| 37 | entries.sort(strcasecmp) |
| 38 | for xxx, subitem, pages in entries: |
| 39 | ofp.write(" \subitem %s%s\n" % (subitem, pages)) |
| 40 | |
| 41 | |
| 42 | breakable_re = re.compile(r" \\item (.*) [(](.*)[)]((?:, \d+)+)") |
| 43 | |
| 44 | def main(): |
| 45 | import getopt |
| 46 | outfile = None |
| 47 | opts, args = getopt.getopt(sys.argv[1:], "o:") |
| 48 | for opt, val in opts: |
| 49 | if opt in ("-o", "--output"): |
| 50 | outfile = val |
| 51 | filename = args[0] |
| 52 | outfile = outfile or filename |
| 53 | if filename == "-": |
| 54 | fp = sys.stdin |
| 55 | else: |
| 56 | fp = open(filename) |
| 57 | ofp = StringIO.StringIO() |
| 58 | item, subitem = None, None |
| 59 | entries = [] |
| 60 | while 1: |
| 61 | line = fp.readline() |
| 62 | if not line: |
| 63 | break |
| 64 | m = breakable_re.match(line) |
| 65 | if m: |
| 66 | entry = m.group(1, 2, 3) |
| 67 | if entries: |
| 68 | if entries[-1][0] != entry[0]: |
| 69 | dump_entries(ofp, entries) |
| 70 | entries = [] |
| 71 | entries.append(entry) |
| 72 | elif entries: |
| 73 | dump_entries(ofp, entries) |
| 74 | entries = [] |
| 75 | ofp.write(line) |
| 76 | else: |
| 77 | pass |
| 78 | ofp.write(line) |
| 79 | fp.close() |
| 80 | if outfile == "-": |
| 81 | fp = sys.stdout |
| 82 | else: |
| 83 | fp = open(outfile, "w") |
| 84 | fp.write(ofp.getvalue()) |
| 85 | fp.close() |
| 86 | |
| 87 | |
| 88 | if __name__ == "__main__": |
| 89 | main() |