]> git.lyx.org Git - lyx.git/blob - src/insets/InsetCitation.cpp
020e2b36891ebd2c7f38606d321a3eaa9bd02d0b
[lyx.git] / src / insets / InsetCitation.cpp
1 /**
2  * \file InsetCitation.cpp
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 "InsetCitation.h"
15
16 #include "Buffer.h"
17 #include "BufferParams.h"
18 #include "debug.h"
19 #include "DispatchResult.h"
20 #include "FuncRequest.h"
21 #include "LaTeXFeatures.h"
22
23 #include "support/fs_extras.h"
24 #include "support/lstrings.h"
25
26 #include <algorithm>
27
28 #include <boost/filesystem/operations.hpp>
29 #include <boost/filesystem/exception.hpp>
30
31
32 namespace lyx {
33
34 using support::FileName;
35 using support::getStringFromVector;
36 using support::getVectorFromString;
37 using support::ltrim;
38 using support::prefixIs;
39 using support::rtrim;
40 using support::split;
41 using support::tokenPos;
42
43 using std::endl;
44 using std::string;
45 using std::vector;
46
47 namespace fs = boost::filesystem;
48
49
50 namespace {
51
52 vector<string> const init_possible_cite_commands()
53 {
54         char const * const possible[] = {
55                 "cite", "citet", "citep", "citealt", "citealp",
56                 "citeauthor", "citeyear", "citeyearpar",
57                 "citet*", "citep*", "citealt*", "citealp*", "citeauthor*",
58                 "Citet",  "Citep",  "Citealt",  "Citealp",  "Citeauthor",
59                 "Citet*", "Citep*", "Citealt*", "Citealp*", "Citeauthor*",
60                 "fullcite",
61                 "footcite", "footcitet", "footcitep", "footcitealt",
62                 "footcitealp", "footciteauthor", "footciteyear", "footciteyearpar",
63                 "citefield", "citetitle", "cite*"
64         };
65         size_t const size_possible = sizeof(possible) / sizeof(possible[0]);
66
67         return vector<string>(possible, possible + size_possible);
68 }
69
70
71 vector<string> const & possible_cite_commands()
72 {
73         static vector<string> const possible = init_possible_cite_commands();
74         return possible;
75 }
76
77
78 bool is_possible_cite_command(string const & input)
79 {
80         vector<string> const & possibles = possible_cite_commands();
81         vector<string>::const_iterator const end = possibles.end();
82         return std::find(possibles.begin(), end, input) != end;
83 }
84
85
86 string const default_cite_command(biblio::CiteEngine engine)
87 {
88         string str;
89         switch (engine) {
90                 case biblio::ENGINE_BASIC:
91                         str = "cite";
92                         break;
93                 case biblio::ENGINE_NATBIB_AUTHORYEAR:
94                         str = "citet";
95                         break;
96                 case biblio::ENGINE_NATBIB_NUMERICAL:
97                         str = "citep";
98                         break;
99                 case biblio::ENGINE_JURABIB:
100                         str = "cite";
101                         break;
102         }
103         return str;
104 }
105
106                 
107 string const 
108                 asValidLatexCommand(string const & input, biblio::CiteEngine const engine)
109 {
110         string const default_str = default_cite_command(engine);
111         if (!is_possible_cite_command(input))
112                 return default_str;
113
114         string output;
115         switch (engine) {
116                 case biblio::ENGINE_BASIC:
117                         output = default_str;
118                         break;
119
120                 case biblio::ENGINE_NATBIB_AUTHORYEAR:
121                 case biblio::ENGINE_NATBIB_NUMERICAL:
122                         if (input == "cite" || input == "citefield" ||
123                                                         input == "citetitle" || input == "cite*")
124                                 output = default_str;
125                         else if (prefixIs(input, "foot"))
126                                 output = input.substr(4);
127                         else
128                                 output = input;
129                         break;
130
131                         case biblio::ENGINE_JURABIB: {
132                 // Jurabib does not support the 'uppercase' natbib style.
133                                 if (input[0] == 'C')
134                                         output = string(1, 'c') + input.substr(1);
135                                 else
136                                         output = input;
137
138                 // Jurabib does not support the 'full' natbib style.
139                                 string::size_type const n = output.size() - 1;
140                                 if (output != "cite*" && output[n] == '*')
141                                         output = output.substr(0, n);
142
143                                 break;
144                         }
145         }
146
147         return output;
148 }
149
150
151 docstring const getNatbibLabel(Buffer const & buffer,
152                             string const & citeType, docstring const & keyList,
153                             docstring const & before, docstring const & after,
154                             biblio::CiteEngine engine)
155 {
156         // Only start the process off after the buffer is loaded from file.
157         if (!buffer.fully_loaded())
158                 return docstring();
159
160         // Cache the labels
161         typedef std::map<Buffer const *, BiblioInfo> CachedMap;
162         static CachedMap cached_keys;
163
164         // and cache the timestamp of the bibliography files.
165         static std::map<FileName, time_t> bibfileStatus;
166
167         BiblioInfo biblist;
168
169         vector<FileName> const & bibfilesCache = buffer.getBibfilesCache();
170         // compare the cached timestamps with the actual ones.
171         bool changed = false;
172         for (vector<FileName>::const_iterator it = bibfilesCache.begin();
173                         it != bibfilesCache.end(); ++ it) {
174                 FileName const f = *it;
175                 try {
176                         std::time_t lastw = fs::last_write_time(f.toFilesystemEncoding());
177                         if (lastw != bibfileStatus[f]) {
178                                 changed = true;
179                                 bibfileStatus[f] = lastw;
180                         }
181                 }
182                 catch (fs::filesystem_error & fserr) {
183                         changed = true;
184                         lyxerr << "Couldn't find or read bibtex file "
185                                << f << endl;
186                         LYXERR(Debug::DEBUG) << "Fs error: "
187                                              << fserr.what() << endl;
188                 }
189         }
190
191         // build the list only if the bibfiles have been changed
192         if (cached_keys[&buffer].empty() || bibfileStatus.empty() || changed) {
193                 biblist.fillWithBibKeys(&buffer);
194                 cached_keys[&buffer] = biblist;
195         } else
196                 // use the cached keys
197                 biblist = cached_keys[&buffer];
198
199         if (biblist.empty())
200                 return docstring();
201
202         // the natbib citation-styles
203         // CITET:       author (year)
204         // CITEP:       (author,year)
205         // CITEALT:     author year
206         // CITEALP:     author, year
207         // CITEAUTHOR:  author
208         // CITEYEAR:    year
209         // CITEYEARPAR: (year)
210         // jurabib supports these plus
211         // CITE:        author/<before field>
212
213         // We don't currently use the full or forceUCase fields.
214         string cite_type = asValidLatexCommand(citeType, engine);
215         if (cite_type[0] == 'C')
216                 //If we were going to use them, this would mean ForceUCase
217                 cite_type = string(1, 'c') + cite_type.substr(1);
218         if (cite_type[cite_type.size() - 1] == '*')
219                 //and this would mean FULL
220                 cite_type = cite_type.substr(0, cite_type.size() - 1);
221
222         docstring before_str;
223         if (!before.empty()) {
224                 // In CITET and CITEALT mode, the "before" string is
225                 // attached to the label associated with each and every key.
226                 // In CITEP, CITEALP and CITEYEARPAR mode, it is attached
227                 // to the front of the whole only.
228                 // In other modes, it is not used at all.
229                 if (cite_type == "citet" ||
230                     cite_type == "citealt" ||
231                     cite_type == "citep" ||
232                     cite_type == "citealp" ||
233                     cite_type == "citeyearpar")
234                         before_str = before + ' ';
235                 // In CITE (jurabib), the "before" string is used to attach
236                 // the annotator (of legal texts) to the author(s) of the
237                 // first reference.
238                 else if (cite_type == "cite")
239                         before_str = '/' + before;
240         }
241
242         docstring after_str;
243         if (!after.empty()) {
244                 // The "after" key is appended only to the end of the whole.
245                 after_str = ", " + after;
246         }
247
248         // One day, these might be tunable (as they are in BibTeX).
249         char const op  = '('; // opening parenthesis.
250         char const cp  = ')'; // closing parenthesis.
251         // puctuation mark separating citation entries.
252         char const * const sep = ";";
253
254         docstring const op_str(' ' + docstring(1, op));
255         docstring const cp_str(docstring(1, cp) + ' ');
256         docstring const sep_str(from_ascii(sep) + ' ');
257
258         docstring label;
259         vector<docstring> keys = getVectorFromString(keyList);
260         vector<docstring>::const_iterator it  = keys.begin();
261         vector<docstring>::const_iterator end = keys.end();
262         for (; it != end; ++it) {
263                 // get the bibdata corresponding to the key
264                 docstring const author(biblist.getAbbreviatedAuthor(*it));
265                 docstring const year(biblist.getYear(*it));
266
267                 // Something isn't right. Fail safely.
268                 if (author.empty() || year.empty())
269                         return docstring();
270
271                 // authors1/<before>;  ... ;
272                 //  authors_last, <after>
273                 if (cite_type == "cite" && engine == biblio::ENGINE_JURABIB) {
274                         if (it == keys.begin())
275                                 label += author + before_str + sep_str;
276                         else
277                                 label += author + sep_str;
278
279                 // (authors1 (<before> year);  ... ;
280                 //  authors_last (<before> year, <after>)
281                 } else if (cite_type == "citet") {
282                         switch (engine) {
283                         case biblio::ENGINE_NATBIB_AUTHORYEAR:
284                                 label += author + op_str + before_str +
285                                         year + cp + sep_str;
286                                 break;
287                         case biblio::ENGINE_NATBIB_NUMERICAL:
288                                 label += author + op_str + before_str + '#' + *it + cp + sep_str;
289                                 break;
290                         case biblio::ENGINE_JURABIB:
291                                 label += before_str + author + op_str +
292                                         year + cp + sep_str;
293                                 break;
294                         case biblio::ENGINE_BASIC:
295                                 break;
296                         }
297
298                 // author, year; author, year; ...
299                 } else if (cite_type == "citep" ||
300                            cite_type == "citealp") {
301                         if (engine == biblio::ENGINE_NATBIB_NUMERICAL) {
302                                 label += *it + sep_str;
303                         } else {
304                                 label += author + ", " + year + sep_str;
305                         }
306
307                 // (authors1 <before> year;
308                 //  authors_last <before> year, <after>)
309                 } else if (cite_type == "citealt") {
310                         switch (engine) {
311                         case biblio::ENGINE_NATBIB_AUTHORYEAR:
312                                 label += author + ' ' + before_str +
313                                         year + sep_str;
314                                 break;
315                         case biblio::ENGINE_NATBIB_NUMERICAL:
316                                 label += author + ' ' + before_str + '#' + *it + sep_str;
317                                 break;
318                         case biblio::ENGINE_JURABIB:
319                                 label += before_str + author + ' ' +
320                                         year + sep_str;
321                                 break;
322                         case biblio::ENGINE_BASIC:
323                                 break;
324                         }
325
326                 // author; author; ...
327                 } else if (cite_type == "citeauthor") {
328                         label += author + sep_str;
329
330                 // year; year; ...
331                 } else if (cite_type == "citeyear" ||
332                            cite_type == "citeyearpar") {
333                         label += year + sep_str;
334                 }
335         }
336         label = rtrim(rtrim(label), sep);
337
338         if (!after_str.empty()) {
339                 if (cite_type == "citet") {
340                         // insert "after" before last ')'
341                         label.insert(label.size() - 1, after_str);
342                 } else {
343                         bool const add =
344                                 !(engine == biblio::ENGINE_NATBIB_NUMERICAL &&
345                                   (cite_type == "citeauthor" ||
346                                    cite_type == "citeyear"));
347                         if (add)
348                                 label += after_str;
349                 }
350         }
351
352         if (!before_str.empty() && (cite_type == "citep" ||
353                                     cite_type == "citealp" ||
354                                     cite_type == "citeyearpar")) {
355                 label = before_str + label;
356         }
357
358         if (cite_type == "citep" || cite_type == "citeyearpar")
359                 label = op + label + cp;
360
361         return label;
362 }
363
364
365 docstring const getBasicLabel(docstring const & keyList, docstring const & after)
366 {
367         using support::contains;
368
369         docstring keys(keyList);
370         docstring label;
371
372         if (contains(keys, ',')) {
373                 // Final comma allows while loop to cover all keys
374                 keys = ltrim(split(keys, label, ',')) + ',';
375                 while (contains(keys, ',')) {
376                         docstring key;
377                         keys = ltrim(split(keys, key, ','));
378                         label += ", " + key;
379                 }
380         } else
381                 label = keys;
382
383         if (!after.empty())
384                 label += ", " + after;
385
386         return '[' + label + ']';
387 }
388
389 } // anon namespace
390
391
392 InsetCitation::InsetCitation(InsetCommandParams const & p)
393         : InsetCommand(p, "citation")
394 {}
395
396
397 docstring const InsetCitation::generateLabel(Buffer const & buffer) const
398 {
399         docstring const before = getParam("before");
400         docstring const after  = getParam("after");
401
402         docstring label;
403         biblio::CiteEngine const engine = buffer.params().getEngine();
404         if (engine != biblio::ENGINE_BASIC) {
405                 label = getNatbibLabel(buffer, getCmdName(), getParam("key"),
406                                        before, after, engine);
407         }
408
409         // Fallback to fail-safe
410         if (label.empty()) {
411                 label = getBasicLabel(getParam("key"), after);
412         }
413
414         return label;
415 }
416
417
418 docstring const InsetCitation::getScreenLabel(Buffer const & buffer) const
419 {
420         biblio::CiteEngine const engine = buffer.params().getEngine();
421         if (cache.params == params() && cache.engine == engine)
422                 return cache.screen_label;
423
424         // The label has changed, so we have to re-create it.
425         docstring const glabel = generateLabel(buffer);
426
427         unsigned int const maxLabelChars = 45;
428
429         docstring label = glabel;
430         if (label.size() > maxLabelChars) {
431                 label.erase(maxLabelChars-3);
432                 label += "...";
433         }
434
435         cache.engine  = engine;
436         cache.params = params();
437         cache.generated_label = glabel;
438         cache.screen_label = label;
439
440         return label;
441 }
442
443
444 int InsetCitation::plaintext(Buffer const & buffer, odocstream & os,
445                              OutputParams const &) const
446 {
447         docstring str;
448
449         if (cache.params == params() &&
450             cache.engine == buffer.params().getEngine())
451                 str = cache.generated_label;
452         else
453                 str = generateLabel(buffer);
454
455         os << str;
456         return str.size();
457 }
458
459
460 static docstring const cleanupWhitespace(docstring const & citelist)
461 {
462         docstring::const_iterator it  = citelist.begin();
463         docstring::const_iterator end = citelist.end();
464         // Paranoia check: make sure that there is no whitespace in here
465         // -- at least not behind commas or at the beginning
466         docstring result;
467         char_type last = ',';
468         for (; it != end; ++it) {
469                 if (*it != ' ')
470                         last = *it;
471                 if (*it != ' ' || last != ',')
472                         result += *it;
473         }
474         return result;
475 }
476
477
478 int InsetCitation::docbook(Buffer const &, odocstream & os,
479                            OutputParams const &) const
480 {
481         os << "<citation>"
482            << cleanupWhitespace(getParam("key"))
483            << "</citation>";
484         return 0;
485 }
486
487
488 int InsetCitation::textString(Buffer const & buf, odocstream & os,
489                        OutputParams const & op) const
490 {
491         return plaintext(buf, os, op);
492 }
493
494
495 // Have to overwrite the default InsetCommand method in order to check that
496 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
497 // citations and then changes his mind, turning natbib support off. The output
498 // should revert to \cite[]{}
499 int InsetCitation::latex(Buffer const & buffer, odocstream & os,
500                          OutputParams const &) const
501 {
502         biblio::CiteEngine cite_engine = buffer.params().getEngine();
503         // FIXME UNICODE
504         docstring const cite_str = from_utf8(
505                 asValidLatexCommand(getCmdName(), cite_engine));
506
507         os << "\\" << cite_str;
508
509         docstring const & before = getParam("before");
510         docstring const & after  = getParam("after");
511         if (!before.empty() && cite_engine != biblio::ENGINE_BASIC)
512                 os << '[' << before << "][" << after << ']';
513         else if (!after.empty())
514                 os << '[' << after << ']';
515
516         os << '{' << cleanupWhitespace(getParam("key")) << '}';
517
518         return 0;
519 }
520
521
522 void InsetCitation::validate(LaTeXFeatures & features) const
523 {
524         switch (features.bufferParams().getEngine()) {
525         case biblio::ENGINE_BASIC:
526                 break;
527         case biblio::ENGINE_NATBIB_AUTHORYEAR:
528         case biblio::ENGINE_NATBIB_NUMERICAL:
529                 features.require("natbib");
530                 break;
531         case biblio::ENGINE_JURABIB:
532                 features.require("jurabib");
533                 break;
534         }
535 }
536
537
538 void InsetCitation::replaceContents(string const & from, string const & to)
539 {
540         if (tokenPos(getContents(), ',', from) != -1) {
541                 vector<string> items = getVectorFromString(getContents());
542                 std::replace(items.begin(), items.end(), from, to);
543                 setContents(getStringFromVector(items));
544         }
545 }
546
547
548 } // namespace lyx