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