]> git.lyx.org Git - lyx.git/blob - src/insets/InsetCitation.cpp
do what the FIXME suggested
[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 "EmbeddedFiles.h"
20 #include "FuncRequest.h"
21 #include "LaTeXFeatures.h"
22 #include "ParIterator.h"
23 #include "TocBackend.h"
24
25 #include "support/debug.h"
26 #include "support/docstream.h"
27 #include "support/gettext.h"
28 #include "support/lstrings.h"
29
30 #include <algorithm>
31
32 using namespace std;
33 using namespace lyx::support;
34
35 namespace lyx {
36
37 namespace {
38
39 vector<string> const init_possible_cite_commands()
40 {
41         char const * const possible[] = {
42                 "cite", "nocite", "citet", "citep", "citealt", "citealp",
43                 "citeauthor", "citeyear", "citeyearpar",
44                 "citet*", "citep*", "citealt*", "citealp*", "citeauthor*",
45                 "Citet",  "Citep",  "Citealt",  "Citealp",  "Citeauthor",
46                 "Citet*", "Citep*", "Citealt*", "Citealp*", "Citeauthor*",
47                 "fullcite",
48                 "footcite", "footcitet", "footcitep", "footcitealt",
49                 "footcitealp", "footciteauthor", "footciteyear", "footciteyearpar",
50                 "citefield", "citetitle", "cite*"
51         };
52         size_t const size_possible = sizeof(possible) / sizeof(possible[0]);
53
54         return vector<string>(possible, possible + size_possible);
55 }
56
57
58 vector<string> const & possible_cite_commands()
59 {
60         static vector<string> const possible = init_possible_cite_commands();
61         return possible;
62 }
63
64
65 //FIXME See the header for the issue.
66 string const default_cite_command(biblio::CiteEngine engine)
67 {
68         string str;
69         switch (engine) {
70                 case biblio::ENGINE_BASIC:
71                         str = "cite";
72                         break;
73                 case biblio::ENGINE_NATBIB_AUTHORYEAR:
74                         str = "citet";
75                         break;
76                 case biblio::ENGINE_NATBIB_NUMERICAL:
77                         str = "citep";
78                         break;
79                 case biblio::ENGINE_JURABIB:
80                         str = "cite";
81                         break;
82         }
83         return str;
84 }
85
86                 
87 string const 
88                 asValidLatexCommand(string const & input, biblio::CiteEngine const engine)
89 {
90         string const default_str = default_cite_command(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 getComplexLabel(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 const getBasicLabel(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         if (!after.empty())
372                 label += ", " + after;
373
374         return '[' + label + ']';
375 }
376
377 } // anon namespace
378
379
380 ParamInfo InsetCitation::param_info_;
381
382
383 InsetCitation::InsetCitation(InsetCommandParams const & p)
384         : InsetCommand(p, "citation")
385 {}
386
387
388 ParamInfo const & InsetCitation::findInfo(string const & /* cmdName */)
389 {
390         // standard cite does only take one argument if jurabib is
391         // not used, but jurabib extends this to two arguments, so
392         // we have to allow both here. InsetCitation takes care that
393         // LaTeX output is nevertheless correct.
394         if (param_info_.empty()) {
395                 param_info_.add("after", ParamInfo::LATEX_OPTIONAL);
396                 param_info_.add("before", ParamInfo::LATEX_OPTIONAL);
397                 param_info_.add("key", ParamInfo::LATEX_REQUIRED);
398         }
399         return param_info_;
400 }
401
402
403 bool InsetCitation::isCompatibleCommand(string const & cmd)
404 {
405         vector<string> const & possibles = possible_cite_commands();
406         vector<string>::const_iterator const end = possibles.end();
407         return find(possibles.begin(), end, cmd) != end;
408 }
409
410
411 docstring InsetCitation::generateLabel() const
412 {
413         docstring const before = getParam("before");
414         docstring const after  = getParam("after");
415
416         docstring label;
417         biblio::CiteEngine const engine = buffer().params().getEngine();
418         label = getComplexLabel(buffer(), getCmdName(), getParam("key"),
419                                before, after, engine);
420
421         // Fallback to fail-safe
422         if (label.empty())
423                 label = getBasicLabel(getParam("key"), after);
424
425         return label;
426 }
427
428
429 docstring InsetCitation::screenLabel() const
430 {
431         return cache.screen_label;
432 }
433
434
435 void InsetCitation::updateLabels(ParIterator const &)
436 {
437         biblio::CiteEngine const engine = buffer().params().getEngine();
438         if (cache.params == params() && cache.engine == engine)
439                 return;
440
441         // The label has changed, so we have to re-create it.
442         docstring const glabel = generateLabel();
443
444         unsigned int const maxLabelChars = 45;
445
446         docstring label = glabel;
447         if (label.size() > maxLabelChars) {
448                 label.erase(maxLabelChars-3);
449                 label += "...";
450         }
451
452         cache.engine  = engine;
453         cache.params = params();
454         cache.generated_label = glabel;
455         cache.screen_label = label;
456 }
457
458
459 void InsetCitation::addToToc(ParConstIterator const & cpit) const
460 {
461         Toc & toc = buffer().tocBackend().toc("citation");
462         toc.push_back(TocItem(cpit, 0, cache.screen_label));
463 }
464
465
466 int InsetCitation::plaintext(odocstream & os, OutputParams const &) const
467 {
468         docstring str;
469
470         if (cache.params == params() &&
471             cache.engine == buffer().params().getEngine())
472                 str = cache.generated_label;
473         else
474                 str = generateLabel();
475
476         os << str;
477         return str.size();
478 }
479
480
481 static docstring const cleanupWhitespace(docstring const & citelist)
482 {
483         docstring::const_iterator it  = citelist.begin();
484         docstring::const_iterator end = citelist.end();
485         // Paranoia check: make sure that there is no whitespace in here
486         // -- at least not behind commas or at the beginning
487         docstring result;
488         char_type last = ',';
489         for (; it != end; ++it) {
490                 if (*it != ' ')
491                         last = *it;
492                 if (*it != ' ' || last != ',')
493                         result += *it;
494         }
495         return result;
496 }
497
498
499 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
500 {
501         os << from_ascii("<citation>")
502            << cleanupWhitespace(getParam("key"))
503            << from_ascii("</citation>");
504         return 0;
505 }
506
507
508 void InsetCitation::textString(odocstream & os) const
509 {
510         plaintext(os, OutputParams(0));
511 }
512
513
514 // Have to overwrite the default InsetCommand method in order to check that
515 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
516 // citations and then changes his mind, turning natbib support off. The output
517 // should revert to \cite[]{}
518 int InsetCitation::latex(odocstream & os, OutputParams const &) const
519 {
520         biblio::CiteEngine cite_engine = buffer().params().getEngine();
521         // FIXME UNICODE
522         docstring const cite_str = from_utf8(
523                 asValidLatexCommand(getCmdName(), cite_engine));
524
525         os << "\\" << cite_str;
526
527         docstring const & before = getParam("before");
528         docstring const & after  = getParam("after");
529         if (!before.empty() && cite_engine != biblio::ENGINE_BASIC)
530                 os << '[' << before << "][" << after << ']';
531         else if (!after.empty())
532                 os << '[' << after << ']';
533
534         os << '{' << cleanupWhitespace(getParam("key")) << '}';
535
536         return 0;
537 }
538
539
540 void InsetCitation::validate(LaTeXFeatures & features) const
541 {
542         switch (features.bufferParams().getEngine()) {
543         case biblio::ENGINE_BASIC:
544                 break;
545         case biblio::ENGINE_NATBIB_AUTHORYEAR:
546         case biblio::ENGINE_NATBIB_NUMERICAL:
547                 features.require("natbib");
548                 break;
549         case biblio::ENGINE_JURABIB:
550                 features.require("jurabib");
551                 break;
552         }
553 }
554
555
556 } // namespace lyx