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