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