]> git.lyx.org Git - lyx.git/blob - src/insets/InsetCitation.cpp
earder cleanup; cosmetics;
[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 & possibleCiteCommands()
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 defaultCiteCommand(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 asValidLatexCommand(string const & input, biblio::CiteEngine const engine)
89 {
90         string const default_str = defaultCiteCommand(engine);
91         if (!InsetCitation::isCompatibleCommand(input))
92                 return default_str;
93
94         string output;
95         switch (engine) {
96                 case biblio::ENGINE_BASIC:
97                         output = input;
98                         break;
99
100                 case biblio::ENGINE_NATBIB_AUTHORYEAR:
101                 case biblio::ENGINE_NATBIB_NUMERICAL:
102                         if (input == "cite" || input == "citefield" ||
103                                                         input == "citetitle" || input == "cite*")
104                                 output = default_str;
105                         else if (prefixIs(input, "foot"))
106                                 output = input.substr(4);
107                         else
108                                 output = input;
109                         break;
110
111                 case biblio::ENGINE_JURABIB: {
112                         // Jurabib does not support the 'uppercase' natbib style.
113                         if (input[0] == 'C')
114                                 output = string(1, 'c') + input.substr(1);
115                         else
116                                 output = input;
117
118                         // Jurabib does not support the 'full' natbib style.
119                         string::size_type const n = output.size() - 1;
120                         if (output != "cite*" && output[n] == '*')
121                                 output = output.substr(0, n);
122
123                         break;
124                 }
125         }
126
127         return output;
128 }
129
130
131 docstring complexLabel(Buffer const & buffer,
132                             string const & citeType, docstring const & keyList,
133                             docstring const & before, docstring const & after,
134                             biblio::CiteEngine engine)
135 {
136         // Only start the process off after the buffer is loaded from file.
137         if (!buffer.isFullyLoaded())
138                 return docstring();
139
140         // Cache the labels
141         typedef map<Buffer const *, BiblioInfo> CachedMap;
142         static CachedMap cached_keys;
143
144         // and cache the timestamp of the bibliography files.
145         static map<FileName, time_t> bibfileStatus;
146
147         BiblioInfo biblist;
148
149         EmbeddedFileList const & bibfilesCache = buffer.getBibfilesCache();
150         // compare the cached timestamps with the actual ones.
151         bool changed = false;
152         for (EmbeddedFileList::const_iterator it = bibfilesCache.begin();
153                         it != bibfilesCache.end(); ++ it) {
154                 FileName const f = *it;
155                 time_t lastw = f.lastModified();
156                 if (lastw != bibfileStatus[f]) {
157                         changed = true;
158                         bibfileStatus[f] = lastw;
159                 }
160         }
161
162         // build the list only if the bibfiles have been changed
163         if (cached_keys[&buffer].empty() || bibfileStatus.empty() || changed) {
164                 biblist.fillWithBibKeys(&buffer);
165                 cached_keys[&buffer] = biblist;
166         } else {
167                 // use the cached keys
168                 biblist = cached_keys[&buffer];
169         }
170
171         if (biblist.empty())
172                 return docstring();
173
174         // the natbib citation-styles
175         // CITET:       author (year)
176         // CITEP:       (author,year)
177         // CITEALT:     author year
178         // CITEALP:     author, year
179         // CITEAUTHOR:  author
180         // CITEYEAR:    year
181         // CITEYEARPAR: (year)
182         // jurabib supports these plus
183         // CITE:        author/<before field>
184
185         // We don't currently use the full or forceUCase fields.
186         string cite_type = asValidLatexCommand(citeType, engine);
187         if (cite_type[0] == 'C')
188                 //If we were going to use them, this would mean ForceUCase
189                 cite_type = string(1, 'c') + cite_type.substr(1);
190         if (cite_type[cite_type.size() - 1] == '*')
191                 //and this would mean FULL
192                 cite_type = cite_type.substr(0, cite_type.size() - 1);
193
194         docstring before_str;
195         if (!before.empty()) {
196                 // In CITET and CITEALT mode, the "before" string is
197                 // attached to the label associated with each and every key.
198                 // In CITEP, CITEALP and CITEYEARPAR mode, it is attached
199                 // to the front of the whole only.
200                 // In other modes, it is not used at all.
201                 if (cite_type == "citet" ||
202                     cite_type == "citealt" ||
203                     cite_type == "citep" ||
204                     cite_type == "citealp" ||
205                     cite_type == "citeyearpar")
206                         before_str = before + ' ';
207                 // In CITE (jurabib), the "before" string is used to attach
208                 // the annotator (of legal texts) to the author(s) of the
209                 // first reference.
210                 else if (cite_type == "cite")
211                         before_str = '/' + before;
212         }
213
214         docstring after_str;
215         // The "after" key is appended only to the end of the whole.
216         if (cite_type == "nocite")
217                 after_str =  " (" + _("not cited") + ')';
218         else if (!after.empty()) {
219                 after_str = ", " + after;
220         }
221
222         // One day, these might be tunable (as they are in BibTeX).
223         char op, cp;    // opening and closing parenthesis.
224         char * sep;     // punctuation mark separating citation entries.
225         if (engine == biblio::ENGINE_BASIC) {
226                 op  = '[';
227                 cp  = ']';
228                 sep = ",";
229         } else {
230                 op  = '(';
231                 cp  = ')';
232                 sep = ";";
233         }
234
235         docstring const op_str = ' ' + docstring(1, op);
236         docstring const cp_str = docstring(1, cp) + ' ';
237         docstring const sep_str = from_ascii(sep) + ' ';
238
239         docstring label;
240         vector<docstring> keys = getVectorFromString(keyList);
241         vector<docstring>::const_iterator it  = keys.begin();
242         vector<docstring>::const_iterator end = keys.end();
243         for (; it != end; ++it) {
244                 // get the bibdata corresponding to the key
245                 docstring const author(biblist.getAbbreviatedAuthor(*it));
246                 docstring const year(biblist.getYear(*it));
247
248                 // Something isn't right. Fail safely.
249                 if (author.empty() || year.empty())
250                         return docstring();
251
252                 // authors1/<before>;  ... ;
253                 //  authors_last, <after>
254                 if (cite_type == "cite") {
255                         if (engine == biblio::ENGINE_BASIC) {
256                                 label += *it + sep_str;
257                         } else if (engine == biblio::ENGINE_JURABIB) {
258                                 if (it == keys.begin())
259                                         label += author + before_str + sep_str;
260                                 else
261                                         label += author + sep_str;
262                         }
263
264                 // nocite
265                 } else if (cite_type == "nocite") {
266                         label += *it + sep_str;
267
268                 // (authors1 (<before> year);  ... ;
269                 //  authors_last (<before> year, <after>)
270                 } else if (cite_type == "citet") {
271                         switch (engine) {
272                         case biblio::ENGINE_NATBIB_AUTHORYEAR:
273                                 label += author + op_str + before_str +
274                                         year + cp + sep_str;
275                                 break;
276                         case biblio::ENGINE_NATBIB_NUMERICAL:
277                                 label += author + op_str + before_str + '#' + *it + cp + sep_str;
278                                 break;
279                         case biblio::ENGINE_JURABIB:
280                                 label += before_str + author + op_str +
281                                         year + cp + sep_str;
282                                 break;
283                         case biblio::ENGINE_BASIC:
284                                 break;
285                         }
286
287                 // author, year; author, year; ...
288                 } else if (cite_type == "citep" ||
289                            cite_type == "citealp") {
290                         if (engine == biblio::ENGINE_NATBIB_NUMERICAL) {
291                                 label += *it + sep_str;
292                         } else {
293                                 label += author + ", " + year + sep_str;
294                         }
295
296                 // (authors1 <before> year;
297                 //  authors_last <before> year, <after>)
298                 } else if (cite_type == "citealt") {
299                         switch (engine) {
300                         case biblio::ENGINE_NATBIB_AUTHORYEAR:
301                                 label += author + ' ' + before_str +
302                                         year + sep_str;
303                                 break;
304                         case biblio::ENGINE_NATBIB_NUMERICAL:
305                                 label += author + ' ' + before_str + '#' + *it + sep_str;
306                                 break;
307                         case biblio::ENGINE_JURABIB:
308                                 label += before_str + author + ' ' +
309                                         year + sep_str;
310                                 break;
311                         case biblio::ENGINE_BASIC:
312                                 break;
313                         }
314
315                 // author; author; ...
316                 } else if (cite_type == "citeauthor") {
317                         label += author + sep_str;
318
319                 // year; year; ...
320                 } else if (cite_type == "citeyear" ||
321                            cite_type == "citeyearpar") {
322                         label += year + sep_str;
323                 }
324         }
325         label = rtrim(rtrim(label), sep);
326
327         if (!after_str.empty()) {
328                 if (cite_type == "citet") {
329                         // insert "after" before last ')'
330                         label.insert(label.size() - 1, after_str);
331                 } else {
332                         bool const add =
333                                 !(engine == biblio::ENGINE_NATBIB_NUMERICAL &&
334                                   (cite_type == "citeauthor" ||
335                                    cite_type == "citeyear"));
336                         if (add)
337                                 label += after_str;
338                 }
339         }
340
341         if (!before_str.empty() && (cite_type == "citep" ||
342                                     cite_type == "citealp" ||
343                                     cite_type == "citeyearpar")) {
344                 label = before_str + label;
345         }
346
347         if (cite_type == "citep" || cite_type == "citeyearpar" || 
348             (cite_type == "cite" && engine == biblio::ENGINE_BASIC) )
349                 label = op + label + cp;
350
351         return label;
352 }
353
354
355 docstring basicLabel(docstring const & keyList, docstring const & after)
356 {
357         docstring keys = keyList;
358         docstring label;
359
360         if (contains(keys, ',')) {
361                 // Final comma allows while loop to cover all keys
362                 keys = ltrim(split(keys, label, ',')) + ',';
363                 while (contains(keys, ',')) {
364                         docstring key;
365                         keys = ltrim(split(keys, key, ','));
366                         label += ", " + key;
367                 }
368         } else {
369                 label = keys;
370         }
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 = possibleCiteCommands();
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().citeEngine();
419         label = complexLabel(buffer(), getCmdName(), getParam("key"),
420                                before, after, engine);
421
422         // Fallback to fail-safe
423         if (label.empty())
424                 label = basicLabel(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().citeEngine();
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().citeEngine();
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().citeEngine()) {
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