]> git.lyx.org Git - lyx.git/blob - src/insets/insetbibtex.C
reintroduce LFUN_BIBDB_ADD and LFUN BIBDB_DEL (bug 961)
[lyx.git] / src / insets / insetbibtex.C
1 /**
2  * \file insetbibtex.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alejandro Aguilar Sierra
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "insetbibtex.h"
14
15 #include "buffer.h"
16 #include "bufferparams.h"
17 #include "dispatchresult.h"
18 #include "debug.h"
19 #include "funcrequest.h"
20 #include "LaTeXFeatures.h"
21 #include "gettext.h"
22 #include "metricsinfo.h"
23 #include "outputparams.h"
24
25 #include "support/filetools.h"
26 #include "support/lstrings.h"
27 #include "support/os.h"
28 #include "support/path.h"
29
30 #include <fstream>
31
32 using lyx::support::AbsolutePath;
33 using lyx::support::ascii_lowercase;
34 using lyx::support::ChangeExtension;
35 using lyx::support::contains;
36 using lyx::support::findtexfile;
37 using lyx::support::IsFileReadable;
38 using lyx::support::latex_path;
39 using lyx::support::ltrim;
40 using lyx::support::MakeAbsPath;
41 using lyx::support::MakeRelPath;
42 using lyx::support::Path;
43 using lyx::support::prefixIs;
44 using lyx::support::rtrim;
45 using lyx::support::split;
46 using lyx::support::subst;
47 using lyx::support::tokenPos;
48 using lyx::support::trim;
49
50 namespace os = lyx::support::os;
51
52 using std::endl;
53 using std::getline;
54 using std::string;
55 using std::ifstream;
56 using std::ostream;
57 using std::pair;
58 using std::vector;
59
60
61 InsetBibtex::InsetBibtex(InsetCommandParams const & p)
62         : InsetCommand(p, "bibtex")
63 {}
64
65
66 std::auto_ptr<InsetBase> InsetBibtex::doClone() const
67 {
68         return std::auto_ptr<InsetBase>(new InsetBibtex(*this));
69 }
70
71
72 void InsetBibtex::doDispatch(LCursor & cur, FuncRequest & cmd)
73 {
74         switch (cmd.action) {
75
76         case LFUN_INSET_MODIFY: {
77                 InsetCommandParams p;
78                 InsetCommandMailer::string2params("bibtex", cmd.argument, p);
79                 if (!p.getCmdName().empty())
80                         setParams(p);
81                 else
82                         cur.noUpdate();
83                 break;
84         }
85
86         default:
87                 InsetCommand::doDispatch(cur, cmd);
88                 break;
89         }
90 }
91
92
93 string const InsetBibtex::getScreenLabel(Buffer const &) const
94 {
95         return _("BibTeX Generated Bibliography");
96 }
97
98
99 namespace {
100
101 string normalize_name(Buffer const & buffer, OutputParams const & runparams,
102                       string const & name, string const & ext)
103 {
104         string const fname = MakeAbsPath(name, buffer.filePath());
105         if (AbsolutePath(name) || !IsFileReadable(fname + ext))
106                 return name;
107         else if (!runparams.nice)
108                 return fname;
109         else
110                 return MakeRelPath(fname, buffer.getMasterBuffer()->filePath());
111 }
112
113 }
114
115
116 int InsetBibtex::latex(Buffer const & buffer, ostream & os,
117                        OutputParams const & runparams) const
118 {
119         // the sequence of the commands:
120         // 1. \bibliographystyle{style}
121         // 2. \addcontentsline{...} - if option bibtotoc set
122         // 3. \bibliography{database}
123         // and with bibtopic:
124         // 1. \bibliographystyle{style}
125         // 2. \begin{btSect}{database}
126         // 3. \btPrint{Cited|NotCited|All}
127         // 4. \end{btSect}
128
129         // the database string
130         string adb;
131         string db_in = getContents();
132         db_in = split(db_in, adb, ',');
133         // If we generate in a temp dir, we might need to give an
134         // absolute path there. This is a bit complicated since we can
135         // have a comma-separated list of bibliographies
136         string db_out;
137         while (!adb.empty()) {
138                 db_out += latex_path(normalize_name(buffer, runparams, adb, ".bib"));
139                 db_out += ',';
140                 db_in = split(db_in, adb,',');
141         }
142         db_out = rtrim(db_out, ",");
143
144         // Style-Options
145         string style = getOptions(); // maybe empty! and with bibtotoc
146         string bibtotoc;
147         if (prefixIs(style, "bibtotoc")) {
148                 bibtotoc = "bibtotoc";
149                 if (contains(style, ',')) {
150                         style = split(style, bibtotoc, ',');
151                 }
152         }
153
154         // line count
155         int i = 0;
156
157         if (!style.empty()) {
158                 os << "\\bibliographystyle{"
159                    << latex_path(normalize_name(buffer, runparams, style, ".bst"))
160                    << "}\n";
161                 i += 1;
162         }
163
164         if (buffer.params().use_bibtopic){
165                 os << "\\begin{btSect}{" << db_out << "}\n";
166                 string btprint = getSecOptions();
167                 if (btprint.empty())
168                         // default
169                         btprint = "btPrintCited";
170                 os << "\\" << btprint << "\n"
171                    << "\\end{btSect}\n";
172                 i += 3;
173         }
174
175         // bibtotoc-Option
176         if (!bibtotoc.empty() && !buffer.params().use_bibtopic) {
177                 // maybe a problem when a textclass has no "art" as
178                 // part of its name, because it's than book.
179                 // For the "official" lyx-layouts it's no problem to support
180                 // all well
181                 if (!contains(buffer.params().getLyXTextClass().name(),
182                               "art")) {
183                         if (buffer.params().sides == LyXTextClass::OneSide) {
184                                 // oneside
185                                 os << "\\clearpage";
186                         } else {
187                                 // twoside
188                                 os << "\\cleardoublepage";
189                         }
190
191                         // bookclass
192                         os << "\\addcontentsline{toc}{chapter}{\\bibname}";
193
194                 } else {
195                         // article class
196                         os << "\\addcontentsline{toc}{section}{\\refname}";
197                 }
198         }
199
200         if (!buffer.params().use_bibtopic){
201                 os << "\\bibliography{" << db_out << "}\n";
202                 i += 1;
203         }
204
205         return i;
206 }
207
208
209 vector<string> const InsetBibtex::getFiles(Buffer const & buffer) const
210 {
211         Path p(buffer.filePath());
212
213         vector<string> vec;
214
215         string tmp;
216         string bibfiles = getContents();
217         bibfiles = split(bibfiles, tmp, ',');
218         while (!tmp.empty()) {
219                 string file = findtexfile(ChangeExtension(tmp, "bib"), "bib");
220                 lyxerr[Debug::LATEX] << "Bibfile: " << file << endl;
221
222                 // If we didn't find a matching file name just fail silently
223                 if (!file.empty())
224                         vec.push_back(file);
225
226                 // Get next file name
227                 bibfiles = split(bibfiles, tmp, ',');
228         }
229
230         return vec;
231 }
232
233
234 // This method returns a comma separated list of Bibtex entries
235 void InsetBibtex::fillWithBibKeys(Buffer const & buffer,
236                                   std::vector<std::pair<string, string> > & keys) const
237 {
238         vector<string> const files = getFiles(buffer);
239         for (vector<string>::const_iterator it = files.begin();
240              it != files.end(); ++ it) {
241                 // This is a _very_ simple parser for Bibtex database
242                 // files. All it does is to look for lines starting
243                 // in @ and not being @preamble and @string entries.
244                 // It does NOT do any syntax checking!
245                 ifstream ifs(it->c_str());
246                 string linebuf0;
247                 while (getline(ifs, linebuf0)) {
248                         string linebuf = trim(linebuf0);
249                         if (linebuf.empty()) continue;
250                         if (prefixIs(linebuf, "@")) {
251                                 linebuf = subst(linebuf, '{', '(');
252                                 string tmp;
253                                 linebuf = split(linebuf, tmp, '(');
254                                 tmp = ascii_lowercase(tmp);
255                                 if (!prefixIs(tmp, "@string")
256                                     && !prefixIs(tmp, "@preamble")) {
257                                         linebuf = split(linebuf, tmp, ',');
258                                         tmp = ltrim(tmp, " \t");
259                                         if (!tmp.empty()) {
260                                                 keys.push_back(pair<string,string>(tmp,string()));
261                                         }
262                                 }
263                         } else if (!keys.empty()) {
264                                 keys.back().second += linebuf + "\n";
265                         }
266                 }
267         }
268 }
269
270
271 bool InsetBibtex::addDatabase(string const & db)
272 {
273         string contents(getContents());
274         if (tokenPos(contents, ',', db) == -1) {
275                 if (!contents.empty())
276                         contents += ',';
277                 setContents(contents + db);
278                 return true;
279         }
280         return false;
281 }
282
283
284 bool InsetBibtex::delDatabase(string const & db)
285 {
286         string contents(getContents());
287         if (contains(contents, db)) {
288                 int const n = tokenPos(contents, ',', db);
289                 string bd = db;
290                 if (n > 0) {
291                         // this is not the first database
292                         string tmp = ',' + bd;
293                         setContents(subst(contents, tmp, ""));
294                 } else if (n == 0)
295                         // this is the first (or only) database
296                         setContents(split(contents, bd, ','));
297                 else
298                         return false;
299         }
300         return true;
301 }
302
303
304 void InsetBibtex::validate(LaTeXFeatures & features) const
305 {
306         if (features.bufferParams().use_bibtopic)
307                 features.require("bibtopic");
308 }