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