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