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