#! /usr/bin/env python

# textags
#
# Create a tags file for LaTeX-files, usable with vi and its clones.
# The tags-file (=tags) is further stripped into a file called mytags.
# That one is a bit easier to read, but of course you are free to use
# the classical tags-file.

import sys
import regex
import os
import string

tags = []	# Modified global variable!

MAX_LEN_NAME = 21

def main():
	args = sys.argv[1:]
	for file in args: treat_file(file)
	if tags:
		fp = open('tags', 'w')
		tags.sort()
		for s in tags: fp.write(s)
	fp.close()
	os.system ("cat tags | sed -e 's/	.*//' > mytags")


expr = '^.*\(chapter\|label\|section\|subsection\){+\([\.\:a-zA-ZéèàîçäöüÄÖÜ0-9 _]+\)'
matcher = regex.compile(expr)

def treat_file(file):
	try:
		fp = open(file, 'r')
	except:
		print 'Cannot open', file
		return
	base = os.path.basename(file)
	if base[-4:] == '.tex': base = base[:-4]
	s = base + '\t' + file + '\t' + '1\n'
	tags.append(s)
	while 1:
		line = fp.readline()
		if not line: break
		if matcher.search(line) >= 0:
			(a, b), (a1, b1), (a2, b2) = matcher.regs[:3]
			
			name = line[a2:b2]
			name = string.replace(name, ' ', '_')
			name = string.replace(name, '.', '')
			tit = line[a:b] 
			if len(tit) > 10 + MAX_LEN_NAME :
				tit = tit[:10 + MAX_LEN_NAME]
			s = name + '\t' + file + '\t/^' + tit + '/\n'
			s = string.replace(s, '\\', '\\\\')
			tags.append(s)

main()
