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