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