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