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