]> git.lyx.org Git - lyx.git/blob - lib/scripts/include_bib.py
16156a502a7bfbd2f940bfa72a53071f48ed8ea6
[lyx.git] / lib / scripts / include_bib.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 # file include_bib.py
5 # This file is part of LyX, the document processor.
6 # Licence details can be found in the file COPYING.
7
8 # authors Richard Heck and [SchAirport]
9
10 # Full author contact details are available in file CREDITS
11
12 import sys, os
13
14 class secbib:
15   def __init__(self, start = -1, end = -1):
16     self.start = start
17     self.end   = end
18
19 class BibError(Exception):
20   def __init__(self, msg):
21     self.msg = msg
22
23   def __str__(self):
24     return self.msg
25
26
27 def InsertBib(fil, out):   
28   ''' Inserts the contents of the .bbl file instead of the bibliography in a new .tex file '''
29
30   texlist = open(fil, 'r').readlines()
31
32   # multiple bibliographies
33   biblist = []
34   stylist = []
35   
36   for i, line in enumerate(texlist):
37     if "\\bibliographystyle" in line:
38       stylist.append(i)
39     elif "\\bibliography" in line:
40       biblist.append(i)
41     elif "\\begin{btSect}" in line:
42       raise BibError("Cannot export sectioned bibliographies")
43   
44   if len(biblist) > 1:
45     raise BibError("Cannot export multiple bibliographies.")
46   if not biblist:
47     raise BibError("No biliography found!")
48
49   bibpos = biblist[0]
50   newlist = texlist[0:bibpos]
51   bblfile = fil[:-4] + ".bbl"
52   bbllist = open(bblfile, 'r').readlines()
53   newlist += bbllist
54   newlist += texlist[bibpos + 1:]
55     
56   outfile = open(out, 'w')
57   outfile.write("".join(newlist))
58   outfile.close()
59   return out
60     
61
62 def usage():
63   print r'''
64 Usage: python include_bib.py file.tex [outfile.tex]
65   Includes the contents of file.bbl, which must exist in the
66   same directory as file.tex, in place of the \bibliography
67   command, and creates the new file outfile.tex. If no name
68   for that file is given, we create: file-bbl.tex.
69 '''  
70
71 if __name__ == "__main__":
72   args = len(sys.argv)
73   if args <= 1 or args > 3:
74     usage()
75     sys.exit(0)
76
77   # we might should make sure this is a tex file....
78   infile = sys.argv[1]
79   if infile[-4:] != ".tex":
80     print "Error: " + infile + " is not a TeX file"
81     usage()
82     sys.exit(1)
83
84   if args == 3:
85     outfile = sys.argv[2]
86   else:
87     outfile = infile[:-4] + "-bbl.tex"
88
89   newfile = InsertBib(infile, outfile)
90   print "Wrote " + outfile