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