]> git.lyx.org Git - lyx.git/blob - src/insets/InsetCitation.cpp
Embedding: merge lyx::EmbeddedFiles to lyx::support::EmbeddedFileList
[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 "support/debug.h"
19 #include "DispatchResult.h"
20 #include "support/gettext.h"
21 #include "EmbeddedFiles.h"
22 #include "FuncRequest.h"
23 #include "LaTeXFeatures.h"
24
25 #include "support/lstrings.h"
26 #include "support/docstream.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 InsetCitation::InsetCitation(InsetCommandParams const & p)
379         : InsetCommand(p, "citation")
380 {}
381
382
383 CommandInfo const * InsetCitation::findInfo(string const & /* cmdName */)
384 {
385         // standard cite does only take one argument if jurabib is
386         // not used, but jurabib extends this to two arguments, so
387         // we have to allow both here. InsetCitation takes care that
388         // LaTeX output is nevertheless correct.
389         static const char * const paramnames[] =
390                 {"after", "before", "key", ""};
391         static const bool isoptional[] = {true, true, false};
392         static const CommandInfo info = {3, paramnames, isoptional};
393         return &info;
394 }
395
396
397 bool InsetCitation::isCompatibleCommand(string const & cmd)
398 {
399         vector<string> const & possibles = possible_cite_commands();
400         vector<string>::const_iterator const end = possibles.end();
401         return find(possibles.begin(), end, cmd) != end;
402 }
403
404
405 docstring const InsetCitation::generateLabel(Buffer const & buffer) const
406 {
407         docstring const before = getParam("before");
408         docstring const after  = getParam("after");
409
410         docstring label;
411         biblio::CiteEngine const engine = buffer.params().getEngine();
412         label = getComplexLabel(buffer, getCmdName(), getParam("key"),
413                                before, after, engine);
414
415         // Fallback to fail-safe
416         if (label.empty())
417                 label = getBasicLabel(getParam("key"), after);
418
419         return label;
420 }
421
422
423 docstring const InsetCitation::getScreenLabel(Buffer const & buffer) const
424 {
425         biblio::CiteEngine const engine = buffer.params().getEngine();
426         if (cache.params == params() && cache.engine == engine)
427                 return cache.screen_label;
428
429         // The label has changed, so we have to re-create it.
430         docstring const glabel = generateLabel(buffer);
431
432         unsigned int const maxLabelChars = 45;
433
434         docstring label = glabel;
435         if (label.size() > maxLabelChars) {
436                 label.erase(maxLabelChars-3);
437                 label += "...";
438         }
439
440         cache.engine  = engine;
441         cache.params = params();
442         cache.generated_label = glabel;
443         cache.screen_label = label;
444
445         return label;
446 }
447
448
449 int InsetCitation::plaintext(Buffer const & buffer, odocstream & os,
450                              OutputParams const &) const
451 {
452         docstring str;
453
454         if (cache.params == params() &&
455             cache.engine == buffer.params().getEngine())
456                 str = cache.generated_label;
457         else
458                 str = generateLabel(buffer);
459
460         os << str;
461         return str.size();
462 }
463
464
465 static docstring const cleanupWhitespace(docstring const & citelist)
466 {
467         docstring::const_iterator it  = citelist.begin();
468         docstring::const_iterator end = citelist.end();
469         // Paranoia check: make sure that there is no whitespace in here
470         // -- at least not behind commas or at the beginning
471         docstring result;
472         char_type last = ',';
473         for (; it != end; ++it) {
474                 if (*it != ' ')
475                         last = *it;
476                 if (*it != ' ' || last != ',')
477                         result += *it;
478         }
479         return result;
480 }
481
482
483 int InsetCitation::docbook(Buffer const &, odocstream & os,
484                            OutputParams const &) const
485 {
486         os << from_ascii("<citation>")
487            << cleanupWhitespace(getParam("key"))
488            << from_ascii("</citation>");
489         return 0;
490 }
491
492
493 int InsetCitation::textString(Buffer const & buf, odocstream & os,
494                        OutputParams const & op) const
495 {
496         return plaintext(buf, os, op);
497 }
498
499
500 // Have to overwrite the default InsetCommand method in order to check that
501 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
502 // citations and then changes his mind, turning natbib support off. The output
503 // should revert to \cite[]{}
504 int InsetCitation::latex(Buffer const & buffer, odocstream & os,
505                          OutputParams const &) const
506 {
507         biblio::CiteEngine cite_engine = buffer.params().getEngine();
508         // FIXME UNICODE
509         docstring const cite_str = from_utf8(
510                 asValidLatexCommand(getCmdName(), cite_engine));
511
512         os << "\\" << cite_str;
513
514         docstring const & before = getParam("before");
515         docstring const & after  = getParam("after");
516         if (!before.empty() && cite_engine != biblio::ENGINE_BASIC)
517                 os << '[' << before << "][" << after << ']';
518         else if (!after.empty())
519                 os << '[' << after << ']';
520
521         os << '{' << cleanupWhitespace(getParam("key")) << '}';
522
523         return 0;
524 }
525
526
527 void InsetCitation::validate(LaTeXFeatures & features) const
528 {
529         switch (features.bufferParams().getEngine()) {
530         case biblio::ENGINE_BASIC:
531                 break;
532         case biblio::ENGINE_NATBIB_AUTHORYEAR:
533         case biblio::ENGINE_NATBIB_NUMERICAL:
534                 features.require("natbib");
535                 break;
536         case biblio::ENGINE_JURABIB:
537                 features.require("jurabib");
538                 break;
539         }
540 }
541
542
543 } // namespace lyx