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