Initial import of my home directory
[home/.git] / .vim / ltags
1 #!/usr/bin/perl
2 # Author: Dimitri Antoniou <dimitri@risc2.aecom.yu.edu>
3 # usage: ltags filename
4 # handles: \label and \cite{ } with one or more arguments
5 #          fails if arguments of cite spread over more than one line
6 # also searches in files that are \include or \input in the main file
7
8 # get main LaTeX source file from command line:
9 $mainfile = shift;
10
11 # get names of included files and store them in an array
12 open MAIN, $mainfile or die "$!" ;
13 @mainfile=<MAIN>;
14 @allsrcfiles = map{ /^\\(?:input|include){(.*?)}/ } @mainfile;
15 unshift @allsrcfiles, $mainfile;
16
17 # loop over all source files
18 for $srcfile (@allsrcfiles) {
19     # if \input{fname} append .tex to fname
20     unless ( $srcfile =~ m/\.tex/ ) { $srcfile = $srcfile . "\.tex" }
21     open SRC, $srcfile or die "$!" ;
22     # store contents of source file in array @texfile
23     @texfile=<SRC>;
24
25     # store lines with \label and \cite (or \citeonline) in arrays
26     @labelList  = grep{ /\\label{/ } @texfile;
27     @citeList = grep{ /\\(cite|citeonline){/ } @texfile;
28
29     # see if we use an external database; if yes, store its name in $bibfile
30     ($dbase) = grep{ /^\\bibliography{/ } @texfile;
31     if ($dbase) {
32        $dbase =~ m/\\bibliography{(.*?)}/;
33        $bibfile = $1;
34     }
35
36     # write \bibitem in tags file 
37     @mrefs=();
38     @refs=();
39     @multirefs=();
40     foreach (@citeList) {
41         while ( m/\\(?:cite|citeonline){(.*?)}/g ) {
42             $refs = $1;
43             # if \cite has more than one argument, split them:
44             if ($refs =~ /,/) {
45                 @mrefs = split /,/, $refs;
46                 # there might be more than one \cite in a line:
47                 push (@multirefs, @mrefs);
48             }
49             else {
50                 @refs = ($refs);
51                 push (@multirefs, @refs);
52             }
53         }
54         # in BibTeX, format is @ARTICLE{Name, }; in source file, \bibitem{Name}
55         for $ref (@multirefs) {
56            if ( $dbase ) {
57                push @unsorttag, "$ref\t$bibfile\t/{$ref,/\n"
58            }
59            else {
60                push @unsorttag, "$ref\t$srcfile\t/bibitem{$ref}/\n"
61            }
62         }
63     }
64
65     # write \label in tag file
66     foreach (@labelList) {
67          m/\\label{(.*?)}/;
68          push @unsorttag, "$1\t$srcfile\t/label{$1}/\n";
69     }
70 }
71
72 # sort tag file; then, eliminate duplicates
73 @sortedtag = sort @unsorttag;
74 %seen = ();
75 @uniqtag = grep { ! $seen{$_} ++ } @sortedtag;
76
77 open(TAGS, "> tags");
78 print TAGS @uniqtag;