]> git.lyx.org Git - lyx.git/blob - src/insets/insetcite.C
Use exceptions to avoid more than one call to the filesystem.
[lyx.git] / src / insets / insetcite.C
1 /**
2  * \file insetcite.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Angus Leeming
7  * \author Herbert Voß
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "insetcite.h"
15
16 #include "buffer.h"
17 #include "bufferparams.h"
18 #include "BufferView.h"
19 #include "debug.h"
20 #include "dispatchresult.h"
21 #include "funcrequest.h"
22 #include "LaTeXFeatures.h"
23
24 #include "frontends/controllers/biblio.h"
25
26 #include "support/fs_extras.h"
27 #include "support/lstrings.h"
28
29 #include <boost/filesystem/operations.hpp>
30 #include <boost/filesystem/exception.hpp>
31
32 using lyx::support::ascii_lowercase;
33 using lyx::support::contains;
34 using lyx::support::getVectorFromString;
35 using lyx::support::ltrim;
36 using lyx::support::rtrim;
37 using lyx::support::split;
38
39 using std::endl;
40 using std::string;
41 using std::ostream;
42 using std::vector;
43 using std::map;
44
45 namespace biblio = lyx::biblio;
46 namespace fs = boost::filesystem;
47
48
49 namespace {
50
51 string const getNatbibLabel(Buffer const & buffer,
52                             string const & citeType, string const & keyList,
53                             string const & before, string const & after,
54                             biblio::CiteEngine engine)
55 {
56         // Only start the process off after the buffer is loaded from file.
57         if (!buffer.fully_loaded())
58                 return string();
59
60         // Cache the labels
61         typedef std::map<Buffer const *, biblio::InfoMap> CachedMap;
62         static CachedMap cached_keys;
63
64         // and cache the timestamp of the bibliography files.
65         static std::map<string, time_t> bibfileStatus;
66
67         biblio::InfoMap infomap;
68
69         vector<string> const & bibfilesCache = buffer.getBibfilesCache();
70         // compare the cached timestamps with the actual ones.
71         bool changed = false;
72         for (vector<string>::const_iterator it = bibfilesCache.begin();
73                         it != bibfilesCache.end(); ++ it) {
74                 string const f = *it;
75                 try {
76                         std::time_t lastw = fs::last_write_time(f);
77                         if (lastw != bibfileStatus[f]) {
78                                 changed = true;
79                                 bibfileStatus[f] = lastw;
80                         }
81                 }
82                 catch (fs::filesystem_error & fserr) {
83                         changed = true;
84                         lyxerr << "Couldn't find or read bibtex file "
85                                << f << endl;
86                         lyxerr[Debug::DEBUG] << "Fs error: "
87                                              << fserr.what() << endl;
88                 }
89         }
90
91         // build the keylist only if the bibfiles have been changed
92         if (cached_keys.empty() || bibfileStatus.empty() || changed) {
93                 typedef vector<std::pair<string, string> > InfoType;
94                 InfoType bibkeys;
95                 buffer.fillWithBibKeys(bibkeys);
96
97                 InfoType::const_iterator bit  = bibkeys.begin();
98                 InfoType::const_iterator bend = bibkeys.end();
99
100                 for (; bit != bend; ++bit)
101                         infomap[bit->first] = bit->second;
102
103                 cached_keys[&buffer] = infomap;
104         } else
105                 // use the cached keys
106                 infomap = cached_keys[&buffer];
107
108         if (infomap.empty())
109                 return string();
110
111         // the natbib citation-styles
112         // CITET:       author (year)
113         // CITEP:       (author,year)
114         // CITEALT:     author year
115         // CITEALP:     author, year
116         // CITEAUTHOR:  author
117         // CITEYEAR:    year
118         // CITEYEARPAR: (year)
119         // jurabib supports these plus
120         // CITE:        author/<before field>
121
122         // We don't currently use the full or forceUCase fields.
123         string cite_type = biblio::asValidLatexCommand(citeType, engine);
124         if (cite_type[0] == 'C')
125                 cite_type = string(1, 'c') + cite_type.substr(1);
126         if (cite_type[cite_type.size() - 1] == '*')
127                 cite_type = cite_type.substr(0, cite_type.size() - 1);
128
129         string before_str;
130         if (!before.empty()) {
131                 // In CITET and CITEALT mode, the "before" string is
132                 // attached to the label associated with each and every key.
133                 // In CITEP, CITEALP and CITEYEARPAR mode, it is attached
134                 // to the front of the whole only.
135                 // In other modes, it is not used at all.
136                 if (cite_type == "citet" ||
137                     cite_type == "citealt" ||
138                     cite_type == "citep" ||
139                     cite_type == "citealp" ||
140                     cite_type == "citeyearpar")
141                         before_str = before + ' ';
142                 // In CITE (jurabib), the "before" string is used to attach
143                 // the annotator (of legal texts) to the author(s) of the
144                 // first reference.
145                 else if (cite_type == "cite")
146                         before_str = '/' + before;
147         }
148
149         string after_str;
150         if (!after.empty()) {
151                 // The "after" key is appended only to the end of the whole.
152                 after_str = ", " + after;
153         }
154
155         // One day, these might be tunable (as they are in BibTeX).
156         char const op  = '('; // opening parenthesis.
157         char const cp  = ')'; // closing parenthesis.
158         // puctuation mark separating citation entries.
159         char const * const sep = ";";
160
161         string const op_str(' ' + string(1, op));
162         string const cp_str(string(1, cp) + ' ');
163         string const sep_str(string(sep) + ' ');
164
165         string label;
166         vector<string> keys = getVectorFromString(keyList);
167         vector<string>::const_iterator it  = keys.begin();
168         vector<string>::const_iterator end = keys.end();
169         for (; it != end; ++it) {
170                 // get the bibdata corresponding to the key
171                 string const author(biblio::getAbbreviatedAuthor(infomap, *it));
172                 string const year(biblio::getYear(infomap, *it));
173
174                 // Something isn't right. Fail safely.
175                 if (author.empty() || year.empty())
176                         return string();
177
178                 // authors1/<before>;  ... ;
179                 //  authors_last, <after>
180                 if (cite_type == "cite" && engine == biblio::ENGINE_JURABIB) {
181                         if (it == keys.begin())
182                                 label += author + before_str + sep_str;
183                         else
184                                 label += author + sep_str;
185
186                 // (authors1 (<before> year);  ... ;
187                 //  authors_last (<before> year, <after>)
188                 } else if (cite_type == "citet") {
189                         switch (engine) {
190                         case biblio::ENGINE_NATBIB_AUTHORYEAR:
191                                 label += author + op_str + before_str +
192                                         year + cp + sep_str;
193                                 break;
194                         case biblio::ENGINE_NATBIB_NUMERICAL:
195                                 label += author + op_str + before_str +
196                                         '#' + *it + cp + sep_str;
197                                 break;
198                         case biblio::ENGINE_JURABIB:
199                                 label += before_str + author + op_str +
200                                         year + cp + sep_str;
201                                 break;
202                         case biblio::ENGINE_BASIC:
203                                 break;
204                         }
205
206                 // author, year; author, year; ...
207                 } else if (cite_type == "citep" ||
208                            cite_type == "citealp") {
209                         if (engine == biblio::ENGINE_NATBIB_NUMERICAL) {
210                                 label += *it + sep_str;
211                         } else {
212                                 label += author + ", " + year + sep_str;
213                         }
214
215                 // (authors1 <before> year;
216                 //  authors_last <before> year, <after>)
217                 } else if (cite_type == "citealt") {
218                         switch (engine) {
219                         case biblio::ENGINE_NATBIB_AUTHORYEAR:
220                                 label += author + ' ' + before_str +
221                                         year + sep_str;
222                                 break;
223                         case biblio::ENGINE_NATBIB_NUMERICAL:
224                                 label += author + ' ' + before_str +
225                                         '#' + *it + sep_str;
226                                 break;
227                         case biblio::ENGINE_JURABIB:
228                                 label += before_str + author + ' ' +
229                                         year + sep_str;
230                                 break;
231                         case biblio::ENGINE_BASIC:
232                                 break;
233                         }
234
235                 // author; author; ...
236                 } else if (cite_type == "citeauthor") {
237                         label += author + sep_str;
238
239                 // year; year; ...
240                 } else if (cite_type == "citeyear" ||
241                            cite_type == "citeyearpar") {
242                         label += year + sep_str;
243                 }
244         }
245         label = rtrim(rtrim(label), sep);
246
247         if (!after_str.empty()) {
248                 if (cite_type == "citet") {
249                         // insert "after" before last ')'
250                         label.insert(label.size() - 1, after_str);
251                 } else {
252                         bool const add =
253                                 !(engine == biblio::ENGINE_NATBIB_NUMERICAL &&
254                                   (cite_type == "citeauthor" ||
255                                    cite_type == "citeyear"));
256                         if (add)
257                                 label += after_str;
258                 }
259         }
260
261         if (!before_str.empty() && (cite_type == "citep" ||
262                                     cite_type == "citealp" ||
263                                     cite_type == "citeyearpar")) {
264                 label = before_str + label;
265         }
266
267         if (cite_type == "citep" || cite_type == "citeyearpar")
268                 label = string(1, op) + label + string(1, cp);
269
270         return label;
271 }
272
273
274 string const getBasicLabel(string const & keyList, string const & after)
275 {
276         string keys(keyList);
277         string label;
278
279         if (contains(keys, ',')) {
280                 // Final comma allows while loop to cover all keys
281                 keys = ltrim(split(keys, label, ',')) + ',';
282                 while (contains(keys, ',')) {
283                         string key;
284                         keys = ltrim(split(keys, key, ','));
285                         label += ", " + key;
286                 }
287         } else
288                 label = keys;
289
290         if (!after.empty())
291                 label += ", " + after;
292
293         return '[' + label + ']';
294 }
295
296 } // anon namespace
297
298
299 InsetCitation::InsetCitation(InsetCommandParams const & p)
300         : InsetCommand(p, "citation")
301 {}
302
303
304 string const InsetCitation::generateLabel(Buffer const & buffer) const
305 {
306         string const before = getSecOptions();
307         string const after  = getOptions();
308
309         string label;
310         biblio::CiteEngine const engine = buffer.params().cite_engine;
311         if (engine != biblio::ENGINE_BASIC) {
312                 label = getNatbibLabel(buffer, getCmdName(), getContents(),
313                                        before, after, engine);
314         }
315
316         // Fallback to fail-safe
317         if (label.empty()) {
318                 label = getBasicLabel(getContents(), after);
319         }
320
321         return label;
322 }
323
324
325 string const InsetCitation::getScreenLabel(Buffer const & buffer) const
326 {
327         biblio::CiteEngine const engine = biblio::getEngine(buffer);
328         if (cache.params == params() && cache.engine == engine)
329                 return cache.screen_label;
330
331         // The label has changed, so we have to re-create it.
332         string const before = getSecOptions();
333         string const after  = getOptions();
334
335         string const glabel = generateLabel(buffer);
336
337         unsigned int const maxLabelChars = 45;
338
339         string label = glabel;
340         if (label.size() > maxLabelChars) {
341                 label.erase(maxLabelChars-3);
342                 label += "...";
343         }
344
345         cache.engine  = engine;
346         cache.params = params();
347         cache.generated_label = glabel;
348         cache.screen_label = label;
349
350         return label;
351 }
352
353
354 int InsetCitation::plaintext(Buffer const & buffer, ostream & os, OutputParams const &) const
355 {
356         if (cache.params == params() &&
357             cache.engine == biblio::getEngine(buffer))
358                 os << cache.generated_label;
359         else
360                 os << generateLabel(buffer);
361         return 0;
362 }
363
364
365 namespace {
366
367 string const cleanupWhitespace(string const & citelist)
368 {
369         string::const_iterator it  = citelist.begin();
370         string::const_iterator end = citelist.end();
371         // Paranoia check: make sure that there is no whitespace in here
372         // -- at least not behind commas or at the beginning
373         string result;
374         char last = ',';
375         for (; it != end; ++it) {
376                 if (*it != ' ')
377                         last = *it;
378                 if (*it != ' ' || last != ',')
379                         result += *it;
380         }
381         return result;
382 }
383
384 // end anon namyspace
385 }
386
387 int InsetCitation::docbook(Buffer const &, ostream & os, OutputParams const &) const
388 {
389         os << "<citation>" << cleanupWhitespace(getContents()) << "</citation>";
390         return 0;
391 }
392
393
394 int InsetCitation::textString(Buffer const & buf, ostream & os,
395                        OutputParams const & op) const
396 {
397         return plaintext(buf, os, op);
398 }
399
400
401 // Have to overwrite the default InsetCommand method in order to check that
402 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
403 // citations and then changes his mind, turning natbib support off. The output
404 // should revert to \cite[]{}
405 int InsetCitation::latex(Buffer const & buffer, ostream & os,
406                          OutputParams const &) const
407 {
408         biblio::CiteEngine const cite_engine = buffer.params().cite_engine;
409         string const cite_str =
410                 biblio::asValidLatexCommand(getCmdName(), cite_engine);
411
412         os << "\\" << cite_str;
413
414         string const before = getSecOptions();
415         string const after  = getOptions();
416         if (!before.empty() && cite_engine != biblio::ENGINE_BASIC)
417                 os << '[' << before << "][" << after << ']';
418         else if (!after.empty())
419                 os << '[' << after << ']';
420
421         os << '{' << cleanupWhitespace(getContents()) << '}';
422
423         return 0;
424 }
425
426
427 void InsetCitation::validate(LaTeXFeatures & features) const
428 {
429         switch (features.bufferParams().cite_engine) {
430         case biblio::ENGINE_BASIC:
431                 break;
432         case biblio::ENGINE_NATBIB_AUTHORYEAR:
433         case biblio::ENGINE_NATBIB_NUMERICAL:
434                 features.require("natbib");
435                 break;
436         case biblio::ENGINE_JURABIB:
437                 features.require("jurabib");
438                 break;
439         }
440 }