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